Skip to content

feat: add an onFeatureFlags listener you can unsubscribe - #670

Open
turnipdabeets wants to merge 2 commits into
chore/v6-flags-loaded-resultfrom
feat/v6-on-feature-flags-listener
Open

turnipdabeets wants to merge 2 commits into
chore/v6-flags-loaded-resultfrom
feat/v6-on-feature-flags-listener

Conversation

@turnipdabeets

@turnipdabeets turnipdabeets commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Brings Flutter to parity with posthog-ios 4.0 (PostHogSDK.shared.onFeatureFlags(_:)) and posthog-android 4.0 (PostHog.onFeatureFlags(callback), PostHog/posthog-android#878). Until now Flutter only had PostHogConfig.onFeatureFlags, which is fixed at setup() and can't be removed.

final subscription = Posthog().onFeatureFlags((loaded) {
  if (loaded.variants['new-checkout'] == 'test') { /* ... */ }
});
subscription.unsubscribe();

Same semantics as iOS and Android:

  • Runs after every load (startup, bootstrap, reloadFeatureFlags(), identify()/group()/reset()), with errorsLoading and the last known flags on failure.
  • If flags already loaded, a new listener gets the current values once, shortly after registering. Skipped if a newer load reaches it first.
  • Can register before setup() and survives close()/setup(). reset() and close() drop the cached load, so a new listener never gets the previous user's flags.

Implementation: a Dart-side registry (FeatureFlagsListeners, @internal). Each platform delivers to it next to the existing config callback: method channel (iOS/Android/macOS), desktop client (Windows/Linux), and posthog-js on web. No native changes, since native already forwards every load.

Web now registers its posthog-js onFeatureFlags listener even without config.onFeatureFlags, and unsubscribes it on close() and before re-registering on repeated setup(). Before, every setup() added another JS listener, so the config callback ran once per setup() call.

A throwing listener is logged and doesn't stop the others. Web skips registration when the page's posthog object has no onFeatureFlags (test stubs), instead of throwing during setup().

Stacked on #664 (needs PostHogFeatureFlagsLoaded).

💚 How did you test it?

  • test/feature_flags_listeners_test.dart: delivery until unsubscribe, one replay, replay skipped when a newer load wins, no replay after clear, unsubscribe during delivery, a throwing listener.
  • One wiring test per platform: method channel (posthog_flutter_io_test), desktop (posthog_flutter_desktop_test), web (posthog_flutter_web_setup_test, also covers repeated setup delivering once).
  • posthog_test: no replay of flags loaded before reset() / close().
  • Mutation-checked: removing the reset clear, the newer-load check, the desktop delivery, or the web re-setup unsubscribe each fails its test.
  • flutter analyze clean, flutter test and flutter test --platform chrome test/posthog_flutter_web_setup_test.dart pass.

📝 Checklist

  • All commits are signed (see Commit signing)
  • 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)

Claude Code wrote this while aligning the flags API across iOS 4, Android 4 and Flutter 6. Kept the listener in Dart instead of adding a native subscribe/unsubscribe channel method: native already pushes every load to Dart, so a Dart registry covers all five platforms with one implementation.

🤖 Generated with Claude Code

@turnipdabeets
turnipdabeets requested a review from a team as a code owner October 25, 2026 16:45
@turnipdabeets turnipdabeets self-assigned this Oct 25, 2026

@posthog posthog Bot 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.

PostHog Review · Standard · reviewed 34d79f4: 2 Should fix.

See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.

Comment thread posthog_flutter/lib/src/posthog.dart
Comment thread posthog_flutter/lib/src/feature_flags_listeners.dart Outdated
@github-actions

github-actions Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

posthog-flutter Compliance Report

Date: 2026-10-26 18:43:53 UTC
Duration: 96887ms

✅ All Tests Passed!

45/45 tests passed


Capture Tests

✅ 29/29 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields ✅ 145ms
Format Validation.Event Has Uuid ✅ 122ms
Format Validation.Event Has Lib Properties ✅ 117ms
Format Validation.Distinct Id Is String ✅ 116ms
Format Validation.Token Is Present ✅ 117ms
Format Validation.Custom Properties Preserved ✅ 118ms
Format Validation.Event Has Timestamp ✅ 119ms
Retry Behavior.Retries On 503 ✅ 5333ms
Retry Behavior.Does Not Retry On 400 ✅ 2119ms
Retry Behavior.Does Not Retry On 401 ✅ 2119ms
Retry Behavior.Respects Retry After Header ✅ 8126ms
Retry Behavior.Implements Backoff ✅ 15448ms
Retry Behavior.Retries On 500 ✅ 5226ms
Retry Behavior.Retries On 502 ✅ 5227ms
Retry Behavior.Retries On 504 ✅ 5228ms
Retry Behavior.Max Retries Respected ✅ 15442ms
Deduplication.Generates Unique Uuids ✅ 126ms
Deduplication.Preserves Uuid On Retry ✅ 5225ms
Deduplication.Preserves Uuid And Timestamp On Retry ✅ 10340ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 5234ms
Deduplication.No Duplicate Events In Batch ✅ 125ms
Deduplication.Different Events Have Different Uuids ✅ 118ms
Compression.Sends Gzip When Enabled ✅ 117ms
Batch Format.Uses Proper Batch Structure ✅ 115ms
Batch Format.Flush With No Events Sends Nothing ✅ 109ms
Batch Format.Multiple Events Batched Together ✅ 125ms
Error Handling.Does Not Retry On 403 ✅ 2117ms
Error Handling.Does Not Retry On 413 ✅ 2118ms
Error Handling.Retries On 408 ✅ 5226ms

Feature_Flags Tests

✅ 16/16 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 14ms
Request Payload.Flags Request Uses V2 Query Param ✅ 11ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 10ms
Request Payload.Flags Request Omits Authorization Header ✅ 9ms
Request Payload.Token In Flags Body Matches Init ✅ 10ms
Request Payload.Groups Round Trip ✅ 10ms
Request Payload.Groups Default To Empty Object ✅ 10ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It ✅ 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 10ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 10ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 10ms
Request Lifecycle.No Flags Request On Init Alone ✅ 4ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 114ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 18ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 10ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 116ms

@turnipdabeets
turnipdabeets force-pushed the feat/v6-on-feature-flags-listener branch from 5a85f1b to 2f7955e Compare October 26, 2026 16:28
@turnipdabeets
turnipdabeets force-pushed the chore/v6-flags-loaded-result branch from de3a190 to 0a7ab2a Compare October 26, 2026 18:38
@turnipdabeets
turnipdabeets force-pushed the feat/v6-on-feature-flags-listener branch from 2f7955e to a194366 Compare October 26, 2026 18:39

@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.

The subscription API and ordinary delivery/replay paths look sound. Two dispatch-boundary cases remain: a config callback can restore an invalidated snapshot after reset/close, and a synchronous config-callback exception prevents runtime subscribers from receiving the load. Both reproduce through the public Dart API and IO channel harness.

AI-assisted review.

?.call(featureFlagsLoadedFromMap(call.arguments));
final loaded = featureFlagsLoadedFromMap(call.arguments);
_onFeatureFlagsCallback?.call(loaded);
FeatureFlagsListeners.instance.deliver(loaded);

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.

[P1] Preserve reset/close invalidation across the config callback

When a config callback starts reset() or close(), a subsequent runtime subscription can receive the invalidated load after that transition has completed. Expected: no replay until replacement flags arrive. Observed: replay of {'old-user-only': true}.

A supported caller can trigger this without private-state mutation:

Future<void>? transition;
var started = false;

await Posthog().setup(
  PostHogConfig('test-token')
    ..onFeatureFlags = (_) {
      if (!started) {
        started = true;
        transition = Posthog().reset(); // Also reproduces with close().
      }
    },
);

// After the callback has run:
await transition!;
final subscription = Posthog().onFeatureFlags(updateUi);

The sequence is:

  1. A load arrives for the current user.
  2. The config callback starts reset/close.
  3. The public method synchronously clears the replay cache.
  4. The callback returns.
  5. The newly added deliver(loaded) writes that invalidated load back into _last.
  6. A late subscription replays it.

The cause is the changed dispatch ordering:

_onFeatureFlagsCallback?.call(loaded);
FeatureFlagsListeners.instance.deliver(loaded);

Equivalent ordering exists in desktop (posthog_flutter_desktop.dart:182–183) and web (posthog_flutter_web.dart:144–145).

This contradicts the new registry's explicit purpose—preventing previous-user replay after reset/close—and the reset/cache invalidation contracts in sdk-specs at b865140e489c191e96e402d12b557d6a586afd0e (openspec/specs/reset/spec.md and openspec/specs/feature-flag-cache/spec.md). It also differs from iOS's invalidation-aware listener handling in PostHogSDK.swift:2395–2426 at f16284d53bb43c2277c1f861a14bb3536d8087cf.

Executed regression: I ran a public-entry IO harness that injects an ordinary onFeatureFlagsCallback message containing {'variants': {'old-user-only': true}, 'errorsLoading': false}, initiates reset/close from the config callback, awaits completion, subscribes, drains microtasks, and asserts an empty result. Both assertions fail on this head with the old-user snapshot. The ordinary delivery/replay control passes.

flutter test --no-pub test/review_callback_boundary_test.dart -r expanded

The local regression file was run in isolated copies using Flutter 3.35.4 / Dart 3.9.2, with identical validation-only removal of workspace resolution and the dev-only dart_apitool dependency. Shipping implementation sources were unchanged. Base 0a7ab2a01000dd97bb0fbb68310592edbf3c3f38 has neither this runtime API nor its replay cache; its controls confirm lifecycle completion, not a passing equivalent replay assertion. Source causality establishes that this stale replay state is introduced here.

The trigger is unusual reentrant application code; no deployed-consumer frequency was established. Impact is stale flag-driven UI following logout or teardown until another load—not demonstrated authorization bypass or backend disclosure. Ordinary reset/close calls between deliveries are not the failing case.

Consider preserving invalidation across this callback boundary, so a reset/close prevents this load from being cached or subsequently dispatched. Applying that consistently to IO, desktop, and web, with both regression cases, would cover the affected seams. No fix was applied or tested.

_onFeatureFlagsCallback
?.call(featureFlagsLoadedFromMap(call.arguments));
final loaded = featureFlagsLoadedFromMap(call.arguments);
_onFeatureFlagsCallback?.call(loaded);

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.

[P1] Isolate config-callback exceptions from runtime subscriptions

If the setup-owned config callback throws synchronously, every runtime subscriber misses that load. Expected: independent subscribers still receive it. Observed: the runtime subscriber receives nothing.

Minimal caller:

await Posthog().setup(
  PostHogConfig('test-token')
    ..onFeatureFlags =
        (_) => throw StateError('application callback'),
);

final subscription = Posthog().onFeatureFlags(updateUi);

The config callback runs outside an exception boundary immediately before FeatureFlagsListeners.instance.deliver(loaded). Its exception prevents delivery from starting, so the registry's per-listener _notify protection cannot help. Equivalent ordering exists in desktop (posthog_flutter_desktop.dart:182–183) and web (posthog_flutter_web.dart:144–145).

The original config-callback exception behavior is pre-existing: the base control confirms the method channel returns an error envelope. The new impact is that this failure now suppresses an independently registered notification channel. A persistently failing handler can starve it on every refresh.

This conflicts with the target's deliberate per-listener isolation and existing desktop-emitter convention. Independent browser implementation/tests also isolate throwing handlers so later callbacks run (packages/browser-common/src/feature-flags.ts:1875–1898; tests/feature-flags-behavior.spec.ts:1479–1500, at 7ef9141d74cf01f25f96ec82f5b46ad95517d657). The sdk-specs on-feature-flags contract at b865140e489c191e96e402d12b557d6a586afd0e permits SDK-specific exception handling rather than mandating isolation universally.

Executed regression: I ran an IO harness that sets the throwing config callback, subscribes through public Posthog().onFeatureFlags, and injects an ordinary native load containing {'variants': {'old-user-only': true}, 'errorsLoading': false}. Head fails:

Expected: [{'old-user-only': true}]
Actual:   []
flutter test --no-pub test/review_callback_boundary_test.dart -r expanded

The ordinary callback control passes. Base 0a7ab2a01000dd97bb0fbb68310592edbf3c3f38 explicitly detects the absent runtime API and confirms the pre-existing error envelope. Later replay/subsequent-load assertions follow the first failing assertion and were not reached. The local regression file was run in isolated copies using Flutter 3.35.4 / Dart 3.9.2, with identical validation-only removal of workspace resolution and the dev-only dart_apitool dependency. Shipping implementation sources were unchanged.

Consider catching/logging the config callback independently of runtime delivery on all three platforms. Coordinating with the invalidation case above matters: unconditional delivery in finally would still restore an invalidated snapshot. This finding concerns synchronous exceptions, not later errors from async callback work. No fix was applied or tested.

@dustinbyrne
dustinbyrne requested a review from a team October 26, 2026 20:22

This branch has not been deployed

No deployments
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.

2 participants