Skip to content

feat(replay): support session replay v2 trigger groups - #850

Open
marc-merino wants to merge 9 commits into
PostHog:mainfrom
marc-merino:knit/session-replay-v2-trigger-groups-on-mobile
Open

marc-merino wants to merge 9 commits into
PostHog:mainfrom
marc-merino:knit/session-replay-v2-trigger-groups-on-mobile

Conversation

@marc-merino

@marc-merino marc-merino commented Oct 7, 2026 •

Copy link
Copy Markdown

Knit Bundle

View bundle

This PR is part of Knit bundle session-replay-v2-trigger-groups-on-mobile.

See the other review objects in this bundle:

Bundle id: session-replay-v2-trigger-groups-on-mobile
Bundle title: Session replay v2 trigger groups on mobile

One of four PRs adding session replay v2 trigger groups to the mobile SDKs (Android, iOS, React Native, Flutter). You can see the unified description of the whole change here: Svartal bundle. The four PRs are linked above.

💡 Motivation and Context

Closes #712.

The server and posthog-js already support session replay v2 trigger groups (sessionRecording.version: 2 with a triggerGroups array). This SDK ignored them, so a project configured with trigger groups recorded on Android without the per-group conditions or sampling.

This PR evaluates the groups the same way posthog-js does (V2TriggerGroupStrategy):

  • Each group has event, screen and flag conditions, combined with any / all. Screen names take the place of URLs on mobile. A group with no conditions activates immediately.
  • Sampling is per group, using the same hash as posthog-js (sessionId + groupId), so web and mobile reach the same decision for a session.
  • Recording starts as soon as any activated group is sampled in. It only waits while no group records and some group is still pending.
  • The lowest minDurationMs among activated groups replaces the v1 minimum duration.
  • $sdk_debug_replay_remote_trigger_matching_config, $sdk_debug_replay_trigger_groups_count and $sdk_debug_replay_matched_recording_trigger_groups match posthog-js.
  • Nothing changes when version is missing or 1.
  • Under React Native, the JS layer evaluates event and screen conditions (that's where events are captured), so this SDK skips those conditions when running under React Native.

The new methods on PostHogRemoteConfig sit on an @PostHogInternal class, so no public API changes.

sdk-specs session-replay-ingestion-controls currently describes v2 as web-only. Happy to add the mobile behaviour there in a follow-up.

Companion PRs for iOS, React Native and Flutter are linked in the Knit block above. I'd especially like a sanity check on the union rule and the React Native split.

💚 How did you test it?

  • Unit tests for parsing, status combining, the sampling hash (vectors computed from the posthog-js helper), property filters, the union rule, minimum duration, session rotation and sample-rate changes. ./gradlew :posthog:test :posthog-android:testDebugUnitTest apiCheck spotlessCheck passes.
  • End to end with posthog-android-sample on an Android 15 emulator, pointed at a local mock PostHog server (POSTHOG_HOST) that served two groups: one on start_replay_trigger_2 with sampleRate: 0, one on start_replay_trigger_1 with sampleRate: 1. Tapping the sample's buttons:
    • before any trigger: no $snapshot uploads, $recording_status: disabled, matched_recording_trigger_groups: []
    • start_replay_trigger_2: still no snapshots; the group reports matched: true, sampled: false
    • start_replay_trigger_1: snapshots start uploading within a second, $recording_status: active, both groups reported with the right sampled value

📝 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)

  • Driven by me in Ivaldi, my agent workspace. Claude Code (Opus 5.5) planned, reviewed and integrated the work; OpenCode (GLM 5.3) wrote the first implementation from a contract taken from the posthog-js code.
  • The feature spans four repos, so I ran it as one Knit bundle: the Android, iOS, React Native and Flutter changes were built, tested and versioned together. All four diffs side by side on Svartal.

@github-actions

Copy link
Copy Markdown
Contributor

This PR hasn't seen activity in a week! Should it be merged, closed, or further worked on? If you want to keep it open, post a comment or remove the stale label – otherwise this will be closed in another week.

@github-actions github-actions Bot added the stale label Oct 15, 2026

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Automated advisory code review.

