Skip to content

feat(flags): IsEnabled accepts a caller-supplied default value - #277

Closed
posthog[bot] wants to merge 2 commits into
mainfrom
posthog-code/go-is-enabled-default-value
Closed

feat(flags): IsEnabled accepts a caller-supplied default value#277
posthog[bot] wants to merge 2 commits into
mainfrom
posthog-code/go-is-enabled-default-value

Conversation

@posthog

@posthog posthog Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Brings FeatureFlagEvaluations.IsEnabled into compliance with the cross-SDK is-feature-enabled contract: a hard SHALL, @both-tagged requirement with no server-SDK carve-out — the SDK must accept a caller-supplied boolean default and return it whenever the flag has no value (missing key, flags not loaded yet, or a failed /flags request). A flag that resolves to a real value, including false or a variant string, always wins over the default.

Flagged in the sdk-specs compliance matrix: posthog-go.md#n12 ("Is Feature Enabled — ❌ Fail"). Neither IsEnabled nor the deprecated legacy IsFeatureEnabled/GetFeatureFlag (FeatureFlagPayload) had a way for a caller to override a miss — both collapsed unconditionally to false.

This PR only touches the canonical, non-deprecated FeatureFlagEvaluations.IsEnabled path (the API the package doc already recommends for new code). The legacy IsFeatureEnabled/GetFeatureFlag surface is marked // Deprecated: Prefer EvaluateFlags for new code. in posthog.go, so it's intentionally left alone — the identical remediation in posthog-python's legacy feature_enabled() was attempted and closed without merge (posthog-python#859), while fixing the canonical is_enabled() there was accepted and merged (posthog-python#800).

Backwards compatibility

Purely additive — defaultValue is a new variadic ...bool parameter. Go has no optional/default parameters or overloading, so a variadic tail is the idiomatic way to add an optional argument without breaking any existing call site; IsEnabled(key) continues to behave exactly as before (falls back to false on a miss). Callers can now opt in with IsEnabled(key, true) to get a true fallback instead.

💚 How did you test it?

  • Added three new tests to feature_flag_evaluations_test.go:
    • TestIsEnabled_ReturnsCallerDefaultOnMiss — an unknown flag key returns false with no default, and returns the caller-supplied true/false default when passed.
    • TestIsEnabled_RealValueWinsOverCallerDefault — a flag that resolves to a real false (or true) value is never overridden by an opposite caller-supplied default.
    • TestIsEnabled_NilSnapshotReturnsCallerDefault — a nil *FeatureFlagEvaluations receiver also honors the caller-supplied default.
  • Ran the full test suite (go test ./...) — all passing.
  • gofmt -l . and go vet ./... — clean.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed. (doc comment on IsEnabled updated; no README signature to update)
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Added a .changeset/is-enabled-default-value.md changeset file

🤖 Agent context

