Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
cf2483c
feat(analytics): hierarchical groups support
tylerjroach Nov 2, 2026
c926dba
feat(analytics): refuse alias on hierarchical groups projects
tylerjroach Nov 2, 2026
0444da1
feat(flags): resolve local assignment keys from context_value_template
tylerjroach Nov 2, 2026
90150a3
feat(analytics): raise for unsupported groups.update operations on hi…
tylerjroach Nov 2, 2026
48ef5ef
feat(analytics): add a company profile to for_company trackers
tylerjroach Nov 3, 2026
c64b0bb
chore(analytics): point the company-only identity error at the compan…
tylerjroach Nov 3, 2026
56b138d
revert(analytics): drop the company profile methods from for_company …
tylerjroach Nov 3, 2026
f4353eb
feat(analytics): infer the company for $company_id group profile updates
tylerjroach Nov 3, 2026
6c36b36
feat(analytics): restore the company profile on for_company clients
tylerjroach Nov 3, 2026
f38f44a
feat(flags): build a flag context from a Mixpanel::Identity
tylerjroach Nov 3, 2026
0802682
feat(analytics): refuse a user from another company on a for_company …
tylerjroach Nov 3, 2026
ef0487e
feat(analytics): send a user without a company as given on hierarchic…
tylerjroach Nov 3, 2026
7694fa8
refactor: align Mixpanel::Identity naming and HG errors with the othe…
tylerjroach Nov 4, 2026
170b7f4
fix(people): use the bound company for a user profile without one on …
tylerjroach Nov 4, 2026
1d655d4
fix(flags): keep the context value template regex linear
tylerjroach Nov 4, 2026
3d9c179
docs: drop the hierarchical groups README section
tylerjroach Nov 5, 2026
f4dd3d4
fix: merge group update message before reading $company_id
tylerjroach Nov 9, 2026
3559f20
fix: keep exposure $user_id, allow-list /groups operations and accept…
tylerjroach Nov 9, 2026
5e23be5
Merge remote-tracking branch 'origin/master' into hierarchical-groups
tylerjroach Nov 17, 2026
6dfd465
fix: copy the company id passed to for_company
tylerjroach Nov 17, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/mixpanel-ruby.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'mixpanel-ruby/consumer.rb'
require 'mixpanel-ruby/identity.rb'
require 'mixpanel-ruby/tracker.rb'
require 'mixpanel-ruby/version.rb'
require 'mixpanel-ruby/credentials.rb'
Expand Down
14 changes: 14 additions & 0 deletions lib/mixpanel-ruby/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,20 @@ class ConnectionError < MixpanelError
class ServerError < MixpanelError
end

# Raised directly to the caller (never passed to the ErrorHandler) when a
# hierarchical groups tracker is asked for a profile operation that
# hierarchical groups projects do not support, such as People#increment,
# People#append or People#track_charge. It signals a mistake in the calling
# code rather than a delivery failure.
class UnsupportedOperationError < MixpanelError
end

# Raised directly to the caller (never passed to the ErrorHandler) when a
# hierarchical groups tracker builds a group profile update without
# knowing its company. Use Tracker#for_company to bind one.
class CompanyRequiredError < MixpanelError
end


# The default behavior of the gem is to silence all errors
# thrown in the consumer. If you wish to handle MixpanelErrors
Expand Down
61 changes: 46 additions & 15 deletions lib/mixpanel-ruby/events.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

require 'mixpanel-ruby/consumer'
require 'mixpanel-ruby/error'
require 'mixpanel-ruby/identity'

module Mixpanel

Expand All @@ -22,10 +23,13 @@ class Events
# # tracker has all of the methods of Mixpanel::Events
# tracker = Mixpanel::Tracker.new(YOUR_MIXPANEL_TOKEN)
#
def initialize(token, error_handler=nil, credentials: nil, &block)
# Pass hierarchical_groups: true if the project uses hierarchical
# groups; see Mixpanel::Tracker#initialize.
def initialize(token, error_handler=nil, credentials: nil, hierarchical_groups: false, &block)
@token = token
@error_handler = error_handler || ErrorHandler.new
@credentials = credentials
@hierarchical_groups = hierarchical_groups ? true : false