@marandaneto
marandaneto requested a review from a team October 21, 2026 12:42
@marandaneto marandaneto removed the stale label Oct 21, 2026
@marandaneto

Copy link
Copy Markdown
Member

@ioannisj worth a look since this is part of your Q. plan

@signed-commit-check

signed-commit-check Bot commented Oct 25, 2026 •

Copy link
Copy Markdown

Commit signatures resolved

GitHub now verifies every commit signature in this PR. No further action is needed.

Evaluate the v2 trigger groups from the sessionRecording remote config:
per-group event, screen and flag conditions combined with any/all,
per-group sampling with the same hash as posthog-js, and recording
when any activated group is sampled in. The lowest minDurationMs among
activated groups replaces the v1 minimum duration, and the
$sdk_debug_replay_* properties report the matched groups. Configs
without version 2 keep the v1 behaviour.

Assisted-by: OpenCode/glm-5.3
Assisted-by: Claude Code/claude-opus-5-5
Knit-Group: kg_20261025_398000
Knit-Bundle: session-replay-v2-trigger-groups-on-mobile
@marc-merino
marc-merino force-pushed the knit/session-replay-v2-trigger-groups-on-mobile branch from e3c8199 to 73d3269 Compare October 25, 2026 20:29

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

Both previously published concerns are addressed in the current source. Four issues remain: local sampling precedence, copied beforeSend properties, cached flag hydration, and object-array property matching. Focused checks reproduce them after merging the target base.

Fifty pure-core tests pass. Full Gradle/native validation remains unavailable in the isolated environment, and passing SDK CI is not established.

AI-assisted review.

@dustinbyrne
dustinbyrne requested a review from a team October 28, 2026 13:32
… regressions

Review feedback