Autonomy: Fully autonomous — this PR was generated by a scheduled compliance-audit loop that reads the SDK compliance matrices in PostHog/sdk-specs and implements one well-scoped, backward-compatible gap per run. No human directed this specific change; left unassigned for the owning team to triage.

  • Tooling: Claude Code (Sonnet 5), running an unattended daily loop over compliance/*.md in PostHog/sdk-specs.
  • Selection: Of the open gaps across 12 SDKs, this was a hard spec SHALL (not a nice-to-have), high-impact (core flag-evaluation API used on nearly every request path), narrowly scoped (one additive parameter), and — after checking open/closed PRs across all affected repos — the only one of 6 affected server SDKs (python, node, php, ruby, go, dotnet) with neither an existing open PR (posthog-php has one open) nor a prior rejected attempt (posthog-python's legacy-method attempt was closed) covering it.
  • Scope decision: Deliberately did not touch the deprecated IsFeatureEnabled/GetFeatureFlag legacy path, following the precedent set by posthog-python's closed PR #859.

Closes the posthog-go × Is Feature Enabled cell in the sdk-specs compliance matrix.

Brings `FeatureFlagEvaluations.IsEnabled` into compliance with the cross-SDK `is-feature-enabled` contract: a hard SHALL requirement that the SDK accept a caller-supplied boolean default and return it whenever the flag has no value (missing key, flags not loaded, or a failed /flags request), while any real flag value — including false or a variant — always wins over the default.

Adds an optional variadic `defaultValue ...bool` parameter so existing calls remain source-compatible.

Generated-By: PostHog Code
Task-Id: 7ee84317-3a73-41e1-bc25-906b7c14be53
@github-actions

github-actions Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

posthog-go Compliance Report

Date: 2026-08-09 16:40:16 UTC
Duration: 169005ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 45ms
Endpoint And Method.Does Not Use Legacy Endpoints 4ms
Required Headers.Has Authorization Bearer Header 6ms
Required Headers.Has Content Type Json 5ms
Required Headers.Has Posthog Sdk Info Format 4ms
Required Headers.Has Posthog Attempt Header 5ms
Required Headers.Has Posthog Request Id 5ms
Required Headers.Has Posthog Request Timestamp 4ms
Required Headers.Has User Agent 5ms
Body Format.Body Has Created At And Batch 5ms
Body Format.No Api Key In Body 4ms
Body Format.No Sent At In Body 5ms
Event Format.Event Has Required Root Fields 5ms
Event Format.Event Uuid Is Valid 4ms
Event Format.Event Timestamp Is Rfc3339 5ms
Event Format.Distinct Id Is String 5ms
Event Format.Distinct Id At Root Not Properties 4ms
Event Format.Custom Properties Preserved 5ms
Event Format.Set Properties Preserved 4ms
Event Format.Set Once Properties Preserved 4ms
Event Format.Groups Properties Preserved 5ms
Event Format.Sdk Generates Uuid If Not Provided 4ms
Event Format.Event Has Required Root Fields Batch 6ms
Event Format.Event Uuid Is Valid Batch 7ms
Event Format.Event Timestamp Is Rfc3339 Batch 7ms
Event Format.Distinct Id Is String Batch 6ms
Event Format.Distinct Id At Root Not Properties Batch 17ms
Event Format.Custom Properties Preserved Batch 7ms
Event Format.Set Properties Preserved Batch 6ms
Event Format.Set Once Properties Preserved Batch 7ms
Event Format.Groups Properties Preserved Batch 17ms
Event Format.Sdk Generates Uuid If Not Provided Batch 6ms
Batch Behavior.Multiple Events In Single Batch 29ms
Batch Behavior.Batch Envelope Smoke 8ms
Batch Behavior.Flush With No Events Sends Nothing 3ms
Batch Behavior.Flush At Triggers Batch 1006ms
Batch Behavior.Created At Reflects Batch Creation Time 7ms
Deduplication.Generates Unique Uuids 13ms
Deduplication.Different Events Same Content Different Uuids 6ms
Deduplication.Preserves Uuid On Retry 5134ms
Deduplication.Preserves Timestamp On Retry 5132ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 5136ms
Deduplication.No Duplicate Events In Batch 31ms
Header Behavior On Retry.Attempt Header Starts At One 6ms
Header Behavior On Retry.Attempt Header Increments On Retry 10139ms
Header Behavior On Retry.Request Id Preserved On Retry 5135ms
Header Behavior On Retry.Different Requests Have Different Request Ids 2014ms
Header Behavior On Retry.Request Timestamp Changes On Retry 5136ms
Response Format Validation.Success Response Has Uuid Keyed Results 6ms
Response Format Validation.Success Response Has Ok For Each Event 27ms
Response Format Validation.Success No Retry After When All Ok 26ms
Response Format Validation.Success Retry After Present When Retry Events 129ms
Response Format Validation.Success No Retry After When Drop Only 26ms
Response Format Validation.Response Echoes Request Id 5ms
Retry Behavior.Retries On 408 5134ms
Retry Behavior.Retries On 500 5134ms
Retry Behavior.Retries On 503 5136ms
Retry Behavior.Retries On 504 5133ms
Retry Behavior.Retryable Errors Have Retry After 2133ms
Retry Behavior.Respects Retry After On Retryable Error 8137ms
Retry Behavior.Does Not Retry On 400 2132ms
Retry Behavior.Does Not Retry On 401 2133ms
Retry Behavior.Does Not Retry On 402 2132ms
Retry Behavior.Does Not Retry On 413 2131ms
Retry Behavior.Does Not Retry On 415 2133ms
Retry Behavior.Non Retryable Errors Have No Retry After 2133ms
Retry Behavior.Implements Backoff 15144ms
Retry Behavior.Max Retries Respected 15144ms
Partial Batch Handling.Handles 200 Full Success 2009ms
Partial Batch Handling.Handles 200 With All Ok 3031ms
Partial Batch Handling.Does Not Retry Dropped Events 3030ms
Partial Batch Handling.Does Not Retry Limited Events 3029ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 5134ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 5136ms
Partial Batch Handling.Retries Only Retry Events From Partial 5133ms
Partial Batch Handling.Partial Retry Preserves Uuids 5136ms
Partial Batch Handling.Partial Retry Attempt Header Increments 5133ms
Partial Batch Handling.Partial Retry Request Id Preserved 5135ms
Partial Batch Handling.Respects Retry After On Partial 5136ms
Partial Batch Handling.Unknown Result Treated As Terminal 3029ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3033ms
Compression.Sends Gzip Content Encoding 17ms
Compression.No Content Encoding When Disabled 5ms
Compression.Compressed Body Is Decompressible 16ms
Error Handling.Does Not Retry On Unknown 4Xx 2128ms
Event Options.Cookieless Mode Override 6ms
Event Options.Disable Skew Correction Override 15ms
Event Options.Process Person Profile Override 5ms
Event Options.Product Tour Id Override 5ms
Event Options.Unset Options Omitted 4ms
Event Options.Options Override In Batch 7ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 5ms
Geoip And Historical Migration.Historical Migration Set In Body 4ms
Geoip And Historical Migration.Historical Migration Absent By Default 5ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 14ms
Request Payload.Flags Request Uses V2 Query Param 14ms
Request Payload.Flags Request Hits Flags Path Not Decide 15ms
Request Payload.Flags Request Omits Authorization Header 14ms
Request Payload.Token In Flags Body Matches Init 14ms
Request Payload.Groups Round Trip 15ms
Request Payload.Groups Default To Empty Object 14ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 14ms
Request Payload.Disable Geoip Omitted Defaults To False 15ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 14ms
Request Lifecycle.No Flags Request On Init Alone 1ms
Request Lifecycle.No Flags Request On Normal Capture 5ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 27ms
Request Lifecycle.Mock Response Value Is Returned To Caller 14ms
Retry Behavior.Retries Flags On 502 15ms
Retry Behavior.Retries Flags On 504 16ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 15ms

Generated-By: PostHog Code
Task-Id: 7ee84317-3a73-41e1-bc25-906b7c14be53
@dustinbyrne
dustinbyrne marked this pull request as ready for review August 10, 2026 16:32
@dustinbyrne
dustinbyrne requested a review from a team as a code owner August 10, 2026 16:32
@posthog

posthog Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

🦔 ReviewHog reviewed this pull request

Found 0 must fix, 0 should fix, 1 consider.

Published 1 finding (view the review).

@posthog

posthog Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor Author

ReviewHog Alpha 🦔 If you find any issues helpful - please reply "valid", "invalid", etc., for evaluation purposes 🙏

@posthog posthog Bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ReviewHog Report

Changes

Issues: 1 issue

Files (2)
  • .changeset/is-enabled-default-value.md
  • feature_flag_evaluations.go

Comment on lines +84 to 86
return resolveIsEnabledDefault(defaultValue)
}
return flag.Enabled

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Per-flag evaluation failures ignore the caller default

consider bug

Why we think it's a valid issue
  • Checked: recordFromFlagDetail (posthog.go:1343-1368), map population (posthog.go:1236), the IsEnabled miss path (feature_flag_evaluations.go:77-87), FlagDetail.Failed (flags.go:50-51), and the cross-SDK is-feature-enabled spec the PR cites.
  • Found: Premise is factually correct. A server-marked failed:true flag is forced to Enabled=false with Error set (posthog.go:1351-1355) but still inserted into the map, so flag, ok := e.flags[key] gives ok==true, the !ok branch (feature_flag_evaluations.go:83) is skipped, and flag.Enabled (false) is returned, ignoring the caller default. Reachable: Failed is a documented v4 API state with dedicated handling. Real inconsistency: a whole-request failure leaves the flag absent → default applies, but a per-flag transient failure returns false.
  • Found (severity counter-evidence): The fetched spec enumerates only three default-triggering cases — 'flags not loaded yet, a failed flags request, or no flag with that key' — and is silent on a returned-but-failed flag; its principle is 'a flag that has a value including false always wins over the default.' Treating a failed flag as a false value, with the error surfaced separately via the existing GetFeatureFlagErrors (feature_flag_evaluations.go:309-310), is a defensible, arguably spec-consistent reading, so the finding's 'violates intended behavior' claim is overstated.
  • Impact: Genuine reachable gap — IsEnabled(key, true) returns false during a transient per-flag failure, contrary to the caller's fallback intent — worth the author's conscious decision. But it is a narrow, transient partial-degradation in a spec-undefined area with failures already observable, so it is not release-blocking.
  • Priority: Lowered from must_fix to consider: real and directly related, but not a clear spec violation and defensible as-is, so down-rank rather than treat as a mandatory fix.
Issue description

The default is used only when the key is absent. However, recordFromFlagDetail stores failed evaluations as present records with Enabled=false and Error set, so IsEnabled returns false instead of the caller-supplied default. This violates the intended behavior when a flag has no usable value due to an evaluation failure.

Suggested fix

Treat records with flag.Error != nil as unresolved: after recording access, return resolveIsEnabledDefault(defaultValue) when !ok or flag.Error != nil. Add a test using a FlagDetail with Failed=true and an opposite caller default.

Prompt to fix with AI (copy-paste)
## Context
@feature_flag_evaluations.go#L84-86

<issue_description>
The default is used only when the key is absent. However, recordFromFlagDetail stores failed evaluations as present records with Enabled=false and Error set, so IsEnabled returns false instead of the caller-supplied default. This violates the intended behavior when a flag has no usable value due to an evaluation failure.
</issue_description>

<issue_validation>
- **Checked:** `recordFromFlagDetail` (posthog.go:1343-1368), map population (posthog.go:1236), the `IsEnabled` miss path (feature_flag_evaluations.go:77-87), `FlagDetail.Failed` (flags.go:50-51), and the cross-SDK `is-feature-enabled` spec the PR cites.
- **Found:** Premise is factually correct. A server-marked `failed:true` flag is forced to `Enabled=false` with `Error` set (posthog.go:1351-1355) but still inserted into the map, so `flag, ok := e.flags[key]` gives `ok==true`, the `!ok` branch (feature_flag_evaluations.go:83) is skipped, and `flag.Enabled` (false) is returned, ignoring the caller default. Reachable: `Failed` is a documented v4 API state with dedicated handling. Real inconsistency: a whole-request failure leaves the flag absent → default applies, but a per-flag transient failure returns false.
- **Found (severity counter-evidence):** The fetched spec enumerates only three default-triggering cases — 'flags not loaded yet, a failed flags request, or no flag with that key' — and is silent on a returned-but-failed flag; its principle is 'a flag that has a value including false always wins over the default.' Treating a failed flag as a false value, with the error surfaced separately via the existing `GetFeatureFlagErrors` (feature_flag_evaluations.go:309-310), is a defensible, arguably spec-consistent reading, so the finding's 'violates intended behavior' claim is overstated.
- **Impact:** Genuine reachable gap — `IsEnabled(key, true)` returns false during a transient per-flag failure, contrary to the caller's fallback intent — worth the author's conscious decision. But it is a narrow, transient partial-degradation in a spec-undefined area with failures already observable, so it is not release-blocking.
- **Priority:** Lowered from `must_fix` to `consider`: real and directly related, but not a clear spec violation and defensible as-is, so down-rank rather than treat as a mandatory fix.
</issue_validation>

## Task
Investigate the issue and solve it

<potential_solution>
Treat records with flag.Error != nil as unresolved: after recording access, return resolveIsEnabledDefault(defaultValue) when !ok or flag.Error != nil. Add a test using a FlagDetail with Failed=true and an opposite caller default.
</potential_solution>

Comment thread api/public-api.txt
func (e *FeatureFlagEvaluations) GetFlagPayload(key string) string

func (e *FeatureFlagEvaluations) IsEnabled(key string) bool
func (e *FeatureFlagEvaluations) IsEnabled(key string, defaultValue ...bool) bool

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i don't know about the variadic usage to keep this backwards compatible? PR description calls it idiomatic but... really?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant