Skip to content

fix(replay): send feature flag called for v2 trigger group flag legs - #1028

Open
ioannisj wants to merge 10 commits into
mainfrom
fix/replay-linked-flag-called
Open

ioannisj wants to merge 10 commits into
mainfrom
fix/replay-linked-flag-called

Conversation

@ioannisj

@ioannisj ioannisj commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Session replay v2 trigger groups gate recording on feature flags, but unlike the v1 linked flag they never sent $feature_flag_called for those flags. So a user whose SDK evaluated the group flag didn't count as exposed to an experiment on that flag. android-v4.1.0 (#1001) shipped that on purpose because the spec said so; the spec now says to report them, in PostHog/sdk-specs#286.

sdk-specs main still has the old SHALL NOT for flag legs until PostHog/sdk-specs#286 merges, so this PR should merge after it.

Related: PostHog/posthog-ios#1141 makes the same change on iOS.

Changes:

  • Each flag a v2 trigger group uses is reported once per flag (not once per group), through the same path as the v1 linked flag from fix(flags): report the linked flag exposure after the flags load #1013: the exposures are read under featureFlagsLock with the recording decision, and reported after the lock.
  • The flag leg exposures are built in isRecordingActive, so /config, the /flags re-arm, the quota path and the cache preload all report them. React Native stays excluded.
  • The report goes through sendFeatureFlagEvent and the existing per-value dedupe, so a key and value already reported since the last reset sends nothing.
  • Until /flags responds, the first report of a launch can carry a cached or bootstrapped value.
  • clear() bumps a generation counter and the report loop stops when it changes, so a reset() from beforeSend during the report doesn't send the other legs for the previous identity.
  • sendFeatureFlagCalled now returns early while opted out. Before, it marked the flag value as reported even though capture dropped the event, so the first read after optIn() sent nothing. This applied to app reads and the v1 linked flag too, and the v2 legs would have made it more common.

The preload report doesn't reach sendFeatureFlagCalled in a real setup, same as v1 today: preload runs in the PostHogRemoteConfig constructor, before PostHog sets remoteConfigHolder, so it returns early at the remoteConfig == null check.

Out of scope, existing behaviour:

  • The /config report still runs beforeSend inside remoteConfigLock. Worth a follow-up to move it out of the lock like the /flags path.
  • A /flags response that was in flight at reset() is still installed and reported for the new identity, on main too. That needs a request-time generation in executeFeatureFlags, so it gets its own PR.

💚 How did you test it?

  • New unit tests in PostHogRemoteConfigTest and PostHogTest: one event per flag leg, dedupe across groups, flags surviving the report, preload, quota, React Native exclusion, and the flag-called switch.
  • a reset during a v2 flag leg report stops the other legs of that pass sent 2 events before the generation check and 1 after.
  • The two new opted-out tests (a v2 leg loaded while opted out, and an app read while opted out) sent 0 events after optIn() before the fix and 1 after.
  • ./gradlew :posthog:build spotlessCheck :posthog-android:testWithoutCompose --continue passes.

📝 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

DRI: @ioannisj
Autonomy: Human-driven (agent-assisted)

@ioannisj ioannisj self-assigned this Dec 2, 2026
@posthog

posthog Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

PostHog Review · Deep · reviewed 9a7b0ff

Posted 2 findings: 2 Consider.

Step Status Result
Prepare the diff done 3 files, 1 chunk
Pick perspectives done 3 perspectives
Run review passes done 2 issues (+1 blind-spot)
Merge overlapping findings done 3 → 3
Validate findings done 2 kept, 1 dismissed
Publish done 2 posted (view review)

@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

posthog-android Compliance Report

Date: 2026-12-02T15:20:48.244666+00:00
Duration: 510681ms

✅ All Tests Passed!

243/243 tests passed


Capture_V1 Tests

✅ 111/111 tests passed

