-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathfeatureflags.go
More file actions
2456 lines (2164 loc) · 79 KB
/
Copy pathfeatureflags.go
File metadata and controls
2456 lines (2164 loc) · 79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package posthog
import (
"bytes"
"context"
"crypto/sha1"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"net/http"
"net/url"
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
json "github.com/goccy/go-json"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
// LONG_SCALE is the denominator used to normalize feature flag hash values.
LONG_SCALE = 0xfffffffffffffff
bucketingIdentifierDevice = "device_id"
)
var relativeDateRegex = regexp.MustCompile(`^-?([0-9]+)([hdwmy])$`)
// Common sentinel errors for matchProperty — reused to avoid allocating new
// InconclusiveMatchError structs on every evaluation of flags with missing properties.
var (
errMissingPropertyValue = &InconclusiveMatchError{"Can't match properties without a given property value"}
errInconclusiveMatch = &InconclusiveMatchError{"Can't determine if feature flag is enabled or not with given properties"}
errAmbiguousExactNumber = &InconclusiveMatchError{"Can't match an integral JSON number locally because Go does not preserve whether it was an integer or float"}
errCohortPropertyValue = &InconclusiveMatchError{msg: "Can't match cohort without a given cohort property value"}
errCohortRequiresServerEval = &RequiresServerEvaluationError{msg: "cohort not found in local cohorts - likely a static cohort that requires server evaluation"}
)
// regexCache caches compiled regexps for flag property matching.
// The set of patterns is bounded by the number of flag conditions (loaded once),
// so this cache grows proportionally and avoids re-compiling on every evaluation.
var regexCache sync.Map // map[string]*regexp.Regexp
// getOrCompileRegex returns a cached compiled regexp for the given pattern,
// or compiles and caches it on first use.
func getOrCompileRegex(pattern string) (*regexp.Regexp, error) {
if cached, ok := regexCache.Load(pattern); ok {
return cached.(*regexp.Regexp), nil
}
r, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
// Store and return — concurrent stores of the same pattern are harmless
regexCache.Store(pattern, r)
return r, nil
}
// flagsState holds the feature flag data that is atomically swapped during updates.
// This provides lock-free reads for the common path (flag evaluation).
type flagsState struct {
featureFlags []FeatureFlag
flagsByKey map[string]FeatureFlag // pre-built index for O(1) lookup, avoids rebuilding per evaluation
cohorts map[string]PropertyGroup
groups map[string]string
flagsEtag string
// minimalFlagCalledEvents is the server-controlled gate for minimal
// $feature_flag_called events, cached from the local-evaluation payload.
minimalFlagCalledEvents bool
}
// FeatureFlagsPoller periodically loads feature flag definitions for local evaluation.
// Applications normally interact with it through Client methods rather than constructing it directly.
type FeatureFlagsPoller struct {
// firstFeatureFlagRequestFinished is used to log feature flag usage before the first feature flag request is done.
// After the request the channel get closed.
firstFeatureFlagRequestFinished chan bool
shutdown chan bool
forceReload chan bool
// state holds all flag-related data using atomic pointer for lock-free reads
state atomic.Pointer[flagsState]
personalApiKey string
projectApiKey string
localEvalUrl *url.URL
// Logger receives poller warnings and errors.
Logger Logger
// Endpoint is the PostHog API host used by the poller.
Endpoint string
http http.Client
nextPollTick func() time.Duration
flagTimeout time.Duration
decider decider
disableGeoIP bool
}
// FeatureFlag is a feature flag definition returned by the local evaluation endpoint.
type FeatureFlag struct {
// Key is the feature flag key.
Key string `json:"key"`
// RolloutPercentage is the top-level rollout percentage, when configured.
RolloutPercentage *float64 `json:"rollout_percentage"`
// Active reports whether the flag is active.
Active bool `json:"active"`
// Filters contains matching conditions, variants, and payloads.
Filters Filter `json:"filters"`
// EnsureExperienceContinuity indicates that the flag requires server-side continuity checks.
EnsureExperienceContinuity *bool `json:"ensure_experience_continuity"`
// BucketingIdentifier optionally selects the property used for hash bucketing.
BucketingIdentifier *string `json:"bucketing_identifier"`
// HasExperiment reports whether the flag is linked to an experiment.
// Nil when the server does not send it (older deployments).
HasExperiment *bool `json:"has_experiment"`
}
// Filter contains the targeting rules, variants, and payloads for a FeatureFlag.
type Filter struct {
// AggregationGroupTypeIndex identifies the group type for group-targeted flags.
AggregationGroupTypeIndex *uint8 `json:"aggregation_group_type_index"`
// Groups contains the ordered condition groups to evaluate.
Groups []FeatureFlagCondition `json:"groups"`
// EarlyExit, when true, stops local condition evaluation and returns a
// definitive disabled result as soon as a condition group matches its
// property filters (or has none) but the rollout percentage excludes the
// user, instead of falling through to later condition groups.
EarlyExit bool `json:"early_exit"`
// Multivariate contains variant definitions for multivariate flags.
Multivariate *Variants `json:"multivariate"`
// Payloads maps flag values or variant keys to raw JSON payloads.
Payloads map[string]json.RawMessage `json:"payloads"`
// DecodedPayloads holds pre-decoded string versions of Payloads.
// Built once at flag load time to avoid per-evaluation json.Unmarshal / unquoting.
DecodedPayloads map[string]string `json:"-"`
// VariantLookupTable is pre-computed at flag load time to avoid per-evaluation
// slice allocation for multivariate flags.
VariantLookupTable []FlagVariantMeta `json:"-"`
}
// Variants contains all variants configured for a multivariate feature flag.
type Variants struct {
// Variants is the ordered list of possible flag variants.
Variants []FlagVariant `json:"variants"`
}
// FlagVariant describes one multivariate feature flag variant.
type FlagVariant struct {
// Key is the stable variant key returned by flag evaluation.
Key string `json:"key"`
// Name is the display name for the variant.
Name string `json:"name"`
// RolloutPercentage is the percentage allocated to this variant.
RolloutPercentage *float64 `json:"rollout_percentage"`
}
// FeatureFlagCondition describes one condition group for a feature flag.
type FeatureFlagCondition struct {
// Properties are the targeting rules in this condition group.
Properties []FlagProperty `json:"properties"`
// RolloutPercentage is the rollout percentage for this condition group.
RolloutPercentage *float64 `json:"rollout_percentage"`
// Variant is the variant key forced by this condition group, when any.
Variant *string `json:"variant"`
// AggregationGroupTypeIndex identifies the group type for this condition group.
AggregationGroupTypeIndex *uint8 `json:"aggregation_group_type_index"`
}
// FlagProperty describes one property matcher in a feature flag or cohort condition.
type FlagProperty struct {
// Key is the property key to read.
Key string `json:"key"`
// Operator is the comparison operator, such as exact, is_not, or regex.
Operator string `json:"operator"`
// Value is the comparison value for Operator.
Value interface{} `json:"value"`
// Type is the property source. Supported values include "person", "group", "cohort", and "flag".
Type string `json:"type"`
// Negation inverts the property match when true.
Negation bool `json:"negation"`
// DependencyChain tracks feature flag dependencies while evaluating nested flag properties.
DependencyChain []string `json:"dependency_chain"`
}
// PropertyGroup describes a nested property group used by cohorts and flag conditions.
type PropertyGroup struct {
// Type is the boolean operator joining Values, such as AND or OR.
Type string `json:"type"`
// Values contains nested PropertyGroup values or FlagProperty values.
Values []any `json:"values"`
// ParsedValues holds pre-parsed typed values from Values.
// Built once at flag load time to avoid reconstructing FlagProperty/PropertyGroup
// from map[string]any on every cohort evaluation.
ParsedValues []parsedPropertyValue `json:"-"`
}
// parsedPropertyValue is a union holding either a nested PropertyGroup or a FlagProperty.
// Exactly one field is set. Avoids per-evaluation type assertion and reconstruction.
type parsedPropertyValue struct {
IsGroup bool
Group PropertyGroup
Property FlagProperty
}
// FlagVariantMeta is a precomputed hash range for a feature flag variant.
type FlagVariantMeta struct {
// ValueMin is the inclusive lower bound of the normalized hash range.
ValueMin float64
// ValueMax is the exclusive upper bound of the normalized hash range.
ValueMax float64
// Key is the variant key for this hash range.
Key string
}
// FeatureFlagsResponse is the wire-format response from the local evaluation endpoint.
type FeatureFlagsResponse struct {
// Flags contains feature flag definitions for local evaluation.
Flags []FeatureFlag `json:"flags"`
// GroupTypeMapping maps group type indexes to group type names.
GroupTypeMapping *map[string]string `json:"group_type_mapping"`
// Cohorts contains cohort definitions referenced by local feature flags.
Cohorts map[string]PropertyGroup `json:"cohorts"`
// MinimalFlagCalledEvents reports whether the server enabled minimal
// $feature_flag_called events for this project. The server sends it only
// when the gate is on; absence means full events.
MinimalFlagCalledEvents bool `json:"minimal_flag_called_events"`
}
// DecideRequestData is the legacy wire-format request body for flag decide calls.
type DecideRequestData struct {
// ApiKey is the PostHog project API key.
ApiKey string `json:"api_key"`
// DistinctId is the user distinct ID to evaluate flags for.
DistinctId string `json:"distinct_id"`
// Groups contains group identifiers for group-targeted flags.
Groups Groups `json:"groups"`
// PersonProperties overrides person properties for this evaluation.
PersonProperties Properties `json:"person_properties"`
// GroupProperties overrides group properties for this evaluation, keyed by group type.
GroupProperties map[string]Properties `json:"group_properties"`
}
// DecideResponse is the legacy wire-format response body for flag decide calls.
type DecideResponse struct {
// FeatureFlags contains evaluated flag values keyed by flag key.
FeatureFlags map[string]interface{} `json:"featureFlags"`
// FeatureFlagPayloads contains raw payloads keyed by flag key.
FeatureFlagPayloads map[string]json.RawMessage `json:"featureFlagPayloads"`
}
// InconclusiveMatchError indicates that local evaluation could not conclusively match a condition.
type InconclusiveMatchError struct {
msg string
}
// Error returns the inconclusive match message.
func (e *InconclusiveMatchError) Error() string {
return e.msg
}
// RequiresServerEvaluationError is returned when feature flag evaluation
// requires server-side data that is not available locally (e.g., static cohorts,
// experience continuity). This error should propagate immediately to trigger
// API fallback, unlike InconclusiveMatchError which allows trying other conditions.
type RequiresServerEvaluationError struct {
msg string
}
// Error returns the reason server-side evaluation is required.
func (e *RequiresServerEvaluationError) Error() string {
return e.msg
}
// isServerEvalError returns true if err is a RequiresServerEvaluationError.
// Uses type assertion instead of errors.As to avoid pointer-variable heap escapes.
func isServerEvalError(err error) bool {
_, ok := err.(*RequiresServerEvaluationError)
return ok
}
// isInconclusiveError returns true if err is an InconclusiveMatchError.
func isInconclusiveError(err error) bool {
_, ok := err.(*InconclusiveMatchError)
return ok
}
// FeatureFlagResult represents the result of a feature flag evaluation,
// containing both the flag value and its payload.
type FeatureFlagResult struct {
// Key is the feature flag key that was evaluated
Key string
// Enabled indicates whether the feature flag evaluation determined
// the flag to be in an enabled state.
Enabled bool
// RawPayload is the serialized JSON payload associated with the flag variant.
// Nil if no payload is configured.
// Use GetPayloadAs to unmarshal the payload into a specific type.
RawPayload *string
// Variant is the variant key if this is a multivariate flag.
// Nil for boolean flags.
Variant *string
// payloadStore and variantStore hold the actual string values so that
// RawPayload/Variant can point into the same allocation as the struct itself,
// avoiding separate heap escapes for the *string pointers.
payloadStore string
variantStore string
}
// GetPayloadAs unmarshals the JSON payload into the provided type.
// Returns an error if the payload is empty or cannot be unmarshaled.
func (r *FeatureFlagResult) GetPayloadAs(v interface{}) error {
if r.RawPayload == nil || *r.RawPayload == "" {
return errors.New("no payload available")
}
return json.Unmarshal([]byte(*r.RawPayload), v)
}
// evaluateFlagDependency evaluates a flag dependency property according to the dependency chain algorithm
func (poller *FeatureFlagsPoller) evaluateFlagDependency(
property FlagProperty,
flagsByKey map[string]FeatureFlag,
evaluationCache map[string]interface{},
distinctId string,
deviceId *string,
properties Properties,
cohorts map[string]PropertyGroup,
) (bool, error) {
// Some of these conditions should never happen, but we'll check them to be defensive.
if property.Value == nil {
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency on '%s' without a value", property.Key),
}
}
if property.Operator != "flag_evaluates_to" {
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Unsupported operator '%s' for flag dependency '%s'", property.Operator, property.Key),
}
}
if flagsByKey == nil || evaluationCache == nil {
// Cannot evaluate flag dependencies without required context
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency on '%s' without flagsByKey and evaluationCache", property.Key),
}
}
// Check if dependency_chain is present - it should always be provided for flag dependencies
if property.DependencyChain == nil {
// Missing dependency_chain indicates malformed server data
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Flag dependency property for '%s' is missing required 'dependency_chain' field", property.Key),
}
}
dependencyChain := property.DependencyChain
// Handle circular dependency (empty chain means circular)
if len(dependencyChain) == 0 {
if poller.Logger != nil {
poller.Logger.Debugf("Circular dependency detected for flag: %s", property.Key)
}
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Circular dependency detected for flag '%s'", property.Key),
}
}
// Evaluate all dependencies in the chain order
for _, depFlagKey := range dependencyChain {
if _, exists := evaluationCache[depFlagKey]; exists {
continue
}
// Need to evaluate this dependency first
depFlag, flagExists := flagsByKey[depFlagKey]
if !flagExists {
// Missing flag dependency - cannot evaluate locally
evaluationCache[depFlagKey] = nil
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency '%s' - flag not found in local flags", depFlagKey),
}
}
// Check if the flag is active (same check as in computeFlagLocally)
if !depFlag.Active {
evaluationCache[depFlagKey] = false
} else {
// Recursively evaluate the dependency
result, err := poller.matchFeatureFlagProperties(depFlag, distinctId, deviceId, properties, cohorts, flagsByKey, evaluationCache, nil, nil)
if err != nil {
// If we can't evaluate a dependency, store nil and propagate the error
evaluationCache[depFlagKey] = nil
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Cannot evaluate flag dependency '%s': %s", depFlagKey, err.Error()),
}
}
evaluationCache[depFlagKey] = result
}
}
// Check if the dependency result matches the expected value and operator
if cachedResult, exists := evaluationCache[property.Key]; exists && cachedResult != nil {
match, err := checkFlagDependencyValue(property.Value, cachedResult)
if err != nil {
return false, err
}
return match, nil
}
// The main dependency couldn't be evaluated
return false, &InconclusiveMatchError{
msg: fmt.Sprintf("Flag dependency '%s' could not be evaluated for value comparison", property.Key),
}
}
// checkFlagDependencyValue checks if a flag dependency result matches the expected value and operator
func checkFlagDependencyValue(expectedValue interface{}, actualResult interface{}) (bool, error) {
// String variant case - check for exact match or boolean true
if actualStr, ok := actualResult.(string); ok && len(actualStr) > 0 {
if expectedBool, ok := expectedValue.(bool); ok {
// Any variant matches boolean true
return expectedBool, nil
} else if expectedStr, ok := expectedValue.(string); ok {
// variants are case-sensitive, hence our comparison is too
return actualStr == expectedStr, nil
} else {
return false, nil
}
}
// Boolean case - must match expected boolean value
if actualBool, ok := actualResult.(bool); ok {
if expectedBool, ok := expectedValue.(bool); ok {
return actualBool == expectedBool, nil
}
}
// Default case
return false, nil
}
func newFeatureFlagsPoller(
projectApiKey string,
personalApiKey string,
logger Logger,
endpoint string,
httpClient http.Client,
pollingInterval time.Duration,
nextPollTick func() time.Duration,
flagTimeout time.Duration,
decider decider,
disableGeoIP bool,
) (*FeatureFlagsPoller, error) {
localEvaluationEndpoint := "/flags/definitions"
localEvalURL, err := url.Parse(endpoint + localEvaluationEndpoint)
if err != nil {
return nil, fmt.Errorf("creating local evaluation URL - %w", err)
}
if nextPollTick == nil {
nextPollTick = func() time.Duration { return pollingInterval }
}
poller := FeatureFlagsPoller{
firstFeatureFlagRequestFinished: make(chan bool),
shutdown: make(chan bool),
forceReload: make(chan bool),
personalApiKey: personalApiKey,
projectApiKey: projectApiKey,
localEvalUrl: localEvalURL,
Logger: logger,
Endpoint: endpoint,
http: httpClient,
nextPollTick: nextPollTick,
flagTimeout: flagTimeout,
decider: decider,
disableGeoIP: disableGeoIP,
}
go poller.run()
return &poller, nil
}
func (poller *FeatureFlagsPoller) run() {
poller.fetchNewFeatureFlags()
close(poller.firstFeatureFlagRequestFinished)
for {
timer := time.NewTimer(poller.nextPollTick())
select {
case <-poller.shutdown:
close(poller.forceReload)
timer.Stop()
return
case <-poller.forceReload:
timer.Stop()
poller.fetchNewFeatureFlags()
case <-timer.C:
poller.fetchNewFeatureFlags()
}
}
}
// fetchNewFeatureFlags fetches the latest feature flag definitions from the PostHog API
// These are used for local evaluation of feature flags and should not be confused with
// the feature flags fetched from the flags API.
func (poller *FeatureFlagsPoller) fetchNewFeatureFlags() {
personalApiKey := poller.personalApiKey
headers := http.Header{"Authorization": []string{"Bearer " + personalApiKey}}
// Read current ETag from state (lock-free)
currentState := poller.state.Load()
currentEtag := ""
if currentState != nil {
currentEtag = currentState.flagsEtag
}
res, cancel, err := poller.localEvaluationFlags(headers, currentEtag)
if err != nil {
poller.Logger.Errorf("Unable to fetch feature flags: %s", err)
return
}
defer cancel()
defer res.Body.Close()
// Handle 304 Not Modified - flags haven't changed, skip processing
if res.StatusCode == http.StatusNotModified {
poller.Logger.Debugf("[FEATURE FLAGS] Flags not modified (304), using cached data")
// Update ETag if server returned one (preserve existing if not)
if newEtag := res.Header.Get("ETag"); newEtag != "" && currentState != nil {
// Atomically swap with updated ETag
newState := &flagsState{
featureFlags: currentState.featureFlags,
flagsByKey: currentState.flagsByKey,
cohorts: currentState.cohorts,
groups: currentState.groups,
flagsEtag: newEtag,
minimalFlagCalledEvents: currentState.minimalFlagCalledEvents,
}
poller.state.Store(newState)
}
return
}
// Handle quota limit response (HTTP 402)
if res.StatusCode == http.StatusPaymentRequired {
// Clear existing flags when quota limited - atomic swap
poller.state.Store(&flagsState{
featureFlags: []FeatureFlag{},
cohorts: map[string]PropertyGroup{},
groups: map[string]string{},
flagsEtag: "",
})
poller.Logger.Warnf("[FEATURE FLAGS] PostHog feature flags quota limited, resetting feature flag data. Learn more about billing limits at https://posthog.com/docs/billing/limits-alerts")
return
}
if res.StatusCode != http.StatusOK {
poller.Logger.Errorf("Unable to fetch feature flags, status: %s", res.Status)
return
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
poller.Logger.Errorf("Unable to fetch feature flags: %s", err)
return
}
var featureFlagsResponse FeatureFlagsResponse
if err = json.Unmarshal(resBody, &featureFlagsResponse); err != nil {
poller.Logger.Errorf("Unable to unmarshal response from api/feature_flag/local_evaluation: %s", err)
return
}
newFlags := append(make([]FeatureFlag, 0, len(featureFlagsResponse.Flags)), featureFlagsResponse.Flags...)
// Pre-decode payloads once at load time (avoids per-evaluation json unquoting)
preDecodePayloads(newFlags)
// Pre-build flagsByKey index for O(1) lookup during evaluation
flagsByKey := buildFlagsByKey(newFlags)
// Store new ETag from response (clear if server stops sending)
newEtag := res.Header.Get("ETag")
// Build new groups map
groups := map[string]string{}
if featureFlagsResponse.GroupTypeMapping != nil {
groups = *featureFlagsResponse.GroupTypeMapping
}
// Pre-parse cohort values into typed structs (avoids per-evaluation reconstruction)
parsedCohorts := preParseCohortValues(featureFlagsResponse.Cohorts)
// Atomic swap of entire state
poller.state.Store(&flagsState{
featureFlags: newFlags,
flagsByKey: flagsByKey,
cohorts: parsedCohorts,
groups: groups,
flagsEtag: newEtag,
minimalFlagCalledEvents: featureFlagsResponse.MinimalFlagCalledEvents,
})
}
// getMinimalFlagCalledEvents reports whether the local-evaluation payload
// enabled minimal $feature_flag_called events. False until definitions have
// been loaded, so missing state always yields full events.
func (poller *FeatureFlagsPoller) getMinimalFlagCalledEvents() bool {
state := poller.state.Load()
return state != nil && state.minimalFlagCalledEvents
}
// GetFeatureFlag evaluates one flag using locally loaded definitions when possible.
// It returns the flag value, whether that value was locally evaluated, and an error.
// If local evaluation is inconclusive and OnlyEvaluateLocally is false, it falls back to /flags.
func (poller *FeatureFlagsPoller) GetFeatureFlag(flagConfig FeatureFlagPayload) (interface{}, bool, error) {
flag, err := poller.getFeatureFlag(flagConfig)
var result interface{}
locallyEvaluated := false
if flag.Key != "" {
result, err = poller.computeFlagLocally(
flag,
flagConfig.DistinctId,
flagConfig.DeviceId,
flagConfig.Groups,
flagConfig.PersonProperties,
flagConfig.GroupProperties,
poller.getCohorts(),
)
locallyEvaluated = err == nil && result != nil
}
if err != nil {
poller.Logger.Warnf("Unable to compute flag locally (%s) - %s", flagConfig.Key, err)
}
if (err != nil || result == nil) && !flagConfig.OnlyEvaluateLocally {
result, err = poller.getFeatureFlagVariant(flagConfig.Key, flagConfig.DistinctId, flagConfig.DeviceId, flagConfig.Groups, flagConfig.PersonProperties, flagConfig.GroupProperties)
if err != nil {
return nil, locallyEvaluated, err
}
}
return result, locallyEvaluated, err
}
// GetFeatureFlagPayload returns the payload for the evaluated flag value.
// It tries local payloads first and falls back to the remote API unless OnlyEvaluateLocally is true.
func (poller *FeatureFlagsPoller) GetFeatureFlagPayload(flagConfig FeatureFlagPayload) (string, error) {
flag, err := poller.getFeatureFlag(flagConfig)
var variant interface{}
if flag.Key != "" {
variant, err = poller.computeFlagLocally(
flag,
flagConfig.DistinctId,
flagConfig.DeviceId,
flagConfig.Groups,
flagConfig.PersonProperties,
flagConfig.GroupProperties,
poller.getCohorts(),
)
}
if err != nil {
poller.Logger.Warnf("Unable to compute flag locally (%s) - %s", flagConfig.Key, err)
} else if variant != nil {
if decoded, ok := flag.Filters.DecodedPayloads[variantToString(variant)]; ok {
return decoded, nil
}
}
if (variant == nil || err != nil) && !flagConfig.OnlyEvaluateLocally {
result, err := poller.getFeatureFlagPayload(flagConfig.Key, flagConfig.DistinctId, flagConfig.DeviceId, flagConfig.Groups, flagConfig.PersonProperties, flagConfig.GroupProperties)
if err != nil {
return "", err
}
return result, nil
}
return "", errors.New("unable to compute flag locally")
}
// flagValueAndPayload holds the result of a single flag evaluation that returns
// both the flag value and its payload, avoiding the need for double evaluation.
type flagValueAndPayload struct {
value interface{}
payload string
err error
locallyEvaluated bool
hasExperiment *bool
// minimalFlagCalledEvents carries the minimal $feature_flag_called gate
// from whichever source produced the value (local definitions or the
// remote /flags response).
minimalFlagCalledEvents bool
}
// GetFeatureFlagWithPayload evaluates a feature flag once and returns both its value
// and payload. This avoids the double evaluation that would happen when calling
// GetFeatureFlag and GetFeatureFlagPayload separately.
func (poller *FeatureFlagsPoller) GetFeatureFlagWithPayload(flagConfig FeatureFlagPayload) flagValueAndPayload {
flag, err := poller.getFeatureFlag(flagConfig)
var result interface{}
if flag.Key != "" {
result, err = poller.computeFlagLocally(
flag,
flagConfig.DistinctId,
flagConfig.DeviceId,
flagConfig.Groups,
flagConfig.PersonProperties,
flagConfig.GroupProperties,
poller.getCohorts(),
)
}
if err != nil {
poller.Logger.Warnf("Unable to compute flag locally (%s) - %s", flagConfig.Key, err)
}
// Try to resolve payload from local evaluation result using pre-decoded payloads
var payload string
if err == nil && result != nil {
variantKey := variantToString(result)
if decoded, ok := flag.Filters.DecodedPayloads[variantKey]; ok {
payload = decoded
}
}
locallyEvaluated := err == nil && result != nil
hasExperiment := flag.HasExperiment
minimalFlagCalledEvents := poller.getMinimalFlagCalledEvents()
// Fall back to remote evaluation if local didn't produce a result
if (err != nil || result == nil) && !flagConfig.OnlyEvaluateLocally {
flagsResponse, remoteErr := poller.getFeatureFlagVariants(flagConfig.DistinctId, flagConfig.DeviceId, flagConfig.Groups, flagConfig.PersonProperties, flagConfig.GroupProperties)
if remoteErr != nil {
return flagValueAndPayload{value: nil, err: remoteErr}
}
locallyEvaluated = false
// Clear local eval error — we successfully made a remote request
err = nil
// The remote response is now the source of the flag value, so it is
// also the source of has_experiment and of the minimal-event gate:
// reset both and only pick them up from the response.
hasExperiment = nil
minimalFlagCalledEvents = false
if flagsResponse != nil {
minimalFlagCalledEvents = flagsResponse.MinimalFlagCalledEvents
if flagValue, ok := flagsResponse.FeatureFlags[flagConfig.Key]; ok {
result = flagValue
} else {
// Flag not in remote response — treat as false (matches getFeatureFlagVariant behavior)
result = false
}
if rawPayload, ok := flagsResponse.FeatureFlagPayloads[flagConfig.Key]; ok {
payload = rawMessageToString(rawPayload)
}
if detail, ok := flagsResponse.Flags[flagConfig.Key]; ok {
hasExperiment = detail.Metadata.HasExperiment
}
} else {
result = false
}
}
return flagValueAndPayload{value: result, payload: payload, err: err, locallyEvaluated: locallyEvaluated, hasExperiment: hasExperiment, minimalFlagCalledEvents: minimalFlagCalledEvents}
}
func (poller *FeatureFlagsPoller) getFeatureFlag(flagConfig FeatureFlagPayload) (FeatureFlag, error) {
// Wait for initial flag fetch to complete
<-poller.firstFeatureFlagRequestFinished
// Use pre-built index for O(1) lookup instead of linear scan
flagsByKey := poller.getFlagsByKey()
if flagsByKey == nil {
return FeatureFlag{}, errors.New("flags were not successfully fetched yet")
}
if f, ok := flagsByKey[flagConfig.Key]; ok {
return f, nil
}
return FeatureFlag{}, nil
}
// GetAllFlags evaluates every available flag for the configured user.
// Values are bools for boolean flags or strings for multivariate variants.
func (poller *FeatureFlagsPoller) GetAllFlags(flagConfig FeatureFlagPayloadNoKey) (map[string]interface{}, error) {
featureFlags, err := poller.GetFeatureFlags()
if err != nil {
return nil, err
}
fallbackToDecide := false
cohorts := poller.getCohorts()
// Pre-size response map to avoid rehashing as flags are added
response := make(map[string]interface{}, len(featureFlags))
if len(featureFlags) == 0 {
fallbackToDecide = true
} else {
for _, storedFlag := range featureFlags {
result, err := poller.computeFlagLocally(
storedFlag,
flagConfig.DistinctId,
flagConfig.DeviceId,
flagConfig.Groups,
flagConfig.PersonProperties,
flagConfig.GroupProperties,
cohorts,
)
if err != nil {
poller.Logger.Warnf("Unable to compute flag locally (%s) - %s", storedFlag.Key, err)
fallbackToDecide = true
} else {
response[storedFlag.Key] = result
}
}
}
if fallbackToDecide && !flagConfig.OnlyEvaluateLocally {
flagsResponse, err := poller.getFeatureFlagVariants(
flagConfig.DistinctId,
flagConfig.DeviceId,
flagConfig.Groups,
flagConfig.PersonProperties,
flagConfig.GroupProperties,
)
if err != nil {
return response, err
}
if flagsResponse != nil {
for k, v := range flagsResponse.FeatureFlags {
response[k] = v
}
}
}
return response, nil
}
func (poller *FeatureFlagsPoller) computeFlagLocally(
flag FeatureFlag,
distinctId string,
deviceId *string,
groups Groups,
personProperties Properties,
groupProperties map[string]Properties,
cohorts map[string]PropertyGroup,
) (interface{}, error) {
if flag.EnsureExperienceContinuity != nil && *flag.EnsureExperienceContinuity {
return nil, &InconclusiveMatchError{"Flag has experience continuity enabled"}
}
if !flag.Active {
return false, nil
}
// Use pre-built flagsByKey index (built once when flags are fetched, not per evaluation)
flagsByKey := poller.getFlagsByKey()
// evaluationCache is created lazily — only allocated when flag has dependencies.
// For simple flags (no dependencies), this avoids a map allocation per evaluation.
var evaluationCache map[string]interface{}
if flagHasDependencies(flag) {
evaluationCache = make(map[string]interface{})
}
if flag.Filters.AggregationGroupTypeIndex != nil {
groupType, exists := poller.getGroups()[fmt.Sprintf("%d", *flag.Filters.AggregationGroupTypeIndex)]
if !exists {
errMessage := "flag has unknown group type index"
return nil, errors.New(errMessage)
}
groupKey, exists := groups[groupType]
if !exists {
errMessage := fmt.Sprintf("[FEATURE FLAGS] Can't compute group feature flag: %s without group names passed in", flag.Key)
return nil, errors.New(errMessage)
}
focusedGroupProperties := groupProperties[groupType]
if _, ok := focusedGroupProperties["$group_key"]; !ok {
focusedGroupProperties = Properties{"$group_key": groupKey}.Merge(focusedGroupProperties)
}
return poller.matchFeatureFlagProperties(flag, groups[groupType].(string), nil, focusedGroupProperties, cohorts, flagsByKey, evaluationCache, groups, groupProperties)
} else {
localPersonProperties := personProperties
// Only add distinct_id if the flag has conditions that check person properties.
// For simple flags (no property conditions), this avoids creating a map that's never read.
if flagHasPersonProperties(flag) {
if _, ok := localPersonProperties["distinct_id"]; !ok {
if personProperties == nil {
localPersonProperties = Properties{"distinct_id": distinctId}
} else {
localPersonProperties = make(Properties, len(personProperties)+1)
localPersonProperties["distinct_id"] = distinctId
for k, v := range personProperties {
localPersonProperties[k] = v
}
}
}
}
return poller.matchFeatureFlagProperties(flag, distinctId, deviceId, localPersonProperties, cohorts, flagsByKey, evaluationCache, groups, groupProperties)
}
}
func getMatchingVariant(flag FeatureFlag, bucketingId string) interface{} {
// Use pre-computed lookup table if available, otherwise compute on the fly
lookupTable := flag.Filters.VariantLookupTable
if lookupTable == nil {
// Fast path: no multivariate variants means boolean flag — skip hash computation
if flag.Filters.Multivariate == nil || len(flag.Filters.Multivariate.Variants) == 0 {
return true
}
lookupTable = getVariantLookupTable(flag)
}
if len(lookupTable) == 0 {
return true
}
hashValue := calculateHash(flag.Key, bucketingId, "variant")
for _, variant := range lookupTable {
if hashValue >= float64(variant.ValueMin) && hashValue < float64(variant.ValueMax) {
return variant.Key
}
}
return true
}
func getBucketingID(flag FeatureFlag, distinctId string, deviceId *string) string {
if flag.BucketingIdentifier != nil && *flag.BucketingIdentifier == bucketingIdentifierDevice && deviceId != nil {
return *deviceId
}
return distinctId
}
func getVariantLookupTable(flag FeatureFlag) []FlagVariantMeta {
multivariates := flag.Filters.Multivariate
if multivariates == nil || multivariates.Variants == nil {
return nil
}
lookupTable := make([]FlagVariantMeta, 0, len(multivariates.Variants))
valueMin := 0.00
for _, variant := range multivariates.Variants {
valueMax := valueMin + *variant.RolloutPercentage/100.
lookupTable = append(lookupTable, FlagVariantMeta{ValueMin: valueMin, ValueMax: valueMax, Key: variant.Key})
valueMin = valueMax
}
return lookupTable
}
func (poller *FeatureFlagsPoller) matchFeatureFlagProperties(
flag FeatureFlag,
distinctId string,
deviceId *string,
properties Properties,
cohorts map[string]PropertyGroup,
flagsByKey map[string]FeatureFlag,
evaluationCache map[string]interface{},
groups Groups,
groupProperties map[string]Properties,
) (interface{}, error) {
conditions := flag.Filters.Groups
bucketingId := getBucketingID(flag, distinctId, deviceId)
flagAggregation := flag.Filters.AggregationGroupTypeIndex
groupTypeMapping := poller.getGroups()
isInconclusive := false
for _, condition := range conditions {
// Per-condition aggregation overrides only when the condition explicitly
// sets its own AggregationGroupTypeIndex that differs from the flag level
// (mixed targeting). When absent, fall back to the flag-level aggregation
// so existing pure person and pure group flags keep their original behavior.
conditionAggregation := condition.AggregationGroupTypeIndex
if conditionAggregation == nil {
conditionAggregation = flagAggregation
}
effectiveProperties := properties
effectiveBucketingId := bucketingId