diff --git a/.changeset/flag-dependency-own-context.md b/.changeset/flag-dependency-own-context.md new file mode 100644 index 00000000..a92795e0 --- /dev/null +++ b/.changeset/flag-dependency-own-context.md @@ -0,0 +1,5 @@ +--- +"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`. diff --git a/.changeset/flags-known-absent-property-keys.md b/.changeset/flags-known-absent-property-keys.md new file mode 100644 index 00000000..10ed4229 --- /dev/null +++ b/.changeset/flags-known-absent-property-keys.md @@ -0,0 +1,5 @@ +--- +"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. diff --git a/.changeset/unusable-group-key.md b/.changeset/unusable-group-key.md new file mode 100644 index 00000000..7740598b --- /dev/null +++ b/.changeset/unusable-group-key.md @@ -0,0 +1,5 @@ +--- +"posthog-ruby": patch +--- + +Treat an empty, `nil`, boolean, array, or hash group key as no group key during local flag evaluation, as the server does. A condition aggregated on that group type is skipped, and a flag whose conditions are all skipped resolves to `false` locally instead of bucketing on the key's string form. diff --git a/.github/workflows/sdk-compliance.yml b/.github/workflows/sdk-compliance.yml index 84669d9f..ba5be781 100644 --- a/.github/workflows/sdk-compliance.yml +++ b/.github/workflows/sdk-compliance.yml @@ -22,11 +22,11 @@ jobs: dockerfile: sdk_compliance_adapter/Dockerfile - mode: sync dockerfile: sdk_compliance_adapter/Dockerfile.sync - 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-ruby-${{ matrix.mode }} sdk-type: server continue-on-error: true diff --git a/lib/posthog/client.rb b/lib/posthog/client.rb index 091e5f74..c2a278fc 100644 --- a/lib/posthog/client.rb +++ b/lib/posthog/client.rb @@ -384,35 +384,12 @@ def capture(attrs) 'avoids a second `/flags` request per capture and guarantees the event carries the ' \ 'exact flag values your code branched on.' ) - # Handle different types of send_feature_flags parameter - case send_feature_flags_param - when true - # Backward compatibility: simple boolean - feature_variants = @feature_flags_poller.get_feature_variants(attrs[:distinct_id], attrs[:groups] || {}) - when Hash - # Hash with options - options = SendFeatureFlagsOptions.from_hash(send_feature_flags_param) - feature_variants = @feature_flags_poller.get_feature_variants( - attrs[:distinct_id], - attrs[:groups] || {}, - options ? options.person_properties : {}, - options ? options.group_properties : {}, - options ? options.only_evaluate_locally : false - ) - when SendFeatureFlagsOptions - # SendFeatureFlagsOptions object - feature_variants = @feature_flags_poller.get_feature_variants( - attrs[:distinct_id], - attrs[:groups] || {}, - send_feature_flags_param.person_properties, - send_feature_flags_param.group_properties, - send_feature_flags_param.only_evaluate_locally || false - ) - else - # Invalid type, treat as false - feature_variants = nil - end - + options = case send_feature_flags_param + when true then SendFeatureFlagsOptions.new + when Hash then SendFeatureFlagsOptions.from_hash(send_feature_flags_param) + when SendFeatureFlagsOptions then send_feature_flags_param + end + feature_variants = options && _capture_feature_variants(attrs[:distinct_id], attrs[:groups], options) attrs[:feature_variants] = feature_variants if feature_variants end @@ -535,6 +512,10 @@ def queued_messages # @param person_properties [Hash] Properties to use when evaluating the user locally or remotely. # @param group_properties [Hash] Properties to use when evaluating groups locally or remotely. # @param only_evaluate_locally [Boolean] Skip the remote /flags call. + # @param person_property_keys_known_absent [Array, Set, nil] Person property + # keys known to be absent. See {#evaluate_flags}. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # Group property keys known to be absent, by group type. See {#evaluate_flags}. # @param send_feature_flag_events [Boolean] Whether to capture `$feature_flag_called` for this access. # @return [Boolean, nil] Whether the flag is enabled, or nil when the flag could not be evaluated. # TODO: In future version, rename to `feature_flag_enabled?` @@ -545,7 +526,9 @@ def is_feature_enabled( # rubocop:disable Naming/PredicatePrefix person_properties: {}, group_properties: {}, only_evaluate_locally: false, - send_feature_flag_events: true + send_feature_flag_events: true, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) _emit_deprecation( :is_feature_enabled, @@ -558,7 +541,9 @@ def is_feature_enabled( # rubocop:disable Naming/PredicatePrefix result = _get_feature_flag_result( flag_key, distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties, - only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events + only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events, + person_property_keys_known_absent: person_property_keys_known_absent, + group_property_keys_known_absent: group_property_keys_known_absent ) response = result&.value return nil if response.nil? @@ -582,6 +567,10 @@ def get_remote_config_payload(flag_key) # @param [Hash] person_properties key-value pairs of properties to associate with the user. # @param [Hash] group_properties # @param only_evaluate_locally [Boolean] Skip the remote /flags call. + # @param person_property_keys_known_absent [Array, Set, nil] Person property + # keys known to be absent. See {#evaluate_flags}. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # Group property keys known to be absent, by group type. See {#evaluate_flags}. # @param send_feature_flag_events [Boolean] Whether to capture `$feature_flag_called` for this access. # # @return [String, Boolean, nil] The value of the feature flag @@ -605,7 +594,9 @@ def get_feature_flag( person_properties: {}, group_properties: {}, only_evaluate_locally: false, - send_feature_flag_events: true + send_feature_flag_events: true, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) _emit_deprecation( :get_feature_flag, @@ -617,7 +608,9 @@ def get_feature_flag( result = _get_feature_flag_result( key, distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties, - only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events + only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events, + person_property_keys_known_absent: person_property_keys_known_absent, + group_property_keys_known_absent: group_property_keys_known_absent ) result&.value end @@ -630,6 +623,10 @@ def get_feature_flag( # @param person_properties [Hash] Properties to use when evaluating the user locally or remotely. # @param group_properties [Hash] Properties to use when evaluating groups locally or remotely. # @param only_evaluate_locally [Boolean] Skip the remote /flags call. + # @param person_property_keys_known_absent [Array, Set, nil] Person property + # keys known to be absent. See {#evaluate_flags}. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # Group property keys known to be absent, by group type. See {#evaluate_flags}. # @param send_feature_flag_events [Boolean] Whether to capture `$feature_flag_called` for this access. # @return [PostHog::FeatureFlagResult, nil] def get_feature_flag_result( @@ -639,7 +636,9 @@ def get_feature_flag_result( person_properties: {}, group_properties: {}, only_evaluate_locally: false, - send_feature_flag_events: true + send_feature_flag_events: true, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) _emit_deprecation( :get_feature_flag_result, @@ -653,7 +652,9 @@ def get_feature_flag_result( _get_feature_flag_result( key, distinct_id, groups: groups, person_properties: person_properties, group_properties: group_properties, - only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events + only_evaluate_locally: only_evaluate_locally, send_feature_flag_events: send_feature_flag_events, + person_property_keys_known_absent: person_property_keys_known_absent, + group_property_keys_known_absent: group_property_keys_known_absent ) end @@ -676,6 +677,16 @@ def get_feature_flag_result( # @param [Array, nil] flag_keys When set, scopes evaluation to only these flag keys. # An empty array returns an empty snapshot without evaluating flags; +nil+ evaluates all flags. # Distinct from {FeatureFlagEvaluations#only}, which filters the already-fetched snapshot in memory. + # @param [Array, Set, nil] person_property_keys_known_absent Person property keys + # the caller knows are absent for this evaluation. A listed key is absent even when +person_properties+ + # has a value for it, so local evaluation resolves it definitively: +is_not_set+ and the negated operators + # (+is_not+, +not_icontains+, +not_starts_with+, +not_ends_with+, +not_regex+) match, and every other + # operator doesn't. Keys starting with +__posthog_person_metadata__+ are ignored. Sent to +/flags+ on remote + # evaluation. At most 1000 keys, counting duplicates; a longer list raises +ArgumentError+ and is never + # truncated. + # @param [Hash{String, Symbol => Array, Set}, nil] group_property_keys_known_absent + # Group property keys known to be absent, by group type name. Each group type's keys apply only to that + # group type and follow the same rules and 1000-key limit as +person_property_keys_known_absent+. # @return [PostHog::FeatureFlagEvaluations] def evaluate_flags( distinct_id, @@ -684,7 +695,9 @@ def evaluate_flags( group_properties: {}, only_evaluate_locally: false, disable_geoip: nil, - flag_keys: nil + flag_keys: nil, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) host = _feature_flag_evaluations_host @@ -694,6 +707,9 @@ def evaluate_flags( return FeatureFlagEvaluations.new(host: host, distinct_id: distinct_id, flags: {}, groups: groups) if @disabled + known_absent = KnownAbsentPropertyKeys.build(person_property_keys_known_absent, + group_property_keys_known_absent) + if flag_keys && flag_keys.empty? return FeatureFlagEvaluations.new( host: host, distinct_id: distinct_id, flags: {}, groups: groups, disable_geoip: disable_geoip @@ -719,7 +735,8 @@ def evaluate_flags( begin match = @feature_flags_poller.send( :_compute_flag_locally, - definition, distinct_id, groups, person_properties, group_properties, snapshot: definition_snapshot + definition, distinct_id, groups, person_properties, group_properties, + snapshot: definition_snapshot, known_absent: known_absent ) rescue PostHog::RequiresServerEvaluation, PostHog::InconclusiveMatchError => e unresolved_flags[key.to_s] = e.reason @@ -770,7 +787,8 @@ def evaluate_flags( minimal_flag_called_events = false begin flags_response = @feature_flags_poller.get_flags( - distinct_id, groups, person_properties, group_properties, flag_keys, disable_geoip + distinct_id, groups, person_properties, group_properties, flag_keys, disable_geoip, + known_absent: known_absent ) minimal_flag_called_events = flags_response[:minimalFlagCalledEvents] == true request_id = flags_response[:requestId] @@ -827,6 +845,10 @@ def evaluate_flags( # @param [Hash] person_properties key-value pairs of properties to associate with the user. # @param [Hash] group_properties # @param only_evaluate_locally [Boolean] Skip the remote /flags call. + # @param person_property_keys_known_absent [Array, Set, nil] Person property + # keys known to be absent. See {#evaluate_flags}. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # 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( @@ -834,15 +856,19 @@ def get_all_flags( groups: {}, person_properties: {}, group_properties: {}, - only_evaluate_locally: false + only_evaluate_locally: false, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) return {} if @disabled + known_absent = KnownAbsentPropertyKeys.build(person_property_keys_known_absent, + group_property_keys_known_absent) groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) @feature_flags_poller.get_all_flags(distinct_id, groups, person_properties, group_properties, - only_evaluate_locally) + only_evaluate_locally, known_absent: known_absent) end # Returns payload for a given feature flag @@ -857,6 +883,10 @@ def get_all_flags( # @param person_properties [Hash] key-value pairs of properties to associate with the user. # @param group_properties [Hash] # @param only_evaluate_locally [Boolean] + # @param person_property_keys_known_absent [Array, Set, nil] Person property + # keys known to be absent. See {#evaluate_flags}. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # Group property keys known to be absent, by group type. See {#evaluate_flags}. # @return [Object, nil] The parsed payload for the matched flag value. # # @deprecated Use {#evaluate_flags} and {FeatureFlagEvaluations#get_flag_payload} instead. @@ -867,7 +897,9 @@ def get_feature_flag_payload( groups: {}, person_properties: {}, group_properties: {}, - only_evaluate_locally: false + only_evaluate_locally: false, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) _emit_deprecation( :get_feature_flag_payload, @@ -879,11 +911,14 @@ def get_feature_flag_payload( return nil if @disabled key = key.to_s + known_absent = KnownAbsentPropertyKeys.build(person_property_keys_known_absent, + group_property_keys_known_absent) groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) @feature_flags_poller.get_feature_flag_payload(key, distinct_id, match_value, groups, person_properties, - group_properties, only_evaluate_locally) + group_properties, only_evaluate_locally, + known_absent: known_absent) end # Returns all flags and payloads for a given user @@ -897,21 +932,30 @@ def get_feature_flag_payload( # @param person_properties [Hash] key-value pairs of properties to associate with the user. # @param group_properties [Hash] # @param only_evaluate_locally [Boolean] Skip the remote /flags call. + # @param person_property_keys_known_absent [Array, Set, nil] Person property + # keys known to be absent. See {#evaluate_flags}. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # Group property keys known to be absent, by group type. See {#evaluate_flags}. # def get_all_flags_and_payloads( distinct_id, groups: {}, person_properties: {}, group_properties: {}, - only_evaluate_locally: false + only_evaluate_locally: false, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) return { featureFlags: {}, featureFlagPayloads: {} } if @disabled + known_absent = KnownAbsentPropertyKeys.build(person_property_keys_known_absent, + group_property_keys_known_absent) groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) response = @feature_flags_poller.get_all_flags_and_payloads( - distinct_id, groups, person_properties, group_properties, only_evaluate_locally + distinct_id, groups, person_properties, group_properties, only_evaluate_locally, + known_absent: known_absent ) # Remove internal information @@ -1154,18 +1198,23 @@ def _get_feature_flag_result( person_properties: {}, group_properties: {}, only_evaluate_locally: false, - send_feature_flag_events: true + send_feature_flag_events: true, + person_property_keys_known_absent: nil, + group_property_keys_known_absent: nil ) return nil if @disabled key = key.to_s + known_absent = KnownAbsentPropertyKeys.build(person_property_keys_known_absent, + group_property_keys_known_absent) groups, person_properties, group_properties = add_local_person_and_group_properties( groups, person_properties, group_properties ) feature_flag_response, flag_was_locally_evaluated, request_id, evaluated_at, feature_flag_error, payload, has_experiment, minimal_flag_called_events = @feature_flags_poller.get_feature_flag( - key, distinct_id, groups, person_properties, group_properties, only_evaluate_locally + key, distinct_id, groups, person_properties, group_properties, only_evaluate_locally, + known_absent: known_absent ) if send_feature_flag_events properties = { @@ -1324,6 +1373,25 @@ def shutdown? @shutdown_mutex.synchronize { @shutdown } end + def _capture_feature_variants(distinct_id, groups, options) + begin + known_absent = KnownAbsentPropertyKeys.build(options.person_property_keys_known_absent, + options.group_property_keys_known_absent) + rescue ArgumentError => e + # Capture is fire-and-forget, so an invalid listing drops the flags rather than the event. + logger.warn("[FEATURE FLAGS] Ignoring send_feature_flags on capture(): #{e.message}") + return nil + end + + groups, person_properties, group_properties = add_local_person_and_group_properties( + groups, options.person_properties, options.group_properties + ) + @feature_flags_poller.get_feature_variants( + distinct_id, groups, person_properties, group_properties, options.only_evaluate_locally || false, + known_absent: known_absent + ) + end + def add_local_person_and_group_properties(groups, person_properties, group_properties) groups, person_properties, group_properties = normalize_flag_evaluation_inputs( groups, person_properties, group_properties diff --git a/lib/posthog/feature_flags.rb b/lib/posthog/feature_flags.rb index 54f012c9..ff71f9be 100644 --- a/lib/posthog/feature_flags.rb +++ b/lib/posthog/feature_flags.rb @@ -11,6 +11,7 @@ require 'posthog/flag_definition_cache' require 'posthog/unresolved_flag_reason' require 'posthog/flag_evaluation_errors' +require 'posthog/known_absent_property_keys' require 'digest' module PostHog @@ -36,6 +37,10 @@ class FeatureFlagsPoller NUMERIC_OPERATORS = %w[gt gte lt lte].freeze DATE_OPERATORS = %w[is_date_before is_date_after].freeze SEMVER_COMPARISON_OPERATORS = %w[semver_eq semver_neq semver_gt semver_gte semver_lt semver_lte].freeze + # Every property-filter operator this SDK evaluates locally. + LOCAL_OPERATORS = (%w[exact is_not is_set is_not_set icontains not_icontains starts_with not_starts_with + ends_with not_ends_with semver_tilde semver_caret semver_wildcard] + + REGEX_OPERATORS + NUMERIC_OPERATORS + DATE_OPERATORS + SEMVER_COMPARISON_OPERATORS).freeze # @param polling_interval [Integer, nil] Seconds between local feature flag definition polls. # Defaults to {Defaults::FeatureFlags::POLLING_INTERVAL_SECONDS}. @@ -147,7 +152,8 @@ def get_feature_variants( person_properties = {}, group_properties = {}, only_evaluate_locally = false, - raise_on_error = false + raise_on_error = false, + known_absent: nil ) groups, person_properties, group_properties = normalize_flag_evaluation_inputs( groups, person_properties, group_properties @@ -159,7 +165,8 @@ def get_feature_variants( person_properties, group_properties, only_evaluate_locally, - raise_on_error + raise_on_error, + known_absent: known_absent ) if flags_data.key?(:featureFlags) @@ -175,13 +182,15 @@ def get_feature_payloads( groups = {}, person_properties = {}, group_properties = {}, - _only_evaluate_locally = false + _only_evaluate_locally = false, + known_absent: nil ) flags_data = get_all_flags_and_payloads( distinct_id, groups, person_properties, - group_properties + group_properties, + known_absent: known_absent ) if flags_data.key?(:featureFlagPayloads) @@ -193,7 +202,7 @@ def get_feature_payloads( end def get_flags(distinct_id, groups = {}, person_properties = {}, group_properties = {}, flag_keys = nil, - disable_geoip = nil) + disable_geoip = nil, known_absent: nil) flag_keys = flag_keys.map(&:to_s) if flag_keys.is_a?(Array) request_data = { distinct_id: distinct_id, @@ -201,6 +210,7 @@ def get_flags(distinct_id, groups = {}, person_properties = {}, group_properties person_properties: person_properties, group_properties: group_properties } + request_data.merge!(known_absent.request_fields) if known_absent request_data[:flag_keys_to_evaluate] = flag_keys if flag_keys && !flag_keys.empty? # The flags endpoint treats an omitted/null value as false; serialize that same default explicitly. request_data[:geoip_disable] = disable_geoip.nil? ? false : disable_geoip @@ -241,7 +251,8 @@ def get_feature_flag( person_properties = {}, group_properties = {}, only_evaluate_locally = false, - snapshot: nil + snapshot: nil, + known_absent: nil ) key = key.to_s @@ -256,7 +267,7 @@ def get_feature_flag( unless feature_flag.nil? begin response = _compute_flag_locally(feature_flag, distinct_id, groups, person_properties, group_properties, - snapshot: snapshot) + snapshot: snapshot, known_absent: known_absent) payload = _compute_flag_payload_locally(key, response, snapshot: snapshot) unless response.nil? logger.debug "Successfully computed flag locally: #{key} -> #{response}" rescue RequiresServerEvaluation, InconclusiveMatchError => e @@ -286,7 +297,7 @@ def get_feature_flag( begin errors = [] flags_data = get_all_flags_and_payloads(distinct_id, groups, person_properties, group_properties, - only_evaluate_locally, true) + only_evaluate_locally, true, known_absent: known_absent) if flags_data.key?(:featureFlags) flags = stringify_keys(flags_data[:featureFlags] || {}) payloads = stringify_keys(flags_data[:featureFlagPayloads] || {}) @@ -340,7 +351,8 @@ def get_all_flags( groups = {}, person_properties = {}, group_properties = {}, - only_evaluate_locally = false + only_evaluate_locally = false, + known_absent: nil ) if @quota_limited.true? logger.debug 'Not fetching flags from server - quota limited' @@ -353,7 +365,8 @@ def get_all_flags( groups, person_properties, group_properties, - only_evaluate_locally + only_evaluate_locally, + known_absent: known_absent ) response[:featureFlags] @@ -365,7 +378,8 @@ def get_all_flags_and_payloads( person_properties = {}, group_properties = {}, only_evaluate_locally = false, - raise_on_error = false + raise_on_error = false, + known_absent: nil ) load_feature_flags snapshot = _evaluation_snapshot @@ -378,7 +392,7 @@ def get_all_flags_and_payloads( snapshot[:flags].each do |flag| match_value = _compute_flag_locally(flag, distinct_id, groups, person_properties, group_properties, - snapshot: snapshot) + snapshot: snapshot, known_absent: known_absent) flags[flag[:key]] = match_value match_payload = _compute_flag_payload_locally(flag[:key], match_value, snapshot: snapshot) payloads[flag[:key]] = match_payload if match_payload @@ -397,7 +411,8 @@ def get_all_flags_and_payloads( if fallback_to_server && !only_evaluate_locally begin - flags_and_payloads = get_flags(distinct_id, groups, person_properties, group_properties) + flags_and_payloads = get_flags(distinct_id, groups, person_properties, group_properties, + known_absent: known_absent) flag_details = flags_and_payloads[:flags] errors_while_computing = flags_and_payloads[:errorsWhileComputingFlags] || false quota_limited = flags_and_payloads[:quotaLimited] @@ -460,7 +475,8 @@ def get_feature_flag_payload( groups = {}, person_properties = {}, group_properties = {}, - only_evaluate_locally = false + only_evaluate_locally = false, + known_absent: nil ) key = key.to_s load_feature_flags @@ -474,13 +490,15 @@ def get_feature_flag_payload( person_properties, group_properties, true, - snapshot: snapshot + snapshot: snapshot, + known_absent: known_absent )[0] end response = nil response = _compute_flag_payload_locally(key, match_value, snapshot: snapshot) unless match_value.nil? if response.nil? && !only_evaluate_locally - flags_payloads = get_feature_payloads(distinct_id, groups, person_properties, group_properties) + flags_payloads = get_feature_payloads(distinct_id, groups, person_properties, group_properties, + known_absent: known_absent) response = flags_payloads[key.downcase] || nil end response @@ -499,6 +517,12 @@ def shutdown_poller # Class methods + # 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) + (group_key.is_a?(String) && !group_key.empty?) || group_key.is_a?(Numeric) + end + def self.pick_unresolved_reason(current, reason) return reason if current.nil? @@ -758,13 +782,27 @@ def self.exact_property_match?(filter, value, property_matching_version) private_class_method :boolean_like?, :legacy_truthy?, :sorted_composite, :property_string, :exact_property_match? - def self.match_property(property, property_values, cohort_properties = {}, property_matching_version: 1) + # @param known_absent_scope [PostHog::KnownAbsentPropertyKeys::Scope, nil] Keys of property_values known + # to be absent. A filter the scope covers resolves definitively by operator, even when property_values + # has a value for it. + def self.match_property(property, property_values, cohort_properties = {}, property_matching_version: 1, + known_absent_scope: nil) # only looks for matches where key exists in property_values # Handle cohort properties if extract_value(property, :type) == 'cohort' return match_cohort(property, property_values, cohort_properties, - property_matching_version: property_matching_version) + property_matching_version: property_matching_version, + known_absent_scope: known_absent_scope) + end + + if known_absent_scope&.covers?(property) + # Like the flags service, a listed key resolves without parsing the condition value. An operator + # this SDK does not implement stays inconclusive, so it still falls back to the server. + operator = property[:operator] || property['operator'] || 'exact' + assert_operator_supported(operator) + assert_condition_value_present(property, operator) + return KnownAbsentPropertyKeys::MATCHING_OPERATORS.include?(operator) end begin @@ -776,6 +814,17 @@ def self.match_property(property, property_values, cohort_properties = {}, prope end end + # An omitted or JSON null condition value leaves a value-requiring operator inconclusive, even for a + # known-absent key, because is_not would otherwise match. + def self.assert_condition_value_present(property, operator) + return if %w[is_set is_not_set].include?(operator) + return unless (property.key?(:value) ? property[:value] : property['value']).nil? + + raise InconclusiveMatchError.new("Missing condition value for operator #{operator}", + reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + end + private_class_method :assert_condition_value_present + def self.match_property_value(property, property_values, property_matching_version) key = (property[:key] || property['key']).to_sym value = property.key?(:value) ? property[:value] : property['value'] @@ -866,15 +915,20 @@ def self.match_property_value(property, property_values, property_matching_versi end private_class_method :match_property_value + def self.assert_operator_supported(operator) + return if LOCAL_OPERATORS.include?(operator) + + raise InconclusiveMatchError.new("Unknown operator: #{operator}", + reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + end + # Raises an unsupported_definition error when local evaluation cannot use the filter, whatever # the call passes: an unknown operator, or a filter value that the operator cannot parse. def self.assert_filter_supported(property) value = property.key?(:value) ? property[:value] : property['value'] operator = property[:operator] || property['operator'] || 'exact' + assert_operator_supported(operator) case operator - when 'exact', 'is_not', 'is_set', 'is_not_set', 'icontains', 'not_icontains', 'starts_with', - 'not_starts_with', 'ends_with', 'not_ends_with' - nil when *REGEX_OPERATORS # An empty input is the most portable one, so this raises only for a pattern that needs the # server whatever the value. Compile without matching, so a server-supplied pattern never runs @@ -893,9 +947,6 @@ def self.assert_filter_supported(property) semver_caret_bounds(value) when 'semver_wildcard' semver_wildcard_bounds(value) - else - raise InconclusiveMatchError.new("Unknown operator: #{operator}", - reason: UnresolvedFlagReason::UNSUPPORTED_DEFINITION) end end @@ -1070,7 +1121,8 @@ def self.regex_repetition_end(characters, index) end private_class_method :regex_repetition_end - def self.match_cohort(property, property_values, cohort_properties, property_matching_version: 1) + def self.match_cohort(property, property_values, cohort_properties, property_matching_version: 1, + known_absent_scope: nil) # Cohort properties are in the form of property groups like this: # { # "cohort_id" => { @@ -1091,10 +1143,12 @@ def self.match_cohort(property, property_values, cohort_properties, property_mat end match_property_group(property_group, property_values, cohort_properties, - property_matching_version: property_matching_version) + property_matching_version: property_matching_version, + known_absent_scope: known_absent_scope) end - def self.match_property_group(property_group, property_values, cohort_properties, property_matching_version: 1) + def self.match_property_group(property_group, property_values, cohort_properties, property_matching_version: 1, + known_absent_scope: nil) return true if property_group.nil? || property_group.empty? group_type = extract_value(property_group, :type) @@ -1105,12 +1159,14 @@ def self.match_property_group(property_group, property_values, cohort_properties if nested_property_group?(properties) property_group_items_match?(properties, group_type) do |group| match_property_group(group, property_values, cohort_properties, - property_matching_version: property_matching_version) + property_matching_version: property_matching_version, + known_absent_scope: known_absent_scope) end else property_group_items_match?(properties, group_type) do |prop| matches = match_property(prop, property_values, cohort_properties, - property_matching_version: property_matching_version) + property_matching_version: property_matching_version, + known_absent_scope: known_absent_scope) extract_value(prop, :negation) ? !matches : matches end end @@ -1173,9 +1229,14 @@ def self.property_group_items_match?(items, group_type) # @param distinct_id [String] The distinct ID being evaluated # @param properties [Hash] Person properties for evaluation # @param cohort_properties [Hash] Cohort properties for evaluation + # @param context [Hash, nil] The evaluation inputs of the top-level flag. Each dependency is evaluated from + # them like a standalone flag, with its own aggregation, bucketing identifier and properties, as the flags + # service does. # @return [Boolean] True if all dependencies in the chain evaluate to true, false otherwise - def evaluate_flag_dependency(property, evaluation_cache, distinct_id, properties, cohort_properties, - snapshot: _evaluation_snapshot) + def evaluate_flag_dependency(property, evaluation_cache, distinct_id, properties, _cohort_properties = {}, + snapshot: _evaluation_snapshot, context: nil) + context ||= { distinct_id: distinct_id, groups: {}, person_properties: properties, group_properties: {}, + known_absent: nil } if snapshot[:flags_by_key].nil? || evaluation_cache.nil? # Cannot evaluate flag dependencies without required context raise InconclusiveMatchError.new( @@ -1211,13 +1272,10 @@ def evaluate_flag_dependency(property, evaluation_cache, distinct_id, properties else # Recursively evaluate the dependency using existing instance method begin - dep_result = match_feature_flag_properties( - dep_flag, - distinct_id, - properties, - evaluation_cache, - cohort_properties, - snapshot: snapshot + dep_result = _compute_flag_locally( + dep_flag, context[:distinct_id], context[:groups], context[:person_properties], + context[:group_properties], + snapshot: snapshot, known_absent: context[:known_absent], evaluation_cache: evaluation_cache ) evaluation_cache[dep_flag_key] = dep_result rescue RequiresServerEvaluation => e @@ -1373,7 +1431,7 @@ def self.unsupported_filter?(property) end private_class_method :extract_value, :find_cohort_property, :nested_property_group?, - :property_group_items_match?, :assert_filter_supported, + :property_group_items_match?, :assert_filter_supported, :assert_operator_supported, :unsupported_property?, :unsupported_property_group?, :unsupported_filter? # Publish/capture all matching state together so a poll cannot switch semantics @@ -1383,7 +1441,7 @@ def _evaluation_snapshot end def _compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {}, group_properties = {}, - snapshot: _evaluation_snapshot) + snapshot: _evaluation_snapshot, known_absent: nil, evaluation_cache: nil) # An inactive flag is false whatever its experience continuity setting. return false unless flag[:active] @@ -1392,8 +1450,9 @@ def _compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {} reason: UnresolvedFlagReason::EXPERIENCE_CONTINUITY) end - # Create evaluation cache for flag dependencies - evaluation_cache = {} + evaluation_cache ||= {} + context = { distinct_id: distinct_id, groups: groups, person_properties: person_properties, + group_properties: group_properties, known_absent: known_absent } flag_filters = flag[:filters] || {} @@ -1406,7 +1465,9 @@ def _compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {} return match_feature_flag_properties(flag, distinct_id, local_person_properties, evaluation_cache, snapshot[:cohorts], groups: groups, group_properties: group_properties, - snapshot: snapshot) + snapshot: snapshot, known_absent: known_absent, + known_absent_scope: known_absent&.person_scope, + context: context) end group_name = snapshot[:group_type_mapping][aggregation_group_type_index.to_s.to_sym] @@ -1422,8 +1483,8 @@ def _compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {} group_name_symbol = group_name.to_sym - unless groups.key?(group_name_symbol) - # Group flags are never enabled if appropriate `groups` aren't passed in + unless FeatureFlagsPoller.usable_group_key?(groups[group_name_symbol]) + # Group flags are never enabled if a usable group key isn't passed in # don't failover to `/flags/`, since response will be the same logger.warn "[FEATURE FLAGS] Can't compute group feature flag: #{flag[:key]} without group names passed in" return false @@ -1432,7 +1493,10 @@ def _compute_flag_locally(flag, distinct_id, groups = {}, person_properties = {} focused_group_properties = group_properties[group_name_symbol] match_feature_flag_properties(flag, groups[group_name_symbol], focused_group_properties, evaluation_cache, snapshot[:cohorts], groups: groups, group_properties: group_properties, - snapshot: snapshot) + snapshot: snapshot, known_absent: known_absent, + known_absent_scope: known_absent&.group_scope( + group_name, aggregation_group_type_index + ), context: context) end def _compute_flag_payload_locally(key, match_value, snapshot: _evaluation_snapshot) @@ -1448,8 +1512,11 @@ def _compute_flag_payload_locally(key, match_value, snapshot: _evaluation_snapsh response end + # known_absent_scope holds the listed keys for `properties`; known_absent holds every listing, so a + # condition aggregated by another group type can use that group type's keys. def match_feature_flag_properties(flag, distinct_id, properties, evaluation_cache, cohort_properties = {}, - groups: {}, group_properties: {}, snapshot: _evaluation_snapshot) + groups: {}, group_properties: {}, snapshot: _evaluation_snapshot, + known_absent: nil, known_absent_scope: nil, context: nil) flag_filters = flag[:filters] || {} # Holdouts precede release conditions: a held-out identifier is excluded from @@ -1474,6 +1541,7 @@ def match_feature_flag_properties(flag, distinct_id, properties, evaluation_cach effective_properties = properties effective_bucketing = distinct_id + effective_known_absent_scope = known_absent_scope # Mixed-override path: condition-level aggregation differs from flag-level. # This assumes flag-level aggregation is nil for mixed flags. @@ -1482,7 +1550,7 @@ def match_feature_flag_properties(flag, distinct_id, properties, evaluation_cach # Person condition under a mixed flag — caller already passed person props/bucketing. else group_name = snapshot[:group_type_mapping][condition_aggregation.to_s.to_sym] - if group_name.nil? || !groups.key?(group_name.to_sym) + if group_name.nil? || !FeatureFlagsPoller.usable_group_key?(groups[group_name.to_sym]) logger.debug do "[FEATURE FLAGS] Skipping group condition for flag '#{flag[:key]}': " \ "group type index #{condition_aggregation} not available" @@ -1497,11 +1565,13 @@ def match_feature_flag_properties(flag, distinct_id, properties, evaluation_cach end effective_properties = group_properties[group_name.to_sym] effective_bucketing = groups[group_name.to_sym] + effective_known_absent_scope = known_absent&.group_scope(group_name, condition_aggregation) end end case condition_match_outcome(flag, effective_bucketing, condition, effective_properties, evaluation_cache, - cohort_properties, snapshot: snapshot) + cohort_properties, snapshot: snapshot, context: context, + known_absent_scope: effective_known_absent_scope) when :match variant_override = condition[:variant] flag_multivariate = flag_filters[:multivariate] || {} @@ -1562,7 +1632,7 @@ def condition_match(flag, distinct_id, condition, properties, evaluation_cache, # Distinguishing :no_match from :out_of_rollout_bound lets the caller implement the # early_exit behavior (mirrors the server-side Rust evaluation engine). def condition_match_outcome(flag, distinct_id, condition, properties, evaluation_cache, cohort_properties = {}, - snapshot: _evaluation_snapshot) + snapshot: _evaluation_snapshot, known_absent_scope: nil, context: nil) rollout_percentage = condition[:rollout_percentage] unless (condition[:properties] || []).empty? @@ -1574,10 +1644,11 @@ def condition_match_outcome(flag, distinct_id, condition, properties, evaluation matches = if prop[:type] == 'flag' evaluate_flag_dependency(prop, evaluation_cache, distinct_id, properties, cohort_properties, - snapshot: snapshot) + snapshot: snapshot, context: context) else FeatureFlagsPoller.match_property(prop, properties, cohort_properties, - property_matching_version: snapshot[:property_matching_version]) + property_matching_version: snapshot[:property_matching_version], + known_absent_scope: known_absent_scope) end return :no_match unless matches rescue RequiresServerEvaluation => e diff --git a/lib/posthog/known_absent_property_keys.rb b/lib/posthog/known_absent_property_keys.rb new file mode 100644 index 00000000..824fc067 --- /dev/null +++ b/lib/posthog/known_absent_property_keys.rb @@ -0,0 +1,136 @@ +# frozen_string_literal: true + +module PostHog + # Person and group property keys the caller knows are absent for one flag evaluation. + # + # @api private + class KnownAbsentPropertyKeys + # The flags service rejects a longer list, counting duplicates, per group type for groups. + MAX_KEYS = 1000 + PERSON_FIELD = 'person_property_keys_known_absent' + GROUP_FIELD = 'group_property_keys_known_absent' + # Persons-table fields such as `created_at` use this prefix and are never hidden by known absence. + PERSON_METADATA_PREFIX = '__posthog_person_metadata__' + # A listed key matches these operators and no others. + MATCHING_OPERATORS = %w[is_not_set is_not not_icontains not_starts_with not_ends_with not_regex].freeze + + # @return [Set] Listed person keys used for local matching. + attr_reader :person_keys + + # Validates and normalizes the public inputs. + # + # @param person_property_keys_known_absent [Array, Set, nil] + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # @return [PostHog::KnownAbsentPropertyKeys, nil] nil when neither input was provided. + # @raise [ArgumentError] when an input has the wrong type or a list holds more than {MAX_KEYS} keys. + def self.build(person_property_keys_known_absent, group_property_keys_known_absent) + return nil if person_property_keys_known_absent.nil? && group_property_keys_known_absent.nil? + + person = if person_property_keys_known_absent.nil? + [] + else + validate_keys(person_property_keys_known_absent, PERSON_FIELD) + end + + groups = {} + unless group_property_keys_known_absent.nil? + unless group_property_keys_known_absent.is_a?(Hash) + raise ArgumentError, "#{GROUP_FIELD} must be a Hash of group type to property keys" + end + + group_property_keys_known_absent.each do |group_type, keys| + unless group_type.is_a?(String) || group_type.is_a?(Symbol) + raise ArgumentError, "#{GROUP_FIELD} must use String or Symbol group types" + end + + field = "#{GROUP_FIELD}[#{group_type}]" + # A String and a Symbol can name the same group type, so their keys are merged before the limit check. + merged = (groups[group_type.to_s] || []) + validate_keys(keys, field) + raise ArgumentError, "#{field} allows at most #{MAX_KEYS} keys, got #{merged.size}" if merged.size > MAX_KEYS + + groups[group_type.to_s] = merged + end + end + + new(person, groups) + end + + def self.validate_keys(keys, field) + raise ArgumentError, "#{field} must be an Array of property keys" unless keys.is_a?(Array) || keys.is_a?(Set) + raise ArgumentError, "#{field} allows at most #{MAX_KEYS} keys, got #{keys.size}" if keys.size > MAX_KEYS + + keys.map do |key| + unless key.is_a?(String) || key.is_a?(Symbol) + raise ArgumentError, "#{field} must contain only String or Symbol keys" + end + + key.to_s + end + end + private_class_method :validate_keys + + def initialize(person, groups) + @person = person + @groups = groups + @person_keys = person.reject { |key| key.start_with?(PERSON_METADATA_PREFIX) }.to_set.freeze + @group_keys = groups.to_h { |group_type, keys| [group_type, keys.to_set.freeze] }.freeze + end + + # @param group_type [String, Symbol] + # @return [Set, nil] Listed keys for that group type only. + def group_keys(group_type) + @group_keys[group_type.to_s] + end + + # @return [Scope] The listed person keys, for filters with `type: "person"`. + def person_scope + Scope.new(person_keys, nil) + end + + # @param group_type [String, Symbol] + # @param group_type_index [Integer, String] The index that group_type maps to. + # @return [Scope] The listed keys for that group type, for group filters of that group type. + def group_scope(group_type, group_type_index) + Scope.new(group_keys(group_type), group_type_index) + end + + # Listed keys for one evaluation scope: person properties, or the properties of one group type. + # Any other filter type, such as `person_metadata`, never resolves from a listing. + class Scope + # @return [Integer, String, nil] The group type index, or nil for the person scope. + attr_reader :group_type_index + + def initialize(keys, group_type_index) + @keys = keys + @group_type_index = group_type_index + end + + # @param aggregation_group_type_index [Integer, String, nil] A flag's aggregation, nil for persons. + def aggregation?(aggregation_group_type_index) + aggregation_group_type_index.to_s == @group_type_index.to_s + end + + # @param property [Hash] A property filter. + # @return [Boolean] Whether the filter's key is listed for this scope and the filter reads this scope. + def covers?(property) + return false unless @keys&.include?((property[:key] || property['key']).to_s) + + type = property[:type] || property['type'] + return type == 'person' if @group_type_index.nil? + + 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)) + end + end + + # @return [Hash] The `/flags` request body fields, omitting a field with nothing listed. + def request_fields + fields = {} + fields[PERSON_FIELD.to_sym] = @person unless @person.empty? + groups = @groups.reject { |_group_type, keys| keys.empty? } + fields[GROUP_FIELD.to_sym] = groups unless groups.empty? + fields + end + end +end diff --git a/lib/posthog/send_feature_flags_options.rb b/lib/posthog/send_feature_flags_options.rb index c94d37fd..53c89037 100644 --- a/lib/posthog/send_feature_flags_options.rb +++ b/lib/posthog/send_feature_flags_options.rb @@ -16,22 +16,43 @@ class SendFeatureFlagsOptions # @return [Hash] Group properties to use for feature flag evaluation. attr_reader :group_properties + # @return [Array, Set, nil] Person property keys known to be absent. + attr_reader :person_property_keys_known_absent + + # @return [Hash{String, Symbol => Array, Set}, nil] Group property keys known to + # be absent, by group type. + attr_reader :group_property_keys_known_absent + # @param only_evaluate_locally [Boolean, nil] Skip remote feature flag evaluation. # @param person_properties [Hash, nil] Person properties to use for feature flag evaluation. # @param group_properties [Hash, nil] Group properties to use for feature flag evaluation. - def initialize(only_evaluate_locally: nil, person_properties: nil, group_properties: nil) + # @param person_property_keys_known_absent [Array, Set, nil] Person property keys + # known to be absent. + # @param group_property_keys_known_absent [Hash{String, Symbol => Array, Set}, nil] + # Group property keys known to be absent, by group type. + def initialize(only_evaluate_locally: nil, person_properties: nil, group_properties: nil, + person_property_keys_known_absent: nil, group_property_keys_known_absent: nil) @only_evaluate_locally = only_evaluate_locally @person_properties = person_properties || {} @group_properties = group_properties || {} + @person_property_keys_known_absent = person_property_keys_known_absent + @group_property_keys_known_absent = group_property_keys_known_absent end # @return [Hash] A hash representation suitable for `capture(send_feature_flags:)`. def to_h - { + hash = { only_evaluate_locally: @only_evaluate_locally, person_properties: @person_properties, group_properties: @group_properties } + unless @person_property_keys_known_absent.nil? + hash[:person_property_keys_known_absent] = @person_property_keys_known_absent + end + unless @group_property_keys_known_absent.nil? + hash[:group_property_keys_known_absent] = @group_property_keys_known_absent + end + hash end # @param hash [Hash] @@ -42,7 +63,11 @@ def self.from_hash(hash) new( only_evaluate_locally: PostHog::Utils.get_by_symbol_or_string_key(hash, :only_evaluate_locally), person_properties: PostHog::Utils.get_by_symbol_or_string_key(hash, :person_properties), - group_properties: PostHog::Utils.get_by_symbol_or_string_key(hash, :group_properties) + group_properties: PostHog::Utils.get_by_symbol_or_string_key(hash, :group_properties), + person_property_keys_known_absent: + PostHog::Utils.get_by_symbol_or_string_key(hash, :person_property_keys_known_absent), + group_property_keys_known_absent: + PostHog::Utils.get_by_symbol_or_string_key(hash, :group_property_keys_known_absent) ) end end diff --git a/public_api_snapshot.txt b/public_api_snapshot.txt index 69779a00..88d7b764 100644 --- a/public_api_snapshot.txt +++ b/public_api_snapshot.txt @@ -12,18 +12,18 @@ instance_method PostHog::Client#clear() instance_method PostHog::Client#dequeue_last_message() instance_method PostHog::Client#emails() instance_method PostHog::Client#enabled?() -instance_method PostHog::Client#evaluate_flags(distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., disable_geoip: ..., flag_keys: ...) +instance_method PostHog::Client#evaluate_flags(distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., disable_geoip: ..., flag_keys: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) instance_method PostHog::Client#feature_flags_loaded?() instance_method PostHog::Client#flush(timeout: ...) -instance_method PostHog::Client#get_all_flags(distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ...) -instance_method PostHog::Client#get_all_flags_and_payloads(distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ...) -instance_method PostHog::Client#get_feature_flag(key, distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., send_feature_flag_events: ...) -instance_method PostHog::Client#get_feature_flag_payload(key, distinct_id, match_value: ..., groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ...) -instance_method PostHog::Client#get_feature_flag_result(key, distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., send_feature_flag_events: ...) +instance_method PostHog::Client#get_all_flags(distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) +instance_method PostHog::Client#get_all_flags_and_payloads(distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) +instance_method PostHog::Client#get_feature_flag(key, distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., send_feature_flag_events: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) +instance_method PostHog::Client#get_feature_flag_payload(key, distinct_id, match_value: ..., groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) +instance_method PostHog::Client#get_feature_flag_result(key, distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., send_feature_flag_events: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) instance_method PostHog::Client#get_remote_config_payload(flag_key) instance_method PostHog::Client#group_identify(attrs) instance_method PostHog::Client#identify(attrs) -instance_method PostHog::Client#is_feature_enabled(flag_key, distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., send_feature_flag_events: ...) +instance_method PostHog::Client#is_feature_enabled(flag_key, distinct_id, groups: ..., person_properties: ..., group_properties: ..., only_evaluate_locally: ..., send_feature_flag_events: ..., person_property_keys_known_absent: ..., group_property_keys_known_absent: ...) instance_method PostHog::Client#queued_messages() instance_method PostHog::Client#reload_feature_flags() instance_method PostHog::Client#shutdown(timeout: ...) @@ -331,8 +331,10 @@ class PostHog::RequiresServerEvaluation < StandardError instance_method PostHog::RequiresServerEvaluation#reason() class PostHog::SendFeatureFlagsOptions instance_method PostHog::SendFeatureFlagsOptions#group_properties() +instance_method PostHog::SendFeatureFlagsOptions#group_property_keys_known_absent() instance_method PostHog::SendFeatureFlagsOptions#only_evaluate_locally() instance_method PostHog::SendFeatureFlagsOptions#person_properties() +instance_method PostHog::SendFeatureFlagsOptions#person_property_keys_known_absent() instance_method PostHog::SendFeatureFlagsOptions#to_h() class_method PostHog::SendFeatureFlagsOptions.from_hash(hash) module PostHog::UnresolvedFlagReason diff --git a/sdk_compliance_adapter/README.md b/sdk_compliance_adapter/README.md index db463020..5c17c122 100644 --- a/sdk_compliance_adapter/README.md +++ b/sdk_compliance_adapter/README.md @@ -28,14 +28,14 @@ effective default rather than changing GeoIP lookup behavior. ## Inventory and interpretation -CI uses published harness **1.32.0**, server wire format, sequential execution, and separate +CI uses published harness **1.34.0**, server wire format, sequential execution, and separate async/sync artifacts. Each profile selects **47** definitions: 30 V0 capture and 17 feature flags. Assertion failures remain advisory; a separate inventory check requires both complete reports. V1, dedicated AI and non-gzip codecs are unsupported and are not advertised. The adapter declares `synchronous_capture` only for sync mode. Published harness -1.32.0 uses that capability to check five distinct events delivered immediately +1.34.0 uses that capability to check five distinct events delivered immediately in five requests, one event per request, with unique UUIDs and no extra request on flush under `capture.batch_format.synchronous_capture_delivers_each_event_immediately`. @@ -55,9 +55,9 @@ already treats omitted/null as false. No public signature or effective privacy default changed, and the adapter does not supply a default option. The reusable workflow is pinned to release commit -`dde638562d33572b5c8ac3a2eafc98b92ffa2261`, whose release inputs pin specs commit +`574c029da75e96d55c11a54d942a6df983a58ea2`, whose release inputs pin specs commit `53e9bc16d14f973809f80049864866d5b6d9bdff`. The published V1 image digest is -`sha256:7eb6c62e2241ddd48a2dfb326652e7933cd2fe26e0ffcad98cd385d603b4eb82`. +`sha256:43f75861fbcf5bc6c3d35511caa2be2d55274054c6071ebeb943aca0bcd0633a`. Actual async and sync reports must each show 47/47 passing to establish compliance; a green advisory job or inventory check alone does not prove this. @@ -80,4 +80,4 @@ SDK_MODE=sync docker compose -f sdk_compliance_adapter/docker-compose.yml up --b For a native launch, unset `STUB` (it disables SDK HTTP), set `RUBYLIB=lib`, and run `ruby sdk_compliance_adapter/adapter.rb` with the desired `PORT` and -`SDK_MODE`. Point harness 1.32.0 at that listener and an available local mock port. +`SDK_MODE`. Point harness 1.34.0 at that listener and an available local mock port. diff --git a/sdk_compliance_adapter/docker-compose.yml b/sdk_compliance_adapter/docker-compose.yml index 1fabbf86..47647d40 100644 --- a/sdk_compliance_adapter/docker-compose.yml +++ b/sdk_compliance_adapter/docker-compose.yml @@ -9,7 +9,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/spec/posthog/feature_flag_input_ownership_spec.rb b/spec/posthog/feature_flag_input_ownership_spec.rb index 9be314c8..432bd8de 100644 --- a/spec/posthog/feature_flag_input_ownership_spec.rb +++ b/spec/posthog/feature_flag_input_ownership_spec.rb @@ -125,7 +125,7 @@ end end - it 'preserves the remote capture flag context without adding group enrichment' do + it 'sends the remote capture flag context with the same group enrichment as evaluate_flags' do properties = { 'company' => { 'unmatched' => false }.freeze }.freeze flags = { person_properties: { 'unmatched' => nil }.freeze, group_properties: properties }.freeze requests = [] @@ -139,7 +139,8 @@ expect(requests.length).to eq(1) expect(requests[0]['groups']).to eq(groups) expect(requests[0]['person_properties']).to eq('unmatched' => nil) - expect(requests[0]['group_properties']).to eq(properties) + expect(requests[0]['group_properties']).to eq('company' => { '$group_key' => 'acme', 'unmatched' => false }) + expect(properties).to eq('company' => { 'unmatched' => false }) end it 'normalizes boolean capture flag inputs once without changing caller groups' do diff --git a/spec/posthog/feature_flags_known_absent_spec.rb b/spec/posthog/feature_flags_known_absent_spec.rb new file mode 100644 index 00000000..ad30390a --- /dev/null +++ b/spec/posthog/feature_flags_known_absent_spec.rb @@ -0,0 +1,916 @@ +# frozen_string_literal: true + +require 'spec_helper' + +module PostHog + describe 'known-absent property keys' do + let(:definitions_endpoint) { 'https://us.i.posthog.com/flags/definitions?token=testsecret&send_cohorts=true' } + let(:flags_endpoint) { 'https://us.i.posthog.com/flags/?v=2' } + let(:remote_response) do + { flags: { 'remote-flag' => { key: 'remote-flag', enabled: true, variant: nil, metadata: { id: 9 } } } } + end + + def flag(key, *properties, **extra) + { id: 1, key: key, active: true, filters: { groups: [{ properties: properties, rollout_percentage: 100 }] } } + .merge(extra) + end + + def person(key, operator, value = nil) + filter = { key: key, operator: operator, type: 'person' } + filter[:value] = value unless value.nil? + filter + end + + def local_client(*flags, cohorts: {}, group_type_mapping: {}) + stub_request(:get, definitions_endpoint).to_return( + status: 200, body: { flags: flags, cohorts: cohorts, group_type_mapping: group_type_mapping }.to_json + ) + stub_request(:post, flags_endpoint).to_return(status: 200, body: remote_response.to_json) + Client.new(api_key: API_KEY, personal_api_key: API_KEY, test_mode: true) + end + + def plan_scope + KnownAbsentPropertyKeys.build(['plan'], nil).person_scope + end + + def flags_request_body + body = nil + expect(WebMock).to(have_requested(:post, flags_endpoint).with { |request| body = JSON.parse(request.body) }) + body + end + + describe 'operator results for a listed key' do + { + ['is_not_set', nil] => true, + ['is_set', nil] => false, + %w[exact pro] => false, + %w[is_not pro] => true, + %w[icontains pro] => false, + %w[not_icontains pro] => true, + %w[starts_with pro] => false, + %w[not_starts_with pro] => true, + %w[ends_with pro] => false, + %w[not_ends_with pro] => true, + ['regex', '^pro'] => false, + ['not_regex', '^pro'] => true, + %w[gt 10] => false, + %w[gte 10] => false, + %w[lt 10] => false, + %w[lte 10] => false, + ['is_date_before', '2025-01-01T10:00:00Z'] => false, + ['is_date_after', '2025-01-01T10:00:00Z'] => false, + ['semver_eq', '1.2.3'] => false, + ['semver_neq', '1.2.3'] => false, + ['semver_gt', '1.2.3'] => false, + ['semver_gte', '1.2.3'] => false, + ['semver_lt', '1.2.3'] => false, + ['semver_lte', '1.2.3'] => false, + ['semver_tilde', '1.2.3'] => false, + ['semver_caret', '1.2.3'] => false, + ['semver_wildcard', '1.2.*'] => false + }.each do |(operator, value), expected| + it "#{expected ? 'matches' : 'does not match'} #{operator}" do + property = { key: 'plan', operator: operator, value: value, type: 'person' } + expect(FeatureFlagsPoller.match_property(property, {}, known_absent_scope: plan_scope)).to be(expected) + end + end + + it 'resolves the flag locally without a remote request' do + c = local_client(flag('incomplete', person('plan', 'is_not_set')), flag('complete', person('plan', 'is_set'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: %w[incomplete complete], + person_property_keys_known_absent: ['plan']) + + expect(snapshot.get_flag('incomplete')).to be(true) + expect(snapshot.get_flag('complete')).to be(false) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + end + + it 'overrides a supplied value for a listed key' do + c = local_client(flag('incomplete', person('plan', 'is_not_set'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['incomplete'], person_properties: { plan: 'pro' }, + person_property_keys_known_absent: [:plan]) + + expect(snapshot.get_flag('incomplete')).to be(true) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'overrides the distinct_id the SDK adds to person properties' do + c = local_client(flag('no-distinct-id', person('distinct_id', 'is_not_set'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['no-distinct-id'], only_evaluate_locally: true, + person_property_keys_known_absent: ['distinct_id']) + + expect(snapshot.get_flag('no-distinct-id')).to be(true) + end + + it 'keeps an omitted key that is not listed inconclusive' do + c = local_client(flag('incomplete', person('plan', 'is_not_set'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['incomplete'], only_evaluate_locally: true, + person_property_keys_known_absent: ['region']) + + expect(snapshot.unresolved_flags).to eq('incomplete' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'ignores person keys with the person-metadata prefix' do + key = '__posthog_person_metadata__created_at' + c = local_client(flag('old-account', person(key, 'is_date_before', '2025-01-01T00:00:00Z'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['old-account'], only_evaluate_locally: true, + person_properties: { key => '2024-01-01T00:00:00Z' }, + person_property_keys_known_absent: [key]) + + expect(snapshot.get_flag('old-account')).to be(true) + end + + it 'still sends a person-metadata key to /flags as provided' do + known_absent = KnownAbsentPropertyKeys.build(%w[__posthog_person_metadata__created_at plan], nil) + + expect(known_absent.person_keys).to eq(Set['plan']) + expect(known_absent.request_fields).to eq( + person_property_keys_known_absent: %w[__posthog_person_metadata__created_at plan] + ) + end + + describe 'group keys' do + let(:org_tier_not_set) do + flag('org-incomplete', { key: 'tier', operator: 'is_not_set', type: 'group', group_type_index: 0 }) + .tap { |definition| definition[:filters][:aggregation_group_type_index] = 0 } + end + + def group_client(definition) + local_client(definition, group_type_mapping: { '0' => 'organization', '1' => 'project' }) + end + + it 'apply to their own group type' do + c = group_client(org_tier_not_set) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-incomplete'], groups: { organization: 'acme' }, + group_property_keys_known_absent: { organization: ['tier'] }) + + expect(snapshot.get_flag('org-incomplete')).to be(true) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'do not apply to another group type' do + c = group_client(org_tier_not_set) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-incomplete'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + group_property_keys_known_absent: { 'project' => ['tier'] }) + + expect(snapshot.unresolved_flags).to eq('org-incomplete' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'do not apply to person properties' do + c = local_client(flag('incomplete', person('tier', 'is_not_set'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['incomplete'], only_evaluate_locally: true, + group_property_keys_known_absent: { organization: ['tier'] }) + + expect(snapshot.unresolved_flags).to eq('incomplete' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'override the $group_key the SDK adds to group properties' do + definition = flag('no-group-key', { key: '$group_key', operator: 'is_not_set', type: 'group', + group_type_index: 0 }) + definition[:filters][:aggregation_group_type_index] = 0 + c = group_client(definition) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['no-group-key'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + group_property_keys_known_absent: { organization: ['$group_key'] }) + + expect(snapshot.get_flag('no-group-key')).to be(true) + end + + it 'apply to a group condition in a mixed-targeting flag' do + definition = flag('mixed') + definition[:filters][:groups] = [{ + properties: [{ key: 'tier', operator: 'is_not_set', type: 'group', group_type_index: 1 }], + rollout_percentage: 100, aggregation_group_type_index: 1 + }] + c = group_client(definition) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['mixed'], groups: { project: 'p1' }, + only_evaluate_locally: true, + group_property_keys_known_absent: { project: ['tier'] }) + + expect(snapshot.get_flag('mixed')).to be(true) + end + end + + describe 'filters local evaluation cannot use' do + [ + ['not_icontains_multi', ['pro']], + ['not_between', [1, 2]], + ['icontains_multi', ['pro']], + ['between', [1, 2]], + %w[future_operator pro] + ].each do |operator, value| + it "stays unsupported for #{operator} #{value.inspect} on a listed key" do + property = { key: 'plan', operator: operator, value: value, type: 'person' } + expect do + FeatureFlagsPoller.match_property(property, {}, known_absent_scope: plan_scope) + end.to raise_error(InconclusiveMatchError) { |e| + expect(e.reason).to eq(UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + } + end + end + + [ + ['is_not omitted', { operator: 'is_not' }], + ['is_not null', { operator: 'is_not', value: nil }], + ['exact null', { operator: 'exact', value: nil }], + ['gt null', { operator: 'gt', value: nil }] + ].each do |name, filter| + it "stays unsupported for #{name} condition value on a listed key" do + property = { key: 'plan', type: 'person' }.merge(filter) + expect do + FeatureFlagsPoller.match_property(property, {}, known_absent_scope: plan_scope) + end.to raise_error(InconclusiveMatchError) { |e| + expect(e.reason).to eq(UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + } + end + end + + it 'stays unsupported for a JSON null condition value with a String-keyed filter' do + property = JSON.parse('{"key": "plan", "operator": "is_not", "value": null, "type": "person"}') + expect do + FeatureFlagsPoller.match_property(property, {}, known_absent_scope: plan_scope) + end.to raise_error(InconclusiveMatchError) { |e| + expect(e.reason).to eq(UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + } + end + + { 'is_not_set' => true, 'is_set' => false }.each do |operator, expected| + it "still resolves #{operator} with a null condition value on a listed key" do + property = { key: 'plan', operator: operator, value: nil, type: 'person' } + expect(FeatureFlagsPoller.match_property(property, {}, known_absent_scope: plan_scope)).to be(expected) + end + end + + [ + ['omitted', { key: 'plan', operator: 'is_not', type: 'person' }], + ['null', { key: 'plan', operator: 'is_not', type: 'person', value: nil }] + ].each do |name, property| + it "leave an #{name} is_not condition value unresolved in local-only mode" do + c = local_client(flag('no-value', property)) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['no-value'], only_evaluate_locally: true, + person_property_keys_known_absent: ['plan']) + + expect(snapshot.get_flag('no-value')).to be_nil + expect(snapshot.unresolved_flags).to eq('no-value' => UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it "fall back to /flags for an #{name} is_not condition value" do + c = local_client(flag('no-value', property)) + stub_request(:post, flags_endpoint).to_return( + status: 200, + body: { flags: { 'no-value' => { key: 'no-value', enabled: false, variant: nil, + metadata: { id: 1 } } } }.to_json + ) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['no-value'], person_property_keys_known_absent: ['plan']) + + expect(snapshot.get_flag('no-value')).to be(false) + expect(flags_request_body['person_property_keys_known_absent']).to eq(['plan']) + end + end + + it 'fall back to /flags with the listed keys' do + c = local_client(flag('multi', person('plan', 'not_icontains_multi', ['pro']))) + stub_request(:post, flags_endpoint).to_return( + status: 200, + body: { flags: { 'multi' => { key: 'multi', enabled: true, variant: nil, metadata: { id: 1 } } } }.to_json + ) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['multi'], person_property_keys_known_absent: ['plan']) + + expect(snapshot.get_flag('multi')).to be(true) + expect(flags_request_body['person_property_keys_known_absent']).to eq(['plan']) + end + end + + describe 'condition values a listed key does not read' do + unusable_values = { + ['not_regex', '['] => true, + ['regex', '['] => false, + ['not_regex', '(?=pro)'] => true, + ['regex', '(?=pro)'] => false, + ['not_regex', '\p{L}'] => true, + ['regex', '\p{L}'] => false, + %w[gt not-a-number] => false, + %w[gte not-a-number] => false, + %w[lt not-a-number] => false, + %w[lte not-a-number] => false, + %w[semver_eq not-a-version] => false, + %w[semver_neq not-a-version] => false, + %w[semver_gt not-a-version] => false, + %w[semver_gte not-a-version] => false, + %w[semver_lt not-a-version] => false, + %w[semver_lte not-a-version] => false, + %w[semver_tilde not-a-version] => false, + %w[semver_caret not-a-version] => false, + %w[semver_wildcard not-a-version] => false, + %w[is_date_before not-a-date] => false, + %w[is_date_after not-a-date] => false + } + + unusable_values.each do |(operator, value), expected| + it "resolves #{operator} #{value.inspect} to #{expected} on a listed key" do + property = { key: 'plan', operator: operator, value: value, type: 'person' } + expect(FeatureFlagsPoller.match_property(property, {}, known_absent_scope: plan_scope)).to be(expected) + end + end + + def unusable_value_flags(values) + values.each_with_index.map do |((operator, value), _expected), index| + flag("unusable-#{index}", person('plan', operator, value)) + end + end + + def expected_unusable_values(values) + values.each_with_index.to_h { |(_filter, expected), index| ["unusable-#{index}", expected] } + end + + it 'resolves the flags in local-only mode' do + c = local_client(*unusable_value_flags(unusable_values)) + expected = expected_unusable_values(unusable_values) + + snapshot = c.evaluate_flags('user-1', flag_keys: expected.keys, only_evaluate_locally: true, + person_property_keys_known_absent: ['plan']) + + expect(expected.keys.to_h { |key| [key, snapshot.get_flag(key)] }).to eq(expected) + expect(snapshot.unresolved_flags).to eq({}) + end + + it 'resolves the flags with the default getter without a remote request' do + c = local_client(*unusable_value_flags(unusable_values)) + expected = expected_unusable_values(unusable_values) + + snapshot = c.evaluate_flags('user-1', flag_keys: expected.keys, person_property_keys_known_absent: ['plan']) + + expect(expected.keys.to_h { |key| [key, snapshot.get_flag(key)] }).to eq(expected) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'still reads the condition value for a key that is not listed' do + c = local_client(flag('bad-number', person('plan', 'gt', 'not-a-number'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['bad-number'], only_evaluate_locally: true, + person_properties: { plan: 5 }, + person_property_keys_known_absent: ['region']) + + expect(snapshot.unresolved_flags).to eq('bad-number' => UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + end + end + + describe 'dynamic cohorts' do + let(:cohorts) do + { + '7' => { type: 'AND', values: [{ type: 'AND', values: [ + { key: 'plan', operator: 'is_set', type: 'person', negation: true } + ] }] } + } + end + + it 'apply negation after the known-absent result' do + c = local_client(flag('no-plan-cohort', { key: 'id', value: 7, type: 'cohort' }), cohorts: cohorts) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['no-plan-cohort'], only_evaluate_locally: true, + person_property_keys_known_absent: ['plan']) + + expect(snapshot.get_flag('no-plan-cohort')).to be(true) + end + + [false, true].each do |negation| + it "check operator support before the known-absent table with negation #{negation}" do + range_cohorts = { + '8' => { type: 'AND', values: [{ type: 'AND', values: [ + { key: 'plan', operator: 'not_between', value: [1, 2], type: 'person', negation: negation } + ] }] } + } + c = local_client(flag('range-cohort', { key: 'id', value: 8, type: 'cohort' }), cohorts: range_cohorts) + stub_request(:post, flags_endpoint).to_return( + status: 200, + body: { flags: { 'range-cohort' => { key: 'range-cohort', enabled: true, variant: nil, + metadata: { id: 1 } } } }.to_json + ) + + local = c.evaluate_flags('user-1', flag_keys: ['range-cohort'], only_evaluate_locally: true, + person_property_keys_known_absent: ['plan']) + expect(local.get_flag('range-cohort')).to be_nil + expect(local.unresolved_flags).to eq('range-cohort' => UnresolvedFlagReason::UNSUPPORTED_DEFINITION) + + remote = c.evaluate_flags('user-1', flag_keys: ['range-cohort'], + person_property_keys_known_absent: ['plan']) + expect(remote.get_flag('range-cohort')).to be(true) + expect(flags_request_body['person_property_keys_known_absent']).to eq(['plan']) + end + end + end + + describe 'filter types' do + let(:group_type_mapping) { { '0' => 'organization', '1' => 'project' } } + + def created_at(operator, value = nil) + filter = { key: 'created_at', operator: operator, type: 'person_metadata' } + filter[:value] = value unless value.nil? + filter + end + + def group_flag(key, *properties, group_type_index: 0) + definition = flag(key, *properties) + definition[:filters][:aggregation_group_type_index] = group_type_index + definition + end + + def flag_dependency(key) + { key: key, type: 'flag', value: true, operator: 'flag_evaluates_to', dependency_chain: [key] } + end + + [['is_not_set', nil], ['is_date_before', '2025-01-01T00:00:00Z'], + ['is_date_after', '2025-01-01T00:00:00Z']].each do |operator, value| + it "do not resolve a person_metadata #{operator} filter on a listed key" do + c = local_client(flag('old-account', created_at(operator, value))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['old-account'], only_evaluate_locally: true, + person_property_keys_known_absent: ['created_at']) + + expect(snapshot.unresolved_flags).to eq('old-account' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it "do not resolve a person_metadata #{operator} cohort leaf on a listed key" do + cohorts = { '9' => { type: 'AND', values: [{ type: 'AND', values: [created_at(operator, value)] }] } } + c = local_client(flag('old-cohort', { key: 'id', value: 9, type: 'cohort' }), cohorts: cohorts) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['old-cohort'], only_evaluate_locally: true, + person_property_keys_known_absent: ['created_at']) + + expect(snapshot.unresolved_flags).to eq('old-cohort' => UnresolvedFlagReason::MISSING_CONTEXT) + end + end + + it 'resolve a person_metadata filter on a listed key from a supplied value' do + c = local_client(flag('old-account', created_at('is_date_before', '2025-01-01T00:00:00Z'))) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['old-account'], only_evaluate_locally: true, + person_properties: { created_at: '2024-01-01T00:00:00Z' }, + person_property_keys_known_absent: ['created_at']) + + expect(snapshot.get_flag('old-account')).to be(true) + end + + it 'fall back to /flags for a person_metadata filter on a listed key' do + c = local_client(flag('old-account', created_at('is_date_before', '2025-01-01T00:00:00Z'))) + stub_request(:post, flags_endpoint).to_return( + status: 200, + body: { flags: { 'old-account' => { key: 'old-account', enabled: true, variant: nil, + metadata: { id: 1 } } } }.to_json + ) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['old-account'], + person_property_keys_known_absent: ['created_at']) + + expect(snapshot.get_flag('old-account')).to be(true) + expect(flags_request_body['person_property_keys_known_absent']).to eq(['created_at']) + end + + it 'do not resolve a group filter in a person-aggregated flag from person keys' do + c = local_client(flag('person-flag', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 0 }), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['person-flag'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + person_property_keys_known_absent: ['tier']) + + expect(snapshot.unresolved_flags).to eq('person-flag' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'do not resolve a group filter in a group-aggregated flag from person keys' do + c = local_client(group_flag('org-flag', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 0 }), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-flag'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + person_property_keys_known_absent: ['tier']) + + expect(snapshot.unresolved_flags).to eq('org-flag' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'do not resolve a group filter for another group type from group keys' do + c = local_client(group_flag('org-flag', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 1 }), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-flag'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + group_property_keys_known_absent: { organization: ['tier'] }) + + expect(snapshot.unresolved_flags).to eq('org-flag' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'do not resolve a person filter in a group-aggregated flag from group keys' do + c = local_client(group_flag('org-flag', person('plan', 'is_not_set')), group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-flag'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + group_property_keys_known_absent: { organization: ['plan'] }) + + expect(snapshot.unresolved_flags).to eq('org-flag' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'do not resolve a person cohort leaf in a group-aggregated flag from group keys' do + cohorts = { '7' => { type: 'AND', values: [{ type: 'AND', values: [person('plan', 'is_not_set')] }] } } + c = local_client(group_flag('org-cohort', { key: 'id', value: 7, type: 'cohort' }), + cohorts: cohorts, group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-cohort'], groups: { organization: 'acme' }, + only_evaluate_locally: true, + group_property_keys_known_absent: { organization: ['plan'] }) + + expect(snapshot.unresolved_flags).to eq('org-cohort' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'do not leak person keys into a group-aggregated flag dependency' do + org_parent = group_flag('org-parent', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 0 }) + c = local_client(org_parent, flag('person-child', flag_dependency('org-parent')), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['person-child'], groups: { organization: 'acme' }, + group_properties: { organization: { tier: 'enterprise' } }, + person_property_keys_known_absent: ['tier'], + only_evaluate_locally: true) + + expect(snapshot.get_flag('person-child')).to be(false) + expect(snapshot.unresolved_flags).to eq({}) + end + + it 'do not leak group keys into a person-aggregated flag dependency' do + org_child = group_flag('org-child', flag_dependency('person-parent')) + c = local_client(flag('person-parent', person('tier', 'is_not_set')), org_child, + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-child'], groups: { organization: 'acme' }, + person_properties: { tier: 'pro' }, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.get_flag('org-child')).to be(false) + expect(snapshot.unresolved_flags).to eq({}) + end + + it 'apply the group keys of a group-aggregated dependency instead of person values' do + org_parent = group_flag('org-parent', { key: 'tier', operator: 'exact', value: 'pro', type: 'group', + group_type_index: 0 }) + c = local_client(org_parent, flag('person-child', flag_dependency('org-parent')), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: %w[person-child org-parent], + groups: { organization: 'acme' }, + person_properties: { tier: 'pro' }, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.get_flag('org-parent')).to be(false) + expect(snapshot.get_flag('person-child')).to be(false) + end + + it 'evaluate a group-aggregated dependency as false when its group is not passed' do + org_parent = group_flag('org-parent', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 0 }) + c = local_client(org_parent, flag('person-child', flag_dependency('org-parent')), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: %w[person-child org-parent], groups: {}, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.get_flag('org-parent')).to be(false) + expect(snapshot.get_flag('person-child')).to be(false) + end + + it 'evaluate a group-aggregated dependency with its group properties, not person properties' do + org_parent = group_flag('org-parent', + { key: 'tier', operator: 'is_not_set', type: 'group', group_type_index: 0 }, + { key: 'region', operator: 'exact', value: 'us', type: 'group', group_type_index: 0 }) + c = local_client(org_parent, flag('person-child', flag_dependency('org-parent')), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: %w[person-child org-parent], + groups: { organization: 'acme' }, + person_properties: { region: 'us' }, + group_properties: { organization: { region: 'eu' } }, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.get_flag('org-parent')).to be(false) + expect(snapshot.get_flag('person-child')).to be(false) + end + + it 'evaluate a person-aggregated dependency with person properties, not group properties' do + person_parent = flag('person-parent', person('plan', 'is_not_set'), person('region', 'exact', 'us')) + c = local_client(person_parent, group_flag('org-child', flag_dependency('person-parent')), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: %w[org-child person-parent], + groups: { organization: 'acme' }, + person_properties: { region: 'us' }, + group_properties: { organization: { region: 'eu' } }, + person_property_keys_known_absent: ['plan'], + only_evaluate_locally: true) + + expect(snapshot.get_flag('person-parent')).to be(true) + expect(snapshot.get_flag('org-child')).to be(true) + end + + it 'apply group keys to a legacy group filter without group_type_index' do + legacy_exact = group_flag('legacy-exact', { key: 'tier', operator: 'exact', value: 'enterprise', + type: 'group' }) + legacy_unset = group_flag('legacy-unset', { key: 'tier', operator: 'is_not_set', type: 'group' }) + c = local_client(legacy_exact, legacy_unset, group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: %w[legacy-exact legacy-unset], + groups: { organization: 'acme' }, + group_properties: { organization: { tier: 'enterprise' } }, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.get_flag('legacy-exact')).to be(false) + expect(snapshot.get_flag('legacy-unset')).to be(true) + end + + it 'do not apply group keys to a group filter for another group type' do + other_type = group_flag('other-type', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 1 }) + c = local_client(other_type, group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['other-type'], groups: { organization: 'acme' }, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.unresolved_flags).to eq('other-type' => UnresolvedFlagReason::MISSING_CONTEXT) + end + + it 'apply group keys to a dependency with the same group aggregation' do + org_parent = group_flag('org-parent', { key: 'tier', operator: 'is_not_set', type: 'group', + group_type_index: 0 }) + c = local_client(org_parent, group_flag('org-child', flag_dependency('org-parent')), + group_type_mapping: group_type_mapping) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-child'], groups: { organization: 'acme' }, + group_property_keys_known_absent: { organization: ['tier'] }, + only_evaluate_locally: true) + + expect(snapshot.get_flag('org-child')).to be(true) + end + end + + it 'applies to flag dependencies' do + dependency = { key: 'incomplete', type: 'flag', value: true, operator: 'flag_evaluates_to', + dependency_chain: ['incomplete'] } + c = local_client(flag('incomplete', person('plan', 'is_not_set')), flag('dependent', dependency)) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['dependent'], only_evaluate_locally: true, + person_property_keys_known_absent: ['plan']) + + expect(snapshot.get_flag('dependent')).to be(true) + end + + describe 'the /flags request body' do + let(:inconclusive_flag) { flag('needs-region', person('region', 'exact', 'eu')) } + + it 'includes the listed person and group keys on fallback' do + c = local_client(inconclusive_flag) + + c.evaluate_flags('user-1', groups: { organization: 'acme' }, + person_property_keys_known_absent: ['plan'], + group_property_keys_known_absent: { organization: ['tier'] }) + + body = flags_request_body + expect(body['person_property_keys_known_absent']).to eq(['plan']) + expect(body['group_property_keys_known_absent']).to eq('organization' => ['tier']) + end + + it 'omits the fields when nothing was provided' do + c = local_client(inconclusive_flag) + + c.evaluate_flags('user-1') + + body = flags_request_body + expect(body).not_to have_key('person_property_keys_known_absent') + expect(body).not_to have_key('group_property_keys_known_absent') + end + + it 'omits empty fields' do + c = local_client(inconclusive_flag) + + c.evaluate_flags('user-1', person_property_keys_known_absent: [], + group_property_keys_known_absent: { organization: [] }) + + body = flags_request_body + expect(body).not_to have_key('person_property_keys_known_absent') + expect(body).not_to have_key('group_property_keys_known_absent') + end + + it 'includes the listed keys for the legacy single-flag getter' do + c = local_client(inconclusive_flag) + allow(Kernel).to receive(:warn) + + c.get_feature_flag_result('needs-region', 'user-1', person_property_keys_known_absent: ['plan']) + + expect(flags_request_body['person_property_keys_known_absent']).to eq(['plan']) + end + + it 'includes the listed keys for all flags and payloads' do + c = local_client(inconclusive_flag) + + c.get_all_flags_and_payloads('user-1', group_property_keys_known_absent: { organization: ['tier'] }) + + expect(flags_request_body['group_property_keys_known_absent']).to eq('organization' => ['tier']) + end + + it 'includes the listed keys for send_feature_flags on capture' do + c = local_client(inconclusive_flag) + allow(Kernel).to receive(:warn) + + c.capture(distinct_id: 'user-1', event: 'signed_up', + send_feature_flags: { person_property_keys_known_absent: ['plan'] }) + + expect(flags_request_body['person_property_keys_known_absent']).to eq(['plan']) + end + + it 'includes the listed keys for a SendFeatureFlagsOptions object on capture' do + c = local_client(inconclusive_flag) + allow(Kernel).to receive(:warn) + options = SendFeatureFlagsOptions.new(group_property_keys_known_absent: { organization: ['tier'] }) + + c.capture(distinct_id: 'user-1', event: 'signed_up', send_feature_flags: options) + + expect(flags_request_body['group_property_keys_known_absent']).to eq('organization' => ['tier']) + end + end + + describe 'capture(send_feature_flags:)' do + def group_filter(key, operator, value = nil) + filter = { key: key, operator: operator, type: 'group', group_type_index: 1 } + filter[:value] = value unless value.nil? + filter + end + + before { allow(Kernel).to receive(:warn) } + + it 'resolves a mixed-targeting group condition locally without group_properties' do + definition = flag('mixed') + definition[:filters][:groups] = [{ + properties: [group_filter('tier', 'is_not_set')], rollout_percentage: 100, aggregation_group_type_index: 1 + }] + c = local_client(definition, group_type_mapping: { '1' => 'project' }) + + c.capture(distinct_id: 'user-1', event: 'signed_up', groups: { project: 'p1' }, + send_feature_flags: { only_evaluate_locally: true, + group_property_keys_known_absent: { project: ['tier'] } }) + + properties = c.dequeue_last_message[:properties] + expect(properties['$feature/mixed']).to be(true) + expect(properties['$active_feature_flags']).to eq(['mixed']) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'resolves a group flag that also reads $group_key without group_properties' do + definition = flag('group-flag', group_filter('tier', 'is_not_set'), group_filter('$group_key', 'exact', 'acme')) + definition[:filters][:aggregation_group_type_index] = 1 + c = local_client(definition, group_type_mapping: { '1' => 'project' }) + options = SendFeatureFlagsOptions.new(only_evaluate_locally: true, + group_property_keys_known_absent: { project: ['tier'] }) + + c.capture(distinct_id: 'user-1', event: 'signed_up', groups: { project: 'acme' }, send_feature_flags: options) + + message = c.dequeue_last_message + expect(message[:properties]['$feature/group-flag']).to be(true) + expect(message[:properties]['$groups']).to eq(project: 'acme') + end + + it 'warns and still captures the event without flags for an invalid listing' do + c = local_client(flag('incomplete', person('plan', 'is_not_set'))) + logger = instance_double(Logger, warn: nil) + allow(c).to receive(:logger).and_return(logger) + + result = c.capture(distinct_id: 'user-1', event: 'signed_up', + send_feature_flags: { person_property_keys_known_absent: 'plan' }) + + expect(result).to be(true) + message = c.dequeue_last_message + expect(message[:event]).to eq('signed_up') + expect(message[:properties]).not_to have_key('$feature/incomplete') + expect(logger).to have_received(:warn).with(/person_property_keys_known_absent must be an Array/) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + end + + describe 'other inputs' do + it 'accepts Set inputs for person and group keys' do + definition = flag('incomplete', person('plan', 'is_not_set')) + c = local_client(definition) + + snapshot = c.evaluate_flags('user-1', only_evaluate_locally: true, + person_property_keys_known_absent: Set['plan'], + group_property_keys_known_absent: { organization: Set['tier'] }) + + expect(snapshot.get_flag('incomplete')).to be(true) + end + + it 'resolves get_feature_flag_payload locally for a listed key' do + definition = flag('incomplete', person('plan', 'is_not_set')) + definition[:filters][:payloads] = { 'true' => '{"tier":"starter"}' } + c = local_client(definition) + + payload = c.get_feature_flag_payload('incomplete', 'user-1', person_property_keys_known_absent: ['plan']) + + expect(payload).to eq('{"tier":"starter"}') + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'sends the listed keys when get_feature_flag_payload falls back to /flags' do + c = local_client(flag('incomplete', person('region', 'exact', 'eu'))) + + c.get_feature_flag_payload('incomplete', 'user-1', person_property_keys_known_absent: ['plan']) + + expect(flags_request_body['person_property_keys_known_absent']).to eq(['plan']) + end + end + + describe 'limits' do + let(:too_many) { Array.new(KnownAbsentPropertyKeys::MAX_KEYS + 1, 'plan') } + + it 'accepts 1000 keys' do + c = local_client(flag('needs-region', person('region', 'exact', 'eu'))) + + c.evaluate_flags('user-1', person_property_keys_known_absent: Array.new(1000) { |i| "key-#{i}" }) + + expect(flags_request_body['person_property_keys_known_absent'].length).to eq(1000) + end + + it 'rejects more than 1000 person keys, counting duplicates, without a request' do + c = local_client(flag('needs-region', person('region', 'exact', 'eu'))) + + expect do + c.evaluate_flags('user-1', person_property_keys_known_absent: too_many) + end.to raise_error(ArgumentError, /person_property_keys_known_absent allows at most 1000 keys/) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'rejects more than 1000 person keys for an empty flag scope' do + c = local_client(flag('needs-region', person('region', 'exact', 'eu'))) + + expect do + c.evaluate_flags('user-1', flag_keys: [], person_property_keys_known_absent: too_many) + end.to raise_error(ArgumentError, /person_property_keys_known_absent allows at most 1000 keys/) + end + + it 'rejects more than 1000 keys for one group type' do + c = local_client(flag('needs-region', person('region', 'exact', 'eu'))) + + expect do + c.get_all_flags('user-1', group_property_keys_known_absent: { organization: too_many }) + end.to raise_error(ArgumentError, /group_property_keys_known_absent\[organization\] allows at most 1000/) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'counts group keys per group type' do + known_absent = KnownAbsentPropertyKeys.build( + nil, { organization: Array.new(1000, 'tier'), project: Array.new(1000, 'tier') } + ) + + expect(known_absent.group_keys(:project)).to eq(Set['tier']) + end + + it 'merges String and Symbol names for the same group type before the limit check' do + known_absent = KnownAbsentPropertyKeys.build(nil, { organization: ['tier'], 'organization' => ['region'] }) + + expect(known_absent.group_keys(:organization)).to eq(Set['tier', 'region']) + expect(known_absent.request_fields) + .to eq(group_property_keys_known_absent: { 'organization' => %w[tier region] }) + too_many = { organization: Array.new(600, 'tier'), 'organization' => Array.new(401, 'region') } + expect { KnownAbsentPropertyKeys.build(nil, too_many) } + .to raise_error(ArgumentError, /allows at most 1000 keys, got 1001/) + end + + it 'rejects inputs of the wrong type' do + expect { KnownAbsentPropertyKeys.build('plan', nil) }.to raise_error(ArgumentError) + expect { KnownAbsentPropertyKeys.build(nil, ['tier']) }.to raise_error(ArgumentError) + expect { KnownAbsentPropertyKeys.build([1], nil) }.to raise_error(ArgumentError) + expect { KnownAbsentPropertyKeys.build(nil, { 1 => ['tier'] }) }.to raise_error(ArgumentError) + end + end + end +end diff --git a/spec/posthog/feature_flags_unusable_group_key_spec.rb b/spec/posthog/feature_flags_unusable_group_key_spec.rb new file mode 100644 index 00000000..98d81478 --- /dev/null +++ b/spec/posthog/feature_flags_unusable_group_key_spec.rb @@ -0,0 +1,171 @@ +# frozen_string_literal: true + +require 'spec_helper' + +module PostHog + # A usable group key is a non-empty string or a number. Any other key counts as no key: a condition + # aggregated on that group type is skipped, and a flag whose conditions are all skipped resolves false + # locally without a /flags request. + describe 'unusable group keys' do + let(:definitions_endpoint) { 'https://us.i.posthog.com/flags/definitions?token=testsecret&send_cohorts=true' } + let(:flags_endpoint) { 'https://us.i.posthog.com/flags/?v=2' } + let(:remote_response) do + { flags: { 'org-flag' => { key: 'org-flag', enabled: true, variant: nil, metadata: { id: 9 } } } } + end + let(:group_type_mapping) { { '0' => 'organization' } } + + unusable_group_keys = { 'an empty string' => '', 'nil' => nil, 'true' => true, 'false' => false, + 'an array' => [], 'a hash' => {}, 'a non-empty array' => ['acme'], + 'a non-empty hash' => { id: 'acme' } } + + def local_client(*flags) + stub_request(:get, definitions_endpoint).to_return( + status: 200, body: { flags: flags, cohorts: {}, group_type_mapping: group_type_mapping }.to_json + ) + stub_request(:post, flags_endpoint).to_return(status: 200, body: remote_response.to_json) + Client.new(api_key: API_KEY, personal_api_key: API_KEY, test_mode: true) + end + + def condition(*properties, rollout_percentage: 100, **extra) + { properties: properties, rollout_percentage: rollout_percentage }.merge(extra) + end + + def org_flag(key = 'org-flag', *conditions) + conditions = [condition] if conditions.empty? + { id: 1, key: key, active: true, filters: { aggregation_group_type_index: 0, groups: conditions } } + end + + def person_flag(key, *conditions) + { id: 2, key: key, active: true, filters: { groups: conditions } } + end + + # A person condition on `plan`, plus a group condition aggregated on organization that matches any + # organization. + def mixed_flag + person_flag('mixed', condition({ key: 'plan', operator: 'exact', value: 'pro', type: 'person' }), + condition(aggregation_group_type_index: 0)) + end + + def flag_dependency(key) + { key: key, type: 'flag', value: true, operator: 'flag_evaluates_to', dependency_chain: [key] } + end + + unusable_group_keys.each do |description, group_key| + context "with #{description} as the group key" do + let(:groups) { { organization: group_key } } + + it 'resolves a group flag to false in local-only mode' do + c = local_client(org_flag) + + snapshot = c.evaluate_flags('user-1', groups: groups, only_evaluate_locally: true) + + expect(snapshot.get_flag('org-flag')).to be(false) + expect(snapshot.unresolved_flags).to eq({}) + end + + it 'resolves a group flag to false with the default getter without a remote request' do + c = local_client(org_flag) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['org-flag'], groups: groups) + + expect(snapshot.get_flag('org-flag')).to be(false) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'resolves a group flag to false with the single-flag getter without a remote request' do + c = local_client(org_flag) + + result = c.get_feature_flag_result('org-flag', 'user-1', groups: groups, send_feature_flag_events: false) + + expect(result.value).to be(false) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'skips the group condition of a mixed flag and lets the person condition decide' do + c = local_client(mixed_flag) + + free = c.evaluate_flags('user-1', groups: groups, person_properties: { plan: 'free' }, + only_evaluate_locally: true) + pro = c.evaluate_flags('user-1', groups: groups, person_properties: { plan: 'pro' }, + only_evaluate_locally: true) + + expect(free.get_flag('mixed')).to be(false) + expect(pro.get_flag('mixed')).to be(true) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'resolves a group-aggregated dependency to false' do + child = person_flag('person-child', condition(flag_dependency('org-parent'))) + c = local_client(org_flag('org-parent'), child) + + snapshot = c.evaluate_flags('user-1', flag_keys: ['person-child'], groups: groups) + + expect(snapshot.get_flag('person-child')).to be(false) + expect(snapshot.unresolved_flags).to eq({}) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + + it 'does not raise from get_all_flags or get_all_flags_and_payloads' do + c = local_client(org_flag, mixed_flag) + + inputs = { groups: groups, person_properties: { plan: 'free' }, only_evaluate_locally: true } + + expect(c.get_all_flags('user-1', **inputs)).to eq('org-flag' => false, 'mixed' => false) + expect(c.get_all_flags_and_payloads('user-1', **inputs)[:featureFlags]) + .to eq('org-flag' => false, 'mixed' => false) + end + + it 'does not raise from capture with send_feature_flags' do + c = local_client(org_flag) + + c.capture(distinct_id: 'user-1', event: 'signed_up', groups: groups, send_feature_flags: true) + + properties = c.dequeue_last_message[:properties] + expect(properties['$feature/org-flag']).to be(false) + expect(WebMock).not_to have_requested(:post, flags_endpoint) + end + end + end + + describe 'usable group keys' do + def variant_flag + org_flag.tap do |definition| + definition[:filters][:multivariate] = { + variants: [{ key: 'control', rollout_percentage: 50 }, { key: 'test', rollout_percentage: 50 }] + } + end + end + + { 'a string' => %w[acme acme], 'an integer' => [42, '42'], 'a float' => [4.5, '4.5'] } + .each do |description, (group_key, rendered_key)| + it "evaluates and buckets #{description} as its rendered string" do + c = local_client(variant_flag) + + snapshot = c.evaluate_flags('user-1', groups: { organization: group_key }, only_evaluate_locally: true) + rendered = c.evaluate_flags('user-1', groups: { organization: rendered_key }, only_evaluate_locally: true) + + expect(snapshot.get_flag('org-flag')).to be_a(String) + expect(snapshot.get_flag('org-flag')).to eq(rendered.get_flag('org-flag')) + end + end + + it 'still evaluates the group condition of a mixed flag' do + c = local_client(mixed_flag) + + snapshot = c.evaluate_flags('user-1', groups: { organization: 'acme' }, group_properties: { organization: {} }, + person_properties: { plan: 'free' }, only_evaluate_locally: true) + + expect(snapshot.get_flag('mixed')).to be(true) + end + + it 'stays inconclusive without the group properties a condition needs' do + c = local_client(org_flag('org-flag', condition({ key: 'tier', operator: 'exact', value: 'pro', + type: 'group', group_type_index: 0 }))) + + snapshot = c.evaluate_flags('user-1', groups: { organization: 'acme' }, only_evaluate_locally: true) + + expect(snapshot.unresolved_flags).to eq('org-flag' => UnresolvedFlagReason::MISSING_CONTEXT) + end + end + end +end diff --git a/spec/posthog/send_feature_flags_options_spec.rb b/spec/posthog/send_feature_flags_options_spec.rb index 283c3a04..27f08ace 100644 --- a/spec/posthog/send_feature_flags_options_spec.rb +++ b/spec/posthog/send_feature_flags_options_spec.rb @@ -83,6 +83,20 @@ expect(options.group_properties).to eq({}) end + it 'reads known-absent property keys and round-trips them through to_h' do + hash = { + 'person_property_keys_known_absent' => ['plan'], + group_property_keys_known_absent: { company: ['tier'] } + } + options = PostHog::SendFeatureFlagsOptions.from_hash(hash) + expect(options.person_property_keys_known_absent).to eq(['plan']) + expect(options.group_property_keys_known_absent).to eq({ company: ['tier'] }) + expect(options.to_h).to include( + person_property_keys_known_absent: ['plan'], + group_property_keys_known_absent: { company: ['tier'] } + ) + end + it 'returns nil for non-hash input' do expect(PostHog::SendFeatureFlagsOptions.from_hash('not a hash')).to be_nil expect(PostHog::SendFeatureFlagsOptions.from_hash(nil)).to be_nil