View Details
Test Status Duration
Redirects And Library Identity.Follows Same Origin 307 ✅ 2302ms
Redirects And Library Identity.Does Not Follow Cross Origin Redirect ✅ 4028ms
Redirects And Library Identity.Treats 302 As Terminal ✅ 4030ms
Redirects And Library Identity.Follows At Most Five Redirects ✅ 5026ms
Redirects And Library Identity.Sends Lib And Lib Version Per Event ✅ 26ms
Request Size.Batches Close Before Byte Target ✅ 5198ms
Endpoint And Method.Targets V1 Endpoint ✅ 25ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 21ms
Required Headers.Has Authorization Bearer Header ✅ 18ms
Required Headers.Has Content Type Json ✅ 17ms
Required Headers.Has Posthog Sdk Info Format ✅ 16ms
Required Headers.Has Posthog Attempt Header ✅ 15ms
Required Headers.Has Posthog Request Id ✅ 18ms
Required Headers.Has Posthog Request Timestamp ✅ 17ms
Required Headers.Has User Agent ✅ 16ms
Body Format.Body Has Created At And Batch ✅ 16ms
Body Format.No Api Key In Body ✅ 17ms
Body Format.No Sent At In Body ✅ 15ms
Event Format.Event Has Required Root Fields ✅ 14ms
Event Format.Event Uuid Is Valid ✅ 18ms
Event Format.Event Timestamp Is Rfc3339 ✅ 16ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 15ms
Event Format.Distinct Id Is String ✅ 14ms
Event Format.Distinct Id At Root Not Properties ✅ 15ms
Event Format.Custom Properties Preserved ✅ 15ms
Event Format.Set Properties Preserved ✅ 16ms
Event Format.Set Once Properties Preserved ✅ 14ms
Event Format.Groups Properties Preserved ✅ 24ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 15ms
Event Format.Event Has Required Root Fields Batch ✅ 25ms
Event Format.Event Uuid Is Valid Batch ✅ 22ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 17ms
Event Format.Distinct Id Is String Batch ✅ 18ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 18ms
Event Format.Custom Properties Preserved Batch ✅ 22ms
Event Format.Set Properties Preserved Batch ✅ 21ms
Event Format.Set Once Properties Preserved Batch ✅ 22ms
Event Format.Groups Properties Preserved Batch ✅ 24ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 20ms
Batch Behavior.Multiple Events In Single Batch ✅ 29ms
Batch Behavior.Batch Envelope Smoke ✅ 22ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 8ms
Batch Behavior.Flush At Triggers Batch ✅ 1014ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 17ms
Deduplication.Generates Unique Uuids ✅ 30ms
Deduplication.Different Events Same Content Different Uuids ✅ 17ms
Deduplication.Preserves Uuid On Retry ✅ 7013ms
Deduplication.Preserves Timestamp On Retry ✅ 7016ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 7017ms
Deduplication.No Duplicate Events In Batch ✅ 30ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 13ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 12022ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 7018ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 2031ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 7017ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 17ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 18ms
Response Format Validation.Success No Retry After When All Ok ✅ 16ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 2011ms
Response Format Validation.Success No Retry After When Drop Only ✅ 21ms
Response Format Validation.Response Echoes Request Id ✅ 14ms
Retry Behavior.Retries On 408 ✅ 7013ms
Retry Behavior.Retries On 500 ✅ 7018ms
Retry Behavior.Retries On 503 ✅ 7024ms
Retry Behavior.Retries On 504 ✅ 7017ms
Retry Behavior.Retries On 404 ✅ 7016ms
Retry Behavior.Retries On 429 ✅ 7018ms
Retry Behavior.Retries On 502 ✅ 6017ms
Retry Behavior.Retryable Errors Have Retry After ✅ 4015ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 10028ms
Retry Behavior.Does Not Retry On 400 ✅ 4020ms
Retry Behavior.Does Not Retry On 401 ✅ 4021ms
Retry Behavior.Does Not Retry On 402 ✅ 4019ms
Retry Behavior.Does Not Retry On 413 ✅ 4020ms
Retry Behavior.Does Not Retry On 415 ✅ 4018ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 4020ms
Retry Behavior.Implements Backoff ✅ 14029ms
Partial Batch Handling.Handles 200 Full Success ✅ 2019ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3025ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3024ms
Partial Batch Handling.Does Not Retry Warning Events ✅ 3024ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 7016ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 7017ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 7017ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 7017ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 7016ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 7017ms
Partial Batch Handling.Respects Retry After On Partial ✅ 7024ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3024ms
Partial Batch Handling.Mixed Ok Drop Warning No Retry ✅ 3029ms
Compression.Sends Gzip Content Encoding ✅ 16ms
Compression.No Content Encoding When Disabled ✅ 12ms
Compression.Compressed Body Is Decompressible ✅ 13ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 4015ms
Event Options.Cookieless Mode Override ✅ 16ms
Event Options.Disable Skew Correction Override ✅ 13ms
Event Options.Process Person Profile Override ✅ 16ms
Event Options.Product Tour Id Override ✅ 12ms
Event Options.Unset Options Omitted ✅ 12ms
Event Options.Options Override In Batch ✅ 17ms
Event Options.Unknown Option Passes Through ✅ 14ms
Event Options.Option Value Is Not Converted ✅ 13ms
Event Options.Lenient Bool Option Values Are Not Converted ✅ 12ms
Event Options.Option Wins Over Legacy Property ✅ 12ms
Event Options.Legacy Property Fills Unset Option ✅ 12ms
Event Options.Null Option Falls Back To Legacy Property ✅ 12ms
Property Layers.Caller Property Beats Registered Property ✅ 14ms
Property Layers.Before Send Runs Last ✅ 15ms
Fail Open.Empty Api Key Sends Nothing ✅ 3010ms
Fail Open.Personal Api Key Sends Nothing ✅ 3013ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 16ms