if block && credentials
warn '[WARNING] credentials passed to Events/Tracker are ignored when a custom sink block is provided. Pass credentials to your consumer directly.'
Expand Down Expand Up @@ -56,14 +60,16 @@ def initialize(token, error_handler=nil, credentials: nil, &block)
# 'Email Template' => 'Pretty Pink Welcome',
# 'User Sign-up Cohort' => 'July 2013'
# })
#
# distinct_id may also be a Mixpanel::Identity, whose keys replace any
# caller-supplied values for the same keys in properties:
#
# tracker.track(Mixpanel::Identity.new(user_id: '12345', company_id: 'acme'), 'Signup')
#
# Raises ArgumentError if the identity does not match the project (see
# Mixpanel::Identity).
def track(distinct_id, event, properties={}, ip=nil)
properties = {
'distinct_id' => distinct_id,
'token' => @token,
'time' => (Time.now.to_f * 1000).to_i,
'mp_lib' => 'ruby',
'$lib_version' => Mixpanel::VERSION,
}.merge(properties)
properties = event_properties(distinct_id, properties)
properties['ip'] = ip if ip

data = {
Expand Down Expand Up @@ -133,6 +139,7 @@ def import(api_key, distinct_id, event, properties={}, ip=nil)
# 'Source' => 'Import'
# })
#
# Like #track, distinct_id may be a Mixpanel::Identity.
def import_events(distinct_id, event, properties={}, ip=nil)
unless @credentials
raise ArgumentError, 'import_events requires credentials in constructor. Use: Tracker.new(token, credentials: credentials)'
Expand All @@ -152,13 +159,7 @@ def import_internal(api_key, distinct_id, event, properties, ip)
raise ArgumentError, 'import requires authentication: provide either api_key parameter or credentials in constructor'
end

properties = {
'distinct_id' => distinct_id,
'token' => @token,
'time' => (Time.now.to_f * 1000).to_i,
'mp_lib' => 'ruby',
'$lib_version' => Mixpanel::VERSION,
}.merge(properties)
properties = event_properties(distinct_id, properties)
properties['ip'] = ip if ip

data = {
Expand Down Expand Up @@ -202,5 +203,35 @@ def import_internal(api_key, distinct_id, event, properties, ip)

ret
end

# Builds the properties of an event message for a distinct id or a
# Mixpanel::Identity. A string distinct id is never refused, in either
# mode: Mixpanel accepts a distinct id it built itself, such as
# "$company:acme|$user:user_123".
def event_properties(distinct_id, properties)
unless distinct_id.is_a?(Identity)
return {
'distinct_id' => distinct_id,
'token' => @token,
'time' => (Time.now.to_f * 1000).to_i,
'mp_lib' => 'ruby',
'$lib_version' => Mixpanel::VERSION,
}.merge(properties)
end

identity = distinct_id
HierarchicalGroups.require_identity_matches_project(identity, @hierarchical_groups)

# An identity without a distinct id sends no distinct_id: Mixpanel
# resolves the event from $user_id, $company_id and $device_id.
defaults = {}
defaults['distinct_id'] = identity.distinct_id unless identity.distinct_id.nil?
defaults.merge(
'token' => @token,
'time' => (Time.now.to_f * 1000).to_i,
'mp_lib' => 'ruby',
'$lib_version' => Mixpanel::VERSION,
).merge(properties).merge(identity.to_properties)
end
end
end
74 changes: 64 additions & 10 deletions lib/mixpanel-ruby/flags/flags_provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
require 'uri'
require 'mixpanel-ruby/version'
require 'mixpanel-ruby/error'
require 'mixpanel-ruby/identity'
require 'mixpanel-ruby/flags/utils'
require 'mixpanel-ruby/flags/types'

Expand All @@ -12,7 +13,7 @@ module Flags
# Base class for feature flags providers
# Provides common HTTP handling and exposure event tracking
class FlagsProvider
# @param provider_config [Hash] Configuration with :token, :api_host, :request_timeout_in_seconds, :exposure_executor, :credentials (optional)
# @param provider_config [Hash] Configuration with :token, :api_host, :request_timeout_in_seconds, :exposure_executor, :credentials (optional), :hierarchical_groups (optional)
# @param endpoint [String] API endpoint path (e.g., '/flags' or '/flags/definitions')
# @param tracker_callback [Proc] Function used to track events (bound tracker.track method)
# @param evaluation_mode [String] The feature flag evaluation mode. This is either 'local' or 'remote'
Expand All @@ -25,6 +26,7 @@ def initialize(provider_config, endpoint, tracker_callback, evaluation_mode, err
@error_handler = error_handler
@exposure_executor = provider_config[:exposure_executor]
@credentials = provider_config[:credentials]
@hierarchical_groups = provider_config[:hierarchical_groups] ? true : false
end

# Make HTTP request to flags API endpoint
Expand Down Expand Up @@ -102,36 +104,86 @@ def shutdown; end
def track_exposure_event(flag_key, selected_variant, context, latency_ms = nil)
distinct_id = context['distinct_id'] || context[:distinct_id]

unless distinct_id
unless can_attribute_exposure(context)
# Local eval succeeds when the flag's Variant Assignment Key is
# something other than distinct_id (e.g., device_id), but the
# exposure event still needs distinct_id to attribute the user.
# Surface the drop instead of silently returning so callers can
# see they need to include distinct_id in the context.
# exposure event still needs distinct_id ($company_id for
# hierarchical groups) to attribute the user. Surface the drop
# instead of silently returning so callers can see what to include
# in the context.
@error_handler&.handle(MixpanelError.new(
"Cannot track exposure event for flag '#{flag_key}' without a distinct_id in the context"
"Cannot track exposure event for flag '#{flag_key}' without a #{@hierarchical_groups ? '$company_id' : 'distinct_id'} in the context"
))
return
end

properties = {
'distinct_id' => distinct_id,
recipient = distinct_id
if @hierarchical_groups
# Sent as a Mixpanel::Identity, so the event carries whichever of
# distinct_id, $user_id and $company_id the context has, and no
# distinct_id when it has none.
recipient = hierarchical_exposure_identity(context)
properties = recipient.to_properties
else
properties = { 'distinct_id' => distinct_id }
end

properties.merge!(
'Experiment name' => flag_key,
'Variant name' => selected_variant.variant_key,
'$experiment_type' => 'feature_flag',
'Flag evaluation mode' => @evaluation_mode
}
)

properties['Variant fetch latency (ms)'] = latency_ms if latency_ms
properties['$experiment_id'] = selected_variant.experiment_id if selected_variant.experiment_id
properties['$is_experiment_active'] = selected_variant.is_experiment_active unless selected_variant.is_experiment_active.nil?
properties['$is_qa_tester'] = selected_variant.is_qa_tester unless selected_variant.is_qa_tester.nil?

dispatch_exposure(distinct_id, properties)
dispatch_exposure(recipient, properties)
end

private

# True if an exposure event for this context can be attributed: by
# distinct_id, or on a hierarchical groups project by $company_id as
# well, from which Mixpanel builds the distinct id.
def can_attribute_exposure(context)
unless @hierarchical_groups
return context['distinct_id'] || context[:distinct_id] ? true : false
end

present?(context_value(context, '$company_id')) || present?(context_value(context, 'distinct_id'))
end

def hierarchical_exposure_identity(context)
distinct_id = context_value(context, 'distinct_id')
user_id = context_value(context, '$user_id')
company_id = context_value(context, '$company_id')
distinct_id = nil unless present?(distinct_id)
company_id = nil unless present?(company_id)
user_id = nil unless present?(user_id)

Mixpanel::Identity.new(distinct_id: exposure_id(distinct_id), user_id: exposure_id(user_id),
company_id: exposure_id(company_id))
end

# A context value as an identity id: Strings and Integers as given,
# anything else as its string form, so an exposure is not lost to a
# context value Mixpanel::Identity does not accept.
def exposure_id(value)
value.nil? || value.is_a?(String) || value.is_a?(Integer) ? value : value.to_s
end

def context_value(context, key)
value = context[key]
value.nil? ? context[key.to_sym] : value
end

def present?(value)
!value.nil? && !value.to_s.empty?
end

# Dispatch the tracker call inline or via the configured executor.
# The executor is duck-typed — anything that responds to #post(&block)
# works (Concurrent::ExecutorService, or a Thread.new wrapper).
Expand All @@ -140,6 +192,8 @@ def track_exposure_event(flag_key, selected_variant, context, latency_ms = nil)
# doesn't terminate the executor thread silently. Inline path
# preserves the original behavior — non-MixpanelError propagates to
# the flag evaluator's caller unchanged.
#
# distinct_id is a Mixpanel::Identity on a hierarchical groups project.
def dispatch_exposure(distinct_id, properties)
if @exposure_executor
begin
Expand Down
54 changes: 45 additions & 9 deletions lib/mixpanel-ruby/flags/local_flags_provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,19 @@ class LocalFlagsProvider < FlagsProvider
exposure_executor: nil
}.freeze

# A {key} placeholder in a flag's context_value_template.
CONTEXT_PLACEHOLDER = /\{([^{}]+)\}/

# @param token [String] Mixpanel project token
# @param config [Hash] Local flags configuration
# @param tracker_callback [Proc] Callback to track events
# @param error_handler [Mixpanel::ErrorHandler] Error handler
# @param credentials [ServiceAccountCredentials, nil] Optional service account credentials
def initialize(token, config, tracker_callback, error_handler, credentials = nil)
# @param hierarchical_groups [Boolean] true if the project uses hierarchical
# groups (default false). On such a project an exposure event is attributed
# by $user_id and $company_id from the context, and tracker_callback receives
# a Mixpanel::Identity instead of a distinct_id string.
def initialize(token, config, tracker_callback, error_handler, credentials = nil, hierarchical_groups: false)
# compact: an explicit nil from the caller (e.g.
# polling_interval_in_seconds: nil) must not override a sane default.
# Both the previous sleep(nil) and the current
Expand All @@ -40,7 +47,8 @@ def initialize(token, config, tracker_callback, error_handler, credentials = nil
api_host: @config[:api_host],
request_timeout_in_seconds: @config[:request_timeout_in_seconds],
exposure_executor: @config[:exposure_executor],
credentials: credentials
credentials: credentials,
hierarchical_groups: hierarchical_groups
}

super(provider_config, '/flags/definitions', tracker_callback, 'local', error_handler)
Expand Down Expand Up @@ -175,13 +183,20 @@ def get_variant(flag_key, fallback_variant, context, report_exposure: true)
return fallback_variant.as_fallback(FallbackReason.flag_not_found) unless flag

context_key = flag['context']
unless context.key?(context_key) || context.key?(context_key.to_sym)
return fallback_variant.as_fallback(FallbackReason.missing_context_key(context_key))
end

context_value = context[context_key] || context[context_key.to_sym]
# The assignment key is the flag's context_value_template filled from the
# context. Without a template, or with a placeholder the context lacks,
# it is the raw context value, as the service does.
context_value = resolve_context_value_template(flag['context_value_template'], context)
if context_value.nil?
unless context.key?(context_key) || context.key?(context_key.to_sym)
return fallback_variant.as_fallback(FallbackReason.missing_context_key(context_key))
end

context_value = context[context_key] || context[context_key.to_sym]
end

selected_variant = get_variant_override_for_test_user(flag, context)
selected_variant = get_variant_override_for_test_user(flag, context, context_value)

unless selected_variant
rollout = get_assigned_rollout(flag, context_value, context)
Expand Down Expand Up @@ -241,11 +256,32 @@ def fetch_flag_definitions
response
end

def get_variant_override_for_test_user(flag, context)
# Fills a context_value_template with the string values of its placeholder
# keys from the evaluation context. Returns nil when there is no template
# or any placeholder's key is absent or nil.
def resolve_context_value_template(template, context)
return nil if template.nil? || template.empty?

missing = false
resolved = template.gsub(CONTEXT_PLACEHOLDER) do
value = context_value(context, Regexp.last_match(1))
missing = true if value.nil?
value.to_s
end
Comment thread
github-advanced-security[bot] marked this conversation as resolved.
Fixed
missing ? nil : resolved
end

def get_variant_override_for_test_user(flag, context, assignment_key)
test_users = flag.dig('ruleset', 'test', 'users')
return nil unless test_users

distinct_id = context['distinct_id'] || context[:distinct_id]
# Test users are keyed by distinct id. A flag assigned on distinct_id
# matches them by its resolved assignment key.
distinct_id = if flag['context'] == 'distinct_id'
assignment_key
else
context['distinct_id'] || context[:distinct_id]
end
return nil unless distinct_id

variant_key = test_users[distinct_id.to_s]
Expand Down
9 changes: 7 additions & 2 deletions lib/mixpanel-ruby/flags/remote_flags_provider.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,20 @@ class RemoteFlagsProvider < FlagsProvider
# @param tracker_callback [Proc] Callback to track events
# @param error_handler [Mixpanel::ErrorHandler] Error handler
# @param credentials [ServiceAccountCredentials, nil] Optional service account credentials
def initialize(token, config, tracker_callback, error_handler, credentials = nil)
# @param hierarchical_groups [Boolean] true if the project uses hierarchical
# groups (default false). On such a project an exposure event is attributed
# by $user_id and $company_id from the context, and tracker_callback receives
# a Mixpanel::Identity instead of a distinct_id string.
def initialize(token, config, tracker_callback, error_handler, credentials = nil, hierarchical_groups: false)
merged_config = DEFAULT_CONFIG.merge(config || {})

provider_config = {
token: token,
api_host: merged_config[:api_host],
request_timeout_in_seconds: merged_config[:request_timeout_in_seconds],
exposure_executor: merged_config[:exposure_executor],
credentials: credentials
credentials: credentials,
hierarchical_groups: hierarchical_groups
}

super(provider_config, '/flags', tracker_callback, 'remote', error_handler)
Expand Down
Loading
Loading