Skip to content

feat: add public onFeatureFlags listener with flags, variants and error state - #897

Merged
turnipdabeets merged 5 commits into
mainfrom
feat/public-on-feature-flags
Oct 3, 2026
Merged

turnipdabeets merged 5 commits into
mainfrom
feat/public-on-feature-flags

Conversation

@turnipdabeets

@turnipdabeets turnipdabeets commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Closes #647.

Today the only signal on iOS is the PostHogSDK.didReceiveFeatureFlags notification. It carries no payload, so apps have to read each flag again. Web's onFeatureFlags passes the enabled flags, their variants and whether loading failed. This PR adds the same listener to iOS, following the on-feature-flags spec.

let subscription = PostHogSDK.shared.onFeatureFlags { loaded in
    loaded.flags          // [String]: enabled flag keys
    loaded.variants       // [String: Any]: enabled key -> true or variant string
    loaded.errorsLoading  // true if the latest attempt to load flags failed
}
subscription.unsubscribe()

The callback:

  • Runs on the main thread, after the getters already return the new values.
  • Fires after flags load from bootstrap values or the network, after reloadFeatureFlags(), and after identify(), group() or reset() reload flags.
  • Fires once with the current values if you register after flags have loaded.
  • Can be registered before setup().
  • Is also available from Objective-C as onFeatureFlags:.

Only enabled flags are included, as on Web. When a request fails, errorsLoading is true and the payload holds the last known (cached) flags.

Behaviour change for existing consumers

The bootstrap "flags loaded" notification used to fire while the remote config was created, part-way through setup(). It now fires at the end of setup(). Nothing changes when setup() runs on the main thread. When setup() runs off main, the notification used to be able to reach the main thread before anyone was listening, so session replay, surveys and the new listeners all missed it. They now receive it. didReceiveFeatureFlags is still posted exactly once.

Differences from the spec and Web

  • Quota limited: iOS notifies with the cached flags and errorsLoading: false. Web currently doesn't call listeners at all in that case, which posthog-js#5045 fixes to match this behaviour.
  • errorsLoading: reports the outcome of the latest load. The deferred bootstrap notification keeps it, so a startup failure still reads as an error after the bootstrap values arrive.

💚 How did you test it?

Unit tests: new tests in PostHogFeatureFlagsTest → "Test onFeatureFlags":

  • payload content
  • a listener registered after flags loaded
  • a listener registered while an update is already queued
  • unsubscribe
  • errorsLoading with the last known flags
  • bootstrap delivery when setup() runs off the main thread
  • exactly one bootstrap delivery when setup() and onFeatureFlags are called together on main
  • no replay of the previous user's flags after reset(), including a delivery that was already queued when reset() ran
  • a listener unsubscribed by another listener during the same delivery isn't called
  • a listener calling reset() or close() stops the rest of that delivery, and later updates still arrive
  • errorsLoading stays true when the bootstrap notification arrives after a failed load

Each regression test was checked to fail without its fix.

On device: a scripted run on an iPhone 14 Pro Max against a real project, in five scenarios. The online ones covered no bootstrap, and bootstrap with setup() on main and off main. The offline ones covered Airplane Mode with and without bootstrap. For every callback I checked that:

  • it ran on the main thread and its payload matched getFeatureFlag
  • bootstrap values arrived exactly once, before the network values
  • a late listener was called exactly once
  • identify() with person properties changed a targeted flag
  • unsubscribe stopped further calls
  • reset() never replayed the previous user's flags
  • offline loads reported errorsLoading: true with the cached flags

Other: an Objective-C caller compiles against the generated header. make build, make test and make lint all pass.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran pnpm changeset to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Tooling: written with Claude Code. Two pre-PR review cycles (review, triage, implement) used sub-agents.
    • Cycle 1 found a stale replay to late listeners and the lost bootstrap notification when setup() runs off main.
    • Cycle 2 found that the bootstrap fix delivered the values twice on the usual launch pattern.
    • All three are fixed and covered by tests.
  • Decisions:
    • The listeners live on PostHogSDK, not on the remote config, so they survive setup()/close().
    • The subscription is an object with unsubscribe() rather than a closure, so it reads well from Objective-C.
    • No PostHogConfig.onFeatureFlags field, because registering before setup() covers that case.
    • The type names PostHogFeatureFlagsLoaded and PostHogFeatureFlagsSubscription are open to suggestions.
  • Docs: docs(ios): document onFeatureFlags callback posthog.com#20698 (draft, to merge after this is released).

🤖 Generated with Claude Code

…or state

Adds `PostHogSDK.onFeatureFlags(_:)`, which calls back on the main thread
whenever feature flags load or change, passing the enabled flags, their
values and whether loading failed. A listener registered after flags have
loaded is called with the current values. The returned subscription's
`unsubscribe()` stops further calls. Listeners can be registered before
`setup()`.

The bootstrap flags-loaded notification now fires at the end of `setup()`
instead of while the remote config is created, so listeners and
integrations no longer miss it when `setup()` runs off the main thread.

Closes #647

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
@greptile-apps

greptile-apps Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Retrigger

[Medium risk] Adds public listener API for feature flag updates.

The PR is not ready to merge because listeners can receive previous-user flags after reset or callbacks after unsubscribing.

Reviews (1) · Last reviewed commit: "feat: add public onFeatureFlags listener..."

Comment thread PostHog/PostHogSDK.swift Resolved
Comment thread PostHog/PostHogSDK.swift Resolved
Comment thread PostHog/PostHogRemoteConfig.swift Resolved
@github-actions

github-actions Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

posthog-ios Compliance Report

Date: 2026-10-02 22:42:46 UTC
Duration: 220562ms

⚠️ Some Tests Failed

44/45 tests passed, 1 failed


Capture Tests

⚠️ 28/29 tests passed, 1 failed

View Details
Test Status Duration
Format Validation.Event Has Required Fields ✅ 2820ms
Format Validation.Event Has Uuid ✅ 2814ms
Format Validation.Event Has Lib Properties ✅ 2799ms
Format Validation.Distinct Id Is String ✅ 453ms
Format Validation.Token Is Present ✅ 2880ms
Format Validation.Custom Properties Preserved ✅ 2732ms
Format Validation.Event Has Timestamp ✅ 2697ms
Retry Behavior.Retries On 503 ✅ 11274ms
Retry Behavior.Does Not Retry On 400 ✅ 4799ms
Retry Behavior.Does Not Retry On 401 ✅ 4837ms
Retry Behavior.Respects Retry After Header ✅ 5396ms
Retry Behavior.Implements Backoff ✅ 15510ms
Retry Behavior.Retries On 500 ✅ 9277ms
Retry Behavior.Retries On 502 ✅ 9520ms
Retry Behavior.Retries On 504 ✅ 9390ms
Retry Behavior.Max Retries Respected ❌ 21277ms
Deduplication.Generates Unique Uuids ✅ 2876ms
Deduplication.Preserves Uuid On Retry ✅ 8840ms
Deduplication.Preserves Uuid And Timestamp On Retry ✅ 16214ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 7888ms
Deduplication.No Duplicate Events In Batch ✅ 2992ms
Deduplication.Different Events Have Different Uuids ✅ 2828ms
Compression.Sends Gzip When Enabled ✅ 2769ms
Batch Format.Uses Proper Batch Structure ✅ 2729ms
Batch Format.Flush With No Events Sends Nothing ✅ 211ms
Batch Format.Multiple Events Batched Together ✅ 2920ms
Error Handling.Does Not Retry On 403 ✅ 4746ms
Error Handling.Does Not Retry On 413 ✅ 4834ms
Error Handling.Retries On 408 ✅ 5414ms

Failures

retry_behavior.max_retries_respected

Expected 4 requests, got 6

Feature_Flags Tests

✅ 16/16 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 2888ms
Request Payload.Flags Request Uses V2 Query Param ✅ 2864ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 2899ms
Request Payload.Flags Request Omits Authorization Header ✅ 2865ms
Request Payload.Token In Flags Body Matches Init ✅ 2892ms
Request Payload.Groups Round Trip ✅ 2824ms
Request Payload.Groups Default To Empty Object ✅ 2773ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It ✅ 2807ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 2873ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 2860ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 2730ms
Request Lifecycle.No Flags Request On Init Alone ✅ 108ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 2997ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 5533ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 2853ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 3045ms

turnipdabeets and others added 2 commits October 2, 2026 12:00
…elivery

- Drop a flags notification whose values no longer match the cache, e.g.
  one queued before reset(), so listeners never get the previous user's
  flags and the replay cache can't hold them.
- Skip a listener that another listener unsubscribed during the same
  delivery.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

@dustinbyrne dustinbyrne left a comment

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.

Approved with the two inline follow-ups below. Source review included an independent validation pass; the proposed regression tests were not executed.

Human-driven, agent-assisted review.

Comment thread PostHog/PostHogRemoteConfig.swift Resolved
Comment thread PostHog/PostHogSDK.swift Resolved
turnipdabeets and others added 2 commits October 2, 2026 17:40
…om a listener

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
…ication follows a failure

errorsLoading now reports the outcome of the latest delivered load. The
deferred bootstrap notification leaves it unchanged, so a startup request
that fails before bootstrap readiness is delivered still reports
errorsLoading: true, including to late subscribers.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
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.

Add full onFeatureFlags callback with flags, variants, and error state

2 participants