Capture_Ai_V1 Tests

✅ 115/115 tests passed

View Details
Test Status Duration
Redirects And Library Identity.Follows Same Origin 307 ✅ 2018ms
Redirects And Library Identity.Does Not Follow Cross Origin Redirect ✅ 4017ms
Redirects And Library Identity.Treats 302 As Terminal ✅ 4020ms
Redirects And Library Identity.Follows At Most Five Redirects ✅ 5020ms
Redirects And Library Identity.Sends Lib And Lib Version Per Event ✅ 17ms
Endpoint And Method.Targets V1 Endpoint ✅ 15ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 13ms
Endpoint And Method.Capture Does Not Reroute Ai Named Events ✅ 11ms
Endpoint And Method.Capture Ai Does Not Reroute Non Ai Events ✅ 13ms
Lane Isolation.Failing Ai Lane Does Not Delay Analytics ✅ 7022ms
Required Headers.Has Authorization Bearer Header ✅ 16ms
Required Headers.Has Content Type Json ✅ 11ms
Required Headers.Has Posthog Sdk Info Format ✅ 11ms
Required Headers.Has Posthog Attempt Header ✅ 11ms
Required Headers.Has Posthog Request Id ✅ 10ms
Required Headers.Has Posthog Request Timestamp ✅ 10ms
Required Headers.Has User Agent ✅ 12ms
Body Format.Body Has Created At And Batch ✅ 14ms
Body Format.No Api Key In Body ✅ 13ms
Body Format.No Sent At In Body ✅ 13ms
Event Format.Event Has Required Root Fields ✅ 12ms
Event Format.Event Uuid Is Valid ✅ 10ms
Event Format.Event Timestamp Is Rfc3339 ✅ 10ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 11ms
Event Format.Distinct Id Is String ✅ 10ms
Event Format.Distinct Id At Root Not Properties ✅ 10ms
Event Format.Custom Properties Preserved ✅ 13ms
Event Format.Set Properties Preserved ✅ 13ms
Event Format.Set Once Properties Preserved ✅ 11ms
Event Format.Groups Properties Preserved ✅ 12ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 10ms
Event Format.Event Has Required Root Fields Batch ✅ 19ms
Event Format.Event Uuid Is Valid Batch ✅ 14ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 19ms
Event Format.Distinct Id Is String Batch ✅ 13ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 12ms
Event Format.Custom Properties Preserved Batch ✅ 13ms
Event Format.Set Properties Preserved Batch ✅ 14ms
Event Format.Set Once Properties Preserved Batch ✅ 13ms
Event Format.Groups Properties Preserved Batch ✅ 14ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 13ms
Batch Behavior.Multiple Events In Single Batch ✅ 18ms
Batch Behavior.Batch Envelope Smoke ✅ 16ms
Batch Behavior.Flush At Triggers Batch ✅ 1013ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 15ms
Deduplication.Generates Unique Uuids ✅ 27ms
Deduplication.Different Events Same Content Different Uuids ✅ 13ms
Deduplication.Preserves Uuid On Retry ✅ 7013ms
Deduplication.Preserves Timestamp On Retry ✅ 7017ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 7016ms
Deduplication.No Duplicate Events In Batch ✅ 25ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 12ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 12022ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 7016ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 2029ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 7016ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 15ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 17ms
Response Format Validation.Success No Retry After When All Ok ✅ 14ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 2007ms
Response Format Validation.Success No Retry After When Drop Only ✅ 16ms
Response Format Validation.Response Echoes Request Id ✅ 14ms
Retry Behavior.Retries On 408 ✅ 7013ms
Retry Behavior.Retries On 500 ✅ 7016ms
Retry Behavior.Retries On 503 ✅ 7023ms
Retry Behavior.Retries On 504 ✅ 7016ms
Retry Behavior.Retries On 404 ✅ 7014ms
Retry Behavior.Retries On 429 ✅ 7012ms
Retry Behavior.Retries On 502 ✅ 6015ms
Retry Behavior.Retryable Errors Have Retry After ✅ 4012ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 10024ms
Retry Behavior.Does Not Retry On 400 ✅ 4018ms
Retry Behavior.Does Not Retry On 401 ✅ 4017ms
Retry Behavior.Does Not Retry On 402 ✅ 4016ms
Retry Behavior.Does Not Retry On 413 ✅ 4020ms
Retry Behavior.Does Not Retry On 415 ✅ 4018ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 4018ms
Retry Behavior.Implements Backoff ✅ 14018ms
Partial Batch Handling.Handles 200 Full Success ✅ 2016ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3023ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3021ms
Partial Batch Handling.Does Not Retry Warning Events ✅ 3026ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 7015ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 7016ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 7014ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 7016ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 7018ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 7015ms
Partial Batch Handling.Respects Retry After On Partial ✅ 7022ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3021ms
Partial Batch Handling.Mixed Ok Drop Warning No Retry ✅ 3029ms
Compression.Sends Gzip Content Encoding ✅ 15ms
Compression.No Content Encoding When Disabled ✅ 11ms
Compression.Compressed Body Is Decompressible ✅ 10ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 4010ms
Event Options.Cookieless Mode Override ✅ 14ms
Event Options.Disable Skew Correction Override ✅ 11ms
Event Options.Process Person Profile Override ✅ 11ms
Event Options.Product Tour Id Override ✅ 10ms
Event Options.Unset Options Omitted ✅ 9ms
Event Options.Options Override In Batch ✅ 13ms
Event Options.Unknown Option Passes Through ✅ 10ms
Event Options.Option Value Is Not Converted ✅ 10ms
Event Options.Lenient Bool Option Values Are Not Converted ✅ 10ms
Event Options.Option Wins Over Legacy Property ✅ 10ms
Event Options.Legacy Property Fills Unset Option ✅ 9ms
Event Options.Null Option Falls Back To Legacy Property ✅ 11ms
Event Size.Event Over Ceiling Is Not Sent ✅ 3149ms
Event Size.Over Ceiling Drop Is Reported Or Logged Without Content ✅ 2050ms
Event Size.Batches Close Before Byte Target ✅ 6045ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 17ms
Property Layers.Caller Property Beats Registered Property ✅ 14ms
Property Layers.Before Send Runs Last ✅ 12ms
Fail Open.Empty Api Key Sends Nothing ✅ 1009ms
Fail Open.Personal Api Key Sends Nothing ✅ 1011ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 29ms
Request Payload.Flags Request Uses V2 Query Param ✅ 15ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 14ms
Request Payload.Flags Request Omits Authorization Header ✅ 15ms
Request Payload.Token In Flags Body Matches Init ✅ 14ms
Request Payload.Groups Round Trip ✅ 10ms
Request Payload.Groups Default To Empty Object ✅ 11ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 12ms
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 ✅ 11ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 12ms
Retry Behavior.Retries Flags On 502 ✅ 316ms
Retry Behavior.Retries Flags On 504 ✅ 318ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 16ms