posthog-ios (PostHog#921)
- The local sampleRate still caps recording under v2 trigger groups (ioannisj).
- Property filters print numbers the way JS String does: a value of 2^63 no
  longer traps, and "0.000001" matches 0.000001 (ioannisj; dustinbyrne F4).
- A v2 group with a flag condition holds the opening buffer until fresh
  /flags, like the v1 linkedFlag, then keeps or drops it (dustinbyrne F2).

posthog-android (PostHog#850)
- The local sampleRate caps v2 permission on every native path (F3).
- Replay matches the event as queued after the beforeSend hooks, and is not
  told about events a hook dropped (F4).
- Cached flags are loaded before cached flag groups are evaluated (F5).
- Object arrays match property filters like lists (F7).
- Property filters print numbers the way JS String does, as on iOS: the
  same "0.000001" mismatch as iOS F4 existed here too.

posthog-js (#5239), with the native side in PostHog#921 and PostHog#850
- Under React Native a JS stop holds native replay: config, flags and session
  callbacks no longer restart the recorder until JS starts it again
  (dustinbyrne PostHog#1).

Regressions fixed

- JS: a start native refused, followed by a failed stop, is retried on the
  next flags reload instead of being marked as recording.
- JS: reset() clears the in-memory activated groups, so a kept session id
  doesn't carry one user's activation to the next.
- iOS: an explicit stop before the first remote config drops the buffered
  opening window instead of migrating it.
- iOS: reset() keeps the trigger groups (project config, as on Android) and
  only clears the per-session activation, so a trigger event captured before
  the next /flags response still activates.
- iOS tests: the app group storage tests no longer crash the macOS run when
  the process can't create the group container (macOS 15+ unsigned runs);
  they run where the container is available and are skipped otherwise.

Every fix above has a test that fails without it. Code no test could tell
apart (a clear already done by another path) was removed instead.

Knit-Group: kg_20261103_7a33cd
Knit-Bundle: session-replay-v2-trigger-groups-on-mobile

@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 six previously reported concerns are addressed in this head. A remaining duration-release transition can strand opening replay data; consider correcting that path and adding the regression inline. Two narrower normalization edge cases are optional feedback. Conflict resolution and SDK/native CI are still needed on the resulting head.

AI-assisted review.

@dustinbyrne
dustinbyrne requested a review from a team November 5, 2026 22:27
Review feedback (dustinbyrne, 2026-11-05)

posthog-js (#5239)
- A fresh /config replay config is applied when no flags load follows
  (preloadFeatureFlags: false or disableRemoteFeatureFlags: true), so a
  group that now excludes the session stops recording without waiting for
  an unrelated flags update (PostHog#1).
- Session rotation re-evaluates trigger groups even when native replay
  never initialized: the session JS last decided for is tracked apart from
  the native session baseline, so a sampled-out first session no longer
  leaves later sampled-in sessions unrecorded (PostHog#2).

posthog-android (PostHog#850)
- An event that lowers the group minimum duration while the hold is active
  runs the buffer's gated migration, so the opening snapshots are released
  with later ones instead of staying stranded in the buffer (PostHog#1).
- Float properties compare as their serialized decimal (0.1f as 0.1), not
  the widened binary value (PostHog#2).
- Primitive arrays (IntArray, DoubleArray, ...) match property filters like
  lists instead of as a JVM identity string (PostHog#3).

posthog-ios (PostHog#921)
- The session-change subscription lives for the whole install, so a session
  that group sampling stopped no longer blocks the next sampled-in session
  from resuming (F1). An explicit stop still holds until the next explicit
  start, and a session change does not restart a recorder that a later
  /config turned the replay flag off for.

Every fix above has a test that fails without it.

Knit-Group: kg_20261110_7327d3
Knit-Bundle: session-replay-v2-trigger-groups-on-mobile

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Follow-up advisory review: one reproduced blocking replay-lifecycle regression.

@marandaneto
marandaneto requested a review from a team November 10, 2026 10:48
… lowered minimums

Review feedback (marandaneto, 2026-11-10)

posthog-js (#5239)
- A fresh /config with sessionRecording: false no longer starts native
  replay. Core drops the cached replay config for that disable, and the
  previous change read the missing config as unrestricted v1. The
  disable now also disarms the in-memory triggers and groups, so the next
  session rotation does not re-evaluate into the same start.
- Any evaluation (flags reload, app restart) treats a missing replay
  config plus a cached /config sessionRecording: false as a project
  disable instead of as unrestricted. This hole predates the previous
  round; same root cause.

posthog-android (PostHog#850)
- An event that lowers the group minimum and also resumes a stopped
  recorder releases the held window after the start, not before it, when
  the release was a no-op for the still-inactive recorder.

posthog-ios (PostHog#921)
- The held opening window is released when the minimum duration drops:
  an event activating a group with a lower minimum, a /flags reload
  activating a flag-conditioned one, and a /config reload. The release
  reruns the buffer's own gated check, so it still waits for the first
  config, needs active replay and a met minimum, and persists nothing for
  a session the fresh config excludes.

Every fix above has a test that fails without it. Full suites pass: RN
1303, Android 1101 + 765, iOS 1605.

Knit-Group: kg_20261110_573e1f
Knit-Bundle: session-replay-v2-trigger-groups-on-mobile

@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 stopped-recorder ordering case is fixed, and Float/primitive-array matching remains correct. One duration-buffer issue remains when an intervening pending flag state erases the earlier minimum: a zero-minimum trigger resumes recording without releasing opening data. Consider reconciling the retained window after an eligible resume. Conflict resolution and SDK/native CI are still needed on the resulting head.

AI-assisted review.

return synchronized(bufferingLock) {
val previous = cachedMinimumDurationMs ?: 0
cachedMinimumDurationMs = minimumDuration
!hasPassedMinimumDuration && previous > 0 && (minimumDuration ?: 0) < previous

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] — Pending eligibility erases the history needed to release opening data

Disposition: REQUIRED

Anchor: PostHogReplayIntegration.kt:3170, RIGHT. Related event path: lines 2723–2736.

Use ordinary non-RN Android replay, automatic replay enabled, first configuration resolved, and one unchanged session. Configure two rate-one groups:

  1. A flag-conditioned group with minimum 30000 ms.
  2. A purchase event group with minimum 0 ms.

While the flag is true, capture two opening replay records below 30 seconds. Reload flags so it becomes false, then call:

PostHog.capture("purchase")

The flag update leaves both groups pending. onRemoteConfig() stores a null effective minimum and stops recording without clearing the retained records.

Purchase then activates the zero-minimum group. However, updateCachedMinimumDuration() treats the previous null as zero and returns minimumLowered == false. The latest fix successfully resumes recording, but release is skipped because that Boolean is false. Subsequent zero-minimum writes bypass buffering and its migration callback.

Observed current-head component result: retained 2, persisted 1.
Expected: retained 0, persisted 3 after releasing the duration hold.

Component case Previous head Current head
Active → purchase minimum zero PASS, 0/3 PASS, 0/3
Explicit stop → purchase minimum zero FAIL, 2/1 PASS, 0/3
Flag pending → purchase minimum zero FAIL, 2/1 FAIL, 2/1
Flag pending → positive minimum 1 PASS, 0/3 PASS, 0/3
Local sampling refuses purchase Persisted 0 Persisted 0

Counts are retained/persisted records.

Evidence boundary: These runs use real core public capture, cached flag parsing, group evaluation and production disk queues, plus thirteen unchanged native method bodies. Android UI/main-loop/same-session hosting is explicitly substituted. They do not execute the actual Android integration class, HTTP /flags, frames, uploads or playback.

The real flags path notifies native config before the core flags-loaded callback. Both effects are exercised; native pending gates correctly refuse the intervening start. Same-session resume does not drain the old queue, and zero-minimum writes no longer invoke its buffered-write callback.

Impact: Retained opening replay data can be discarded on cleanup. Later event-resumed incremental data can lack its original anchor, contrary to the integration’s all-or-nothing migration rationale. Complete playback failure or a privacy bypass was not demonstrated.

This is not a regression introduced by the latest two-file commit: both reviewed heads fail. V2 exposes an existing queue-transition weakness through an ordinary within-configuration transition; merge base has no equivalent V2 path.

Recommendation: Consider reconciling outstanding duration-held data after a successful eligible start/resume, using current hold/buffer state rather than only the immediately preceding positive minimum. Preserve first-config withholding, eligibility/local sampling, active-recorder checks, session ownership and ordered migration.

Native regression needed: Extend the existing duration fixture with:

  • Minimum 30000 and two held records.
  • Pending eligibility and null minimum; config callback stops recording.
  • Purchase activation with minimum zero.
  • Assert recording resumes and the queue becomes retained 0/persisted 3.

The following focused native command was not executed as part of this review:

./gradlew --no-daemon -PenableDebugTests=true \
  :posthog-android:testDebugUnitTest \
  --tests "com.posthog.android.replay.PostHogReplayIntegrationTest"

Source trace and governing contract:

Compared revisions: current 8f59db712d9fa62a04014d89b5761aac58dedcc2, previous 8f2f81bc35c24f7df3451e07276a4e66057d55ac, merge base 9b1e3c9fa0cd9b58b1b635f7d9ed633cf149dfd1 (target base 129a83a1cc3227910e80fd55210c1bd29f104e97). The already-active and explicit-stop cases verified in the resolved discussions are repaired; this reproduction specifically adds an intervening pending state.

Suggested native regression — NOT EXECUTED: reuse the existing private fixture/await helpers in PostHogReplayIntegrationTest. This sketch isolates the minimum-history transition with mocked eligibility; the executed component probe additionally uses the real parser/evaluator.

@Test
@LooperMode(LooperMode.Mode.PAUSED)
fun `pending eligibility does not strand the retained duration window`() {
    val minimum = java.util.concurrent.atomic.AtomicLong(30_000)
    val pending = AtomicBoolean(false)
    val (fx, client) = durationHoldFixture(minimum)

    whenever(fx.remoteConfig.hasPendingSessionRecordingTriggerGroups(any()))
        .thenAnswer { pending.get() }
    whenever(fx.remoteConfig.isSessionRecordingPermittedByTriggerGroups(any()))
        .thenAnswer { !pending.get() }
    whenever(fx.remoteConfig.getSessionRecordingTriggerGroupsMinimumDurationMs(any()))
        .thenAnswer { if (pending.get()) null else minimum.get() }

    fx.sut.install(client)
    try {
        fx.sut.start(resumeCurrent = true)
        shadowOf(Looper.getMainLooper()).idle()
        fx.replayQueue.add(createTestEvent("opening_meta"))
        fx.replayQueue.add(createTestEvent("opening_full"))
        awaitReplayExecutors()
        assertEquals(2, fx.replayQueue.bufferDepth)
        assertEquals(0, fx.replayQueue.depth)

        pending.set(true)
        fx.sut.onRemoteConfig()
        shadowOf(Looper.getMainLooper()).idle()
        awaitReplayExecutors()
        assertFalse(fx.sut.isActive())
        assertEquals(2, fx.replayQueue.bufferDepth)

        minimum.set(0)
        pending.set(false)
        fx.sut.onEvent("purchase", emptyMap())
        shadowOf(Looper.getMainLooper()).idle()
        assertTrue(fx.sut.isActive())

        fx.replayQueue.add(createTestEvent("later_incremental"))
        awaitCondition {
            fx.replayQueue.bufferDepth == 0 && fx.replayQueue.depth == 3
        }
    } finally {
        fx.sut.uninstall()
        PostHogSessionManager.endSession()
    }
}

@dustinbyrne
dustinbyrne requested a review from a team November 12, 2026 21:08
marc-merino and others added 4 commits November 14, 2026 11:25
…sume

Review feedback (dustinbyrne, 2026-11-12)

posthog-android (PostHog#850)
- A held opening window is now released based on what is still buffered,
  not on whether the cached minimum just dropped. Pending trigger groups
  store no minimum, so a later zero-minimum activation compared against
  nothing and left the window stranded while new snapshots persisted
  directly.
- The release runs from startRecording, so an event, a config reload and
  an explicit start that resume the recorder all reconcile the buffer.
- The recheck is queued on the replay queue's executor behind any pending
  buffer clear, so a session rotation cannot release the previous
  session's window.

Tests: the reviewer's scenario, the config-reload and explicit-start
variants, a positive-minimum control and three recheckBuffer queue tests.
The three stranded-window tests fail without the fix. make test,
make checkFormat and make api pass.

Knit-Group: kg_20261114_28663c
Knit-Bundle: session-replay-v2-trigger-groups-on-mobile
Co-Authored-By: Ivaldi <ivaldi@users.noreply.github.com>
…sion-replay-v2-trigger-groups-on-mobile

Conflicts resolved in PostHogReplayIntegration.kt, PostHog.kt,
PostHogRemoteConfig.kt, PostHogSessionReplayHandlerFake.kt and
PostHogTest.kt, keeping both sides.

- capture() tells replay about the event main now queues after its single
  beforeSend pass. The branch's captureStatelessEvent helper is dropped
  because the second pass it served no longer exists, and the
  dropped-event test now drops in that one pass.
- The linked-flag decision uses the trigger-group decision config against
  main's successful flags only.
- The React Native early return and the stop-hold lift sit inside main's
  setupLock sections.

Co-Authored-By: Ivaldi <ivaldi@users.noreply.github.com>
optOut() now uninstalls the integrations and optIn() reinstalls them,
which dropped the hold a JS stop had placed on native replay. After
opt-in, a remote config or flags reload, a matching event or a session
change could restart replay the JS layer had stopped.

optIn() now repeats the stop on the reinstalled handler when the app's
last word was a stop, before the cached remote config is re-applied, as
posthog-ios does. A recording the app started is still restored, a stop
made while opted out is still ignored, and apps outside React Native are
unaffected.

Co-Authored-By: Ivaldi <ivaldi@users.noreply.github.com>
While no trigger group records and at least one can still activate,
$sdk_debug_replay_pending_trigger_conditions now lists trigger_groups,
as posthog-ios does. Under v2 the flat event and linked-flag triggers
read trigger_disabled, so nothing said why the session was not
recording yet.

Not reported once replay is uninstalled, like the trigger statuses.

Co-Authored-By: Ivaldi <ivaldi@users.noreply.github.com>

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.

Session replay: support v2 trigger groups (conditional recording)

3 participants