@ioannisj
ioannisj marked this pull request as ready for review December 2, 2026 15:39
@ioannisj
ioannisj requested a review from a team as a code owner December 2, 2026 15:40
@veria-ai

veria-ai Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

PR overview

No security issues were found in this pull request.

Reviews

@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 v2 flag-leg report works as described for a single setup. The paths, the dedupe across groups, the React Native exclusion, the reset() stop, and the opt-out fix all check out. Locally, the focused PostHogRemoteConfigTest/PostHogTest/replay suites pass at b75c2e6, and the new tests fail on the base as expected.

There's one concern, inline: after close() and then setup() on the same instance, the start-up report marks the flag as called while the SDK is disabled. There are also two notes on the changeset.

Outside this PR:

  • sdk-specs#286 needs a rebase onto main before it merges. Main now has the rule that a boolean true satisfies a flag leg that configures a variant (session-replay-trigger-groups/spec.md "Flag leg" paragraph, and the scenario "A boolean true flag value satisfies a flag leg with a variant"). #286's rewrite of that paragraph comes from an older base and drops both. The Android evaluator implements that rule.
  • posthog-ios still marks a flag as called while opted out (reportFeatureFlagCalled, also in #1141). Worth mirroring this PR's opt-out guard there.
  • The posthog.com replay docs will be stale. session-replay/_snippets/flutter-installation.mdx says replay flag evaluation doesn't capture $feature_flag_called. The "Feature flag triggers" section of how-to-control-which-sessions-you-record.mdx could also say that a linked flag reports as called and counts toward experiment exposure.
  • The in-flight /flags at reset() issue from the resolved thread reproduces on main too. I'm leaving it to your planned follow-up.

AI-assisted review.

return
}
// capture() drops the event while opted out; marking it called would suppress the exposure after optIn
if (isOptedOut()) {

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.

Concern: After close() and then setup() on the same instance, the start-up flag-leg report marks the flag as called while the SDK is disabled. The app's next $feature_flag_called for that flag and value is then suppressed.

The PR body says the preload report never reaches sendFeatureFlagCalled, because remoteConfigHolder isn't set yet. That holds for the first setup but not for a re-setup:

  • remoteConfig is config?.remoteConfigHolder (PostHog.kt:211-212).
  • close() (:763-807) sets enabled = false and clears featureFlagsCalled, but keeps this.config and its holder.
  • On the next setup(), config.remoteConfigProvider(...) (:437) constructs PostHogRemoteConfig. Its init runs preloadSessionRecordingConfig() (PostHogRemoteConfig.kt:217; report at :1330) before this.config = config (:461) and enabled = true (:502).
  • So the report reaches sendFeatureFlagCalled through the closed setup's holder, passes the remoteConfig == null and isOptedOut() checks, and adds the key (:2837-2845). capture then drops the event in prepareEvent because !isEnabled() (:1367).
  • Nothing clears the key afterwards. The app's next getFeatureFlag with the same value sends nothing, and neither do the /config or /flags re-arm reports, until reset(), close(), or a value change.
PostHog.close()
PostHogAndroid.setup(context, config) // same shared instance; the cache holds a v2 flag-leg replay config and the flag value
PostHog.getFeatureFlag("session-replay-flag") // returns true, but no $feature_flag_called is captured

On the base, v2 flag legs aren't reported at start-up, so that read sends its event. The v1 linkedFlag already has this problem on the base; this PR extends it to every v2 flag-leg flag. Re-setup on the shared instance is a supported path: the static PostHog.setup/close delegate to it, and PostHogTest covers re-setup with both a fresh and a reused config. posthog-ios#1141 doesn't have this problem, because close() sets remoteConfig = nil.

Impact: apps that re-initialize the SDK lose $feature_flag_called for replay flag-leg flags, including the app's own reads, for the rest of that setup. Experiment exposure for those flags is undercounted.

Consider returning early while disabled as well as while opted out:

// capture() drops the event while disabled or opted out; marking it called would suppress the next exposure
if (!enabled || isOptedOut()) {
    return
}

getFeatureFlag and getFeatureFlagResult already return early while disabled, so this only changes remote-config reports made while disabled. It would also be worth updating the PR body's preload paragraph.

Regression test, added to PostHogTest. I ran it: at head b75c2e6 the v2 test fails with expected:<1> but was:<0>, and at base 9655a57 it passes. The v1 linkedFlag variant fails on both, and a single-setup control passes on both. I haven't run it with the fix applied.

private fun reSetupFlagCalledEvents(cachedRecording: Map<String, Any?>): List<PostHogEvent> {
    val http = mockHttp()
    val cachePreferences = PostHogMemoryPreferences()
    cachePreferences.setValue(SESSION_REPLAY, cachedRecording)
    cachePreferences.setValue(FEATURE_FLAGS, mapOf("session-replay-flag" to true))

    // first setup: preload runs before remoteConfigHolder exists, so it can't reach sendFeatureFlagCalled
    val sut = getSut(http.url("/").toString(), preloadFeatureFlags = false, cachePreferences = cachePreferences)
    sut.close()

    val flagCalled = CopyOnWriteArrayList<PostHogEvent>()
    val newConfig =
        PostHogConfig(PROJECT_TOKEN, http.url("/").toString()).apply {
            storagePrefix = tmpDir.newFolder().absolutePath
            preloadFeatureFlags = false
            this.cachePreferences = cachePreferences
            addBeforeSend { event ->
                if (event.event == "\$feature_flag_called") flagCalled.add(event)
                event
            }
        }
    sut.setup(newConfig)

    assertEquals(true, sut.getFeatureFlag("session-replay-flag"))
    sut.close()
    return flagCalled.filter { it.properties?.get("\$feature_flag") == "session-replay-flag" }
}

@Test
fun `during re-setup a v2 flag leg preload does not suppress the first app read exposure`() {
    val events =
        reSetupFlagCalledEvents(
            mapOf(
                "endpoint" to "/b/",
                "version" to 2,
                "triggerGroups" to
                    listOf(mapOf("id" to "g0", "sampleRate" to 1.0, "conditions" to mapOf("flag" to "session-replay-flag"))),
            ),
        )

    assertEquals(1, events.size)
}

@Test
fun `during re-setup a v1 linked flag preload does not suppress the first app read exposure`() {
    val events = reSetupFlagCalledEvents(mapOf("endpoint" to "/b/", "linkedFlag" to "session-replay-flag"))

    assertEquals(1, events.size)
}

"posthog-android": patch
---

Session replay v2 trigger groups now send `$feature_flag_called` for each flag a group uses, once per flag and not once per group, like the v1 linked flag. This reverses the behavior released in android-v4.1.0, which sent no event for v2 flag legs. A user whose SDK evaluates the group flag now counts as exposed to an experiment on that flag. Until `/flags` responds, the first report of a launch can carry a cached or bootstrapped flag value. The event follows `sendFeatureFlagEvent` and the existing per-value dedupe, so a flag key and value sends no event when it was already reported since the last reset, for example by an app flag read. React Native is unchanged.

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.

Suggestion: It would help readers to say who gets the new events. The report runs even when the app has session replay off (sessionReplay defaults to false, PostHogConfig.kt:157-162), as long as the project's v2 trigger groups use a flag that has a value, because the /config, /flags re-arm and quota paths don't check the local setting. Also, "android-v4.1.0" is the posthog-android version, but this entry also lands in posthog/CHANGELOG.md, where that change shipped as 7.1.0.

Consider adding something like: "This applies even when session replay is off in the app, and adds up to one event per flag key and value per launch. Reverses the behavior released in posthog 7.1.0 / posthog-android 4.1.0." posthog-ios#1141's changeset states the per-launch volume in the same way.

@@ -0,0 +1,6 @@
---
"posthog": patch

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.

Question: Should this be a minor for both packages? The SDK guidelines ("Keep changelogs and version bumps accurate") reserve patch releases for changes that don't add customer-facing behavior. This adds $feature_flag_called events that change experiment exposure counts, and the v1 linked-flag equivalent shipped as a minor in 3.36.0. If patch is meant to match posthog-ios#1141, that's fine too. This doesn't block the code change.

@dustinbyrne
dustinbyrne requested a review from a team December 2, 2026 16:04

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

Checked against sdk-specs#286: one report per distinct key through the normal flag-called path, no V1 linkedFlag under groups, a variant leg with true reports true, no report without a value, React Native excluded (JS owns it), and the reset() generation stop all hold. The focused PostHogRemoteConfigTest and PostHogTest pass locally at b75c2e6. Approving on the understanding that this waits for #286 to merge (after its rebase onto main's variant/boolean rule) and that Dustin's re-setup thread gets an answer; the !enabled guard he suggests looks like the right small fix.

}

@Test
fun `a reset during a v2 flag leg report stops the other legs of that pass`() {

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.

nit: this covers a reset() during the /flags report. The /config report goes through the same reportLinkedFlagExposures but runs inside remoteConfigLock. Worth a sibling case driven by loadRemoteConfig, so moving that report out of the lock later (your follow-up) keeps the stop?

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.

3 participants