From 5299581e7a9512d519ed35c3bef16125ea0f32d1 Mon Sep 17 00:00:00 2001 From: Adarsh Sahu Date: Sun, 29 Nov 2026 15:17:40 +0530 Subject: [PATCH] fix(replay): Advance converted session segment ID from sent segment --- .../android/replay/ReplayIntegration.kt | 17 +- .../replay/capture/BaseCaptureStrategy.kt | 2 +- .../replay/capture/BufferCaptureStrategy.kt | 25 ++- .../android/replay/capture/CaptureStrategy.kt | 4 +- .../replay/capture/SessionCaptureStrategy.kt | 4 +- .../android/replay/ReplayIntegrationTest.kt | 174 +++++++++++++++++- .../capture/BufferCaptureStrategyTest.kt | 54 +++++- .../capture/SessionCaptureStrategyTest.kt | 10 +- 8 files changed, 247 insertions(+), 43 deletions(-) diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt index 6bdca6f748f..86f4f3ba371 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt @@ -323,7 +323,7 @@ public class ReplayIntegration( scopes?.configureScope { it.replayId = current.replayId } if (isTerminating == true) { // A main-thread crash blocks the looper while flushing, so mark termination synchronously. - current.captureStrategy?.captureReplay(true) {} + current.captureStrategy?.captureReplay(true) { _, _ -> } } else { enqueueOnMainThread { captureCurrentReplay(current.generation, current.replayId) { strategy, onSegmentSent -> @@ -337,7 +337,7 @@ public class ReplayIntegration( private fun captureCurrentReplay( expectedGeneration: Long, expectedReplayId: SentryId, - capture: (CaptureStrategy, (Date) -> Unit) -> Unit, + capture: (CaptureStrategy, (Int, Date) -> Unit) -> Unit, ) { val current = state.get() val strategy = current.captureStrategy @@ -356,12 +356,13 @@ public class ReplayIntegration( // Convert before capturing, so the callback knows which strategy continues the replay. val activeStrategy = strategy.convert() - capture(strategy) { newTimestamp -> - // Runs on the replay executor, which the converted strategy shares. Advancing the segment - // here lands before any segment the converted strategy creates later (e.g. on stop), so the - // flushed segment id is not reused. A stale strategy (stopped or restarted replay) is not - // in the state anymore, so updating it has no effect. - activeStrategy.currentSegment++ + capture(strategy) { sentSegmentId, newTimestamp -> + // Runs on the replay executor, which the converted strategy shares. Setting the next segment + // from the sent segment id lands before any segment the converted strategy creates later + // (e.g. on stop), even if queued buffer tasks changed currentSegment after convert() ran. + // A stale strategy (stopped or restarted replay) is not in the state anymore, so updating it + // has no effect. + activeStrategy.currentSegment = sentSegmentId + 1 activeStrategy.segmentTimestamp = newTimestamp activeStrategy.isFlushed = true } diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt index 6b55cab0bb1..3ccba3f4453 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BaseCaptureStrategy.kt @@ -61,7 +61,7 @@ constructor( private val ticker: MonotonicTicker, protected val replayExecutor: ScheduledExecutorService, protected val persistingExecutor: ScheduledExecutorService, - private val replayCacheProvider: ((replayId: SentryId) -> ReplayCache)? = null, + protected val replayCacheProvider: ((replayId: SentryId) -> ReplayCache)? = null, ) : CaptureStrategy { internal companion object { private const val TAG = "CaptureStrategy" diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt index 988a62e6411..062feab08ee 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/BufferCaptureStrategy.kt @@ -91,7 +91,7 @@ constructor( super.stop() } - override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Date) -> Unit) { + override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Int, Date) -> Unit) { if (isTerminating) { this.isTerminating.set(true) // avoid capturing replay, because the video will be malformed @@ -115,19 +115,20 @@ constructor( } createCurrentSegment("capture_replay") { segment -> - bufferedSegments.capture() + val lastBufferedSegment = bufferedSegments.capture() if (segment is ReplaySegment.Created) { segment.capture(scopes) - // we only want to increment segment_id in the case of success, but currentSegment - // might be irrelevant since we changed strategies, so in the callback we increment - // it on the new strategy already - onSegmentSent(segment.replay.timestamp) + // pass the sent segment id so the converted strategy advances from what was actually sent + // rather than a snapshot taken before queued buffer tasks updated currentSegment + onSegmentSent(segment.replay.segmentId, segment.replay.timestamp) + } else if (lastBufferedSegment != null) { + onSegmentSent(lastBufferedSegment.replay.segmentId, lastBufferedSegment.replay.timestamp) } } } - override fun flush(onSegmentSent: (Date) -> Unit) = captureReplay(false, onSegmentSent) + override fun flush(onSegmentSent: (Int, Date) -> Unit) = captureReplay(false, onSegmentSent) override fun onScreenshotRecorded( bitmap: Bitmap?, @@ -184,10 +185,13 @@ constructor( ticker, replayExecutor, persistingExecutor, + replayCacheProvider, ) captureStrategy.recorderConfig = recorderConfig + // Start at 0; captureReplay's onSegmentSent sets the exact next ID from the last sent segment + // on replayExecutor before any session segment runs, and 0 is right if nothing ends up sent. captureStrategy.start( - segmentId = currentSegment, + segmentId = 0, replayId = currentReplayId, replayType = BUFFER, ) @@ -218,16 +222,19 @@ constructor( } } - private fun MutableList.capture() { + private fun MutableList.capture(): ReplaySegment.Created? { + var lastCaptured: ReplaySegment.Created? = null var bufferedSegment = removeFirstOrNull() while (bufferedSegment != null) { bufferedSegment.capture(scopes) + lastCaptured = bufferedSegment bufferedSegment = removeFirstOrNull() // a short delay between processing envelopes to avoid bursting our server and hitting // another rate limit https://develop.sentry.dev/sdk/features/#additional-capabilities // InterruptedException will be handled by the outer try-catch Thread.sleep(ENVELOPE_PROCESSING_DELAY) } + return lastCaptured } private fun MutableList.rotate(bufferLimit: Long) { diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/CaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/CaptureStrategy.kt index fc8b8d13065..9631fe79999 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/CaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/CaptureStrategy.kt @@ -43,10 +43,10 @@ internal interface CaptureStrategy { * Captures replay data for an event. Session mode may defer sending until its normal segment * boundary because the replay is already being uploaded continuously. */ - fun captureReplay(isTerminating: Boolean, onSegmentSent: (Date) -> Unit) + fun captureReplay(isTerminating: Boolean, onSegmentSent: (Int, Date) -> Unit) /** Explicitly sends the current replay data to Sentry in either session or buffer mode. */ - fun flush(onSegmentSent: (Date) -> Unit) + fun flush(onSegmentSent: (Int, Date) -> Unit) fun onScreenshotRecorded( bitmap: Bitmap? = null, diff --git a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt index 58bbf887084..cbe961b8ba8 100644 --- a/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt +++ b/sentry-android-replay/src/main/java/io/sentry/android/replay/capture/SessionCaptureStrategy.kt @@ -86,7 +86,7 @@ constructor( super.stop() } - override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Date) -> Unit) { + override fun captureReplay(isTerminating: Boolean, onSegmentSent: (Int, Date) -> Unit) { if (options.sessionReplay.isDebug) { options.logger.log( DEBUG, @@ -96,7 +96,7 @@ constructor( this.isTerminating.set(isTerminating) } - override fun flush(onSegmentSent: (Date) -> Unit) { + override fun flush(onSegmentSent: (Int, Date) -> Unit) { createCurrentSegment("flush") { segment -> if (segment is ReplaySegment.Created) { segment.capture(scopes) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt index d66584f1085..c0b1db66207 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt @@ -716,13 +716,13 @@ class ReplayIntegrationTest { fun `stale capture callback cannot mutate restarted replay`() { val oldReplayId = SentryId() val newReplayId = SentryId() - var onSegmentSent: ((Date) -> Unit)? = null + var onSegmentSent: ((Int, Date) -> Unit)? = null val oldStrategy = mock() whenever(oldStrategy.currentReplayId).thenReturn(oldReplayId) whenever(oldStrategy.convert()).thenReturn(oldStrategy) doAnswer { @Suppress("UNCHECKED_CAST") - onSegmentSent = it.arguments[1] as (Date) -> Unit + onSegmentSent = it.arguments[1] as (Int, Date) -> Unit } .whenever(oldStrategy) .captureReplay(any(), any()) @@ -746,7 +746,7 @@ class ReplayIntegrationTest { replay.stop() replay.start() shadowOf(Looper.getMainLooper()).idle() - onSegmentSent?.invoke(Date()) + onSegmentSent?.invoke(0, Date()) shadowOf(Looper.getMainLooper()).idle() assertThat(replay.replayId).isEqualTo(newReplayId) @@ -755,12 +755,12 @@ class ReplayIntegrationTest { @Test fun `flush followed by immediate stop advances the converted strategy segment`() { val replayId = SentryId() - var onSegmentSent: ((Date) -> Unit)? = null + var onSegmentSent: ((Int, Date) -> Unit)? = null val bufferStrategy = mock() whenever(bufferStrategy.currentReplayId).thenReturn(replayId) doAnswer { @Suppress("UNCHECKED_CAST") - onSegmentSent = it.arguments[0] as (Date) -> Unit + onSegmentSent = it.arguments[0] as (Int, Date) -> Unit } .whenever(bufferStrategy) .flush(any()) @@ -788,7 +788,7 @@ class ReplayIntegrationTest { // the flushed segment completes on the replay executor after stop ran on the main thread, // but before the stop segment of the converted strategy is created val timestamp = Date() - onSegmentSent!!.invoke(timestamp) + onSegmentSent!!.invoke(0, timestamp) verify(sessionStrategy).currentSegment = 1 verify(sessionStrategy).segmentTimestamp = timestamp @@ -1551,6 +1551,168 @@ class ReplayIntegrationTest { verify(fixture.scopes).captureReplay(any(), any()) } + private fun createQueuedBufferReplay( + nowProvider: () -> Long, + holdQueue: () -> Boolean, + queuedTasks: ArrayDeque, + capturedSegmentIds: MutableList, + ): ReplayIntegration { + whenever(fixture.replayCache.firstFrameTimestamp()).thenAnswer { + nowProvider() - VIDEO_DURATION + } + val replayExecutor = + mock { + whenever(mock.submit(any())).doAnswer { invocation -> + val task = invocation.arguments[0] as Runnable + if (holdQueue()) queuedTasks.addLast(task) else task.run() + null + } + } + val persistingExecutor = + mock { + whenever(mock.submit(any())).doAnswer { invocation -> + (invocation.arguments[0] as Runnable).run() + null + } + } + doAnswer { invocation -> + capturedSegmentIds += (invocation.arguments[0] as io.sentry.SentryReplayEvent).segmentId + SentryId() + } + .whenever(fixture.scopes) + .captureReplay(any(), any()) + + fixture.options.cacheDirPath = tmpDir.newFolder().absolutePath + return fixture.getSut( + context, + sessionSampleRate = 0.0, + onErrorSampleRate = 1.0, + dateProvider = ICurrentDateProvider { nowProvider() }, + recorderProvider = { mock() }, + replayCaptureStrategyProvider = { + BufferCaptureStrategy( + fixture.options, + fixture.scopes, + ICurrentDateProvider { nowProvider() }, + fixture.options.monotonicTicker, + replayExecutor, + persistingExecutor, + ) { _ -> + fixture.replayCache + } + }, + ) + } + + @Test + fun `queued configuration change before captureReplay does not repeat session segment id`() { + var now = 1_720_693_524_000L + var holdQueue = false + val queuedTasks = ArrayDeque() + val capturedSegmentIds = mutableListOf() + val replay = createQueuedBufferReplay({ now }, { holdQueue }, queuedTasks, capturedSegmentIds) + + replay.register(fixture.scopes, fixture.options) + replay.start() + val config = ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000) + replay.onConfigurationChanged(config) + + holdQueue = true + replay.onConfigurationChanged(config.copy(recordingWidth = 200, recordingHeight = 100)) + replay.captureReplay(false) + + holdQueue = false + while (queuedTasks.isNotEmpty()) { + queuedTasks.removeFirst().run() + } + + now += fixture.options.sessionReplay.sessionSegmentDuration + replay.onScreenshotRecorded(mock()) + + assertThat(capturedSegmentIds).containsExactly(0, 1, 2).inOrder() + } + + @Test + fun `queued frame rotating out a buffered segment before captureReplay does not skip a session segment id`() { + var now = 1_720_693_524_000L + var holdQueue = false + val queuedTasks = ArrayDeque() + val capturedSegmentIds = mutableListOf() + val replay = createQueuedBufferReplay({ now }, { holdQueue }, queuedTasks, capturedSegmentIds) + + replay.register(fixture.scopes, fixture.options) + replay.start() + val config = ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000) + replay.onConfigurationChanged(config) + + // Buffer two segments: segment 0 ends at now, segment 1 ends 20s later + replay.pause() + replay.resume() + now += 20_000L + replay.onConfigurationChanged(config.copy(recordingWidth = 200, recordingHeight = 100)) + + // Move past errorReplayDuration for segment 0 only, then queue add_frame ahead of captureReplay + now += 15_000L + holdQueue = true + replay.onScreenshotRecorded(mock()) + replay.captureReplay(false) + + holdQueue = false + while (queuedTasks.isNotEmpty()) { + queuedTasks.removeFirst().run() + } + + now += fixture.options.sessionReplay.sessionSegmentDuration + replay.onScreenshotRecorded(mock()) + + assertThat(capturedSegmentIds).containsExactly(0, 1, 2).inOrder() + } + + @Test + fun `queued pause before captureReplay advances session segment id even when current segment fails`() { + var now = 1_720_693_524_000L + var holdQueue = false + val queuedTasks = ArrayDeque() + val capturedSegmentIds = mutableListOf() + var createCalls = 0 + whenever( + fixture.replayCache.createVideoOf( + anyLong(), + anyLong(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + any(), + ), + ) + .thenAnswer { + // Call 1 (pause) and call 3 (session) succeed; call 2 (capture_replay current segment) + // fails + if (++createCalls == 2) null else GeneratedVideo(File("0.mp4"), 5, VIDEO_DURATION) + } + val replay = createQueuedBufferReplay({ now }, { holdQueue }, queuedTasks, capturedSegmentIds) + + replay.register(fixture.scopes, fixture.options) + replay.start() + replay.onConfigurationChanged(ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000)) + + holdQueue = true + replay.pause() + replay.captureReplay(false) + + holdQueue = false + while (queuedTasks.isNotEmpty()) { + queuedTasks.removeFirst().run() + } + + now += fixture.options.sessionReplay.sessionSegmentDuration + replay.onScreenshotRecorded(mock()) + + assertThat(capturedSegmentIds).containsExactly(0, 1).inOrder() + } + @Test fun `closed replay cannot be started`() { val replay = fixture.getSut(context) diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt index a926eb00358..203f0e2474e 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/BufferCaptureStrategyTest.kt @@ -270,7 +270,7 @@ class BufferCaptureStrategyTest { val strategy = fixture.getSut() strategy.start() - strategy.captureReplay(true) {} + strategy.captureReplay(true) { _, _ -> } val converted = strategy.convert() assertTrue(converted is BufferCaptureStrategy) @@ -283,7 +283,7 @@ class BufferCaptureStrategyTest { val strategy = fixture.getSut() strategy.start() - strategy.captureReplay(false) {} + strategy.captureReplay(false) { _, _ -> } val converted = strategy.convert() assertTrue(converted is BufferCaptureStrategy) @@ -385,7 +385,7 @@ class BufferCaptureStrategyTest { strategy.onConfigurationChanged(fixture.recorderConfig) strategy.pause() - strategy.captureReplay(false) {} + strategy.captureReplay(false) { _, _ -> } // neither the current nor the buffered segment should be sent while rate-limited verify(fixture.scopes, never()).captureReplay(any(), any()) @@ -400,7 +400,7 @@ class BufferCaptureStrategyTest { strategy.onConfigurationChanged(fixture.recorderConfig) strategy.pause() - strategy.captureReplay(false) {} + strategy.captureReplay(false) { _, _ -> } val discarded = fixture.discardedEvents() assertEquals(1, discarded.size) @@ -414,25 +414,25 @@ class BufferCaptureStrategyTest { strategy.start() strategy.onConfigurationChanged(fixture.recorderConfig) - strategy.captureReplay(false) {} + strategy.captureReplay(false) { _, _ -> } assertTrue(fixture.discardedEvents().none { it.category == DataCategory.Replay.category }) } @Test fun `captureReplay captures buffered segments`() { - var called = false + var sentSegmentId = -1 val strategy = fixture.getSut() strategy.start() strategy.onConfigurationChanged(fixture.recorderConfig) strategy.pause() - strategy.captureReplay(false) { called = true } + strategy.captureReplay(false) { segmentId, _ -> sentSegmentId = segmentId } // buffered + current = 2 verify(fixture.scopes, times(2)).captureReplay(any(), any()) - assertTrue(called) + assertEquals(1, sentSegmentId) } @Test @@ -444,13 +444,47 @@ class BufferCaptureStrategyTest { val oldTimestamp = strategy.segmentTimestamp whenever(fixture.replayCache.firstFrameTimestamp()).thenReturn(oldTimestamp!!.time) - strategy.captureReplay(false) { newTimestamp -> - assertEquals(oldTimestamp!!.time + VIDEO_DURATION, newTimestamp.time) + strategy.captureReplay(false) { segmentId, newTimestamp -> + assertEquals(0, segmentId) + assertEquals(oldTimestamp.time + VIDEO_DURATION, newTimestamp.time) } verify(fixture.scopes).captureReplay(any(), any()) } + @Test + fun `captureReplay calls onSegmentSent with last buffered segment id when current segment fails`() { + var sentSegmentId = -1 + var sentTimestamp: java.util.Date? = null + val strategy = fixture.getSut() + strategy.start() + strategy.onConfigurationChanged(fixture.recorderConfig) + + strategy.pause() + whenever( + fixture.replayCache.createVideoOf( + anyLong(), + anyLong(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + anyInt(), + any(), + ), + ) + .thenReturn(null) + + strategy.captureReplay(false) { segmentId, timestamp -> + sentSegmentId = segmentId + sentTimestamp = timestamp + } + + verify(fixture.scopes, times(1)).captureReplay(any(), any()) + assertEquals(0, sentSegmentId) + assertTrue(sentTimestamp != null) + } + @Test fun `replayId should be set and serialized first`() { val strategy = fixture.getSut() diff --git a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt index 68f7bb0cb0f..00f7d0cafa5 100644 --- a/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt +++ b/sentry-android-replay/src/test/java/io/sentry/android/replay/capture/SessionCaptureStrategyTest.kt @@ -308,7 +308,7 @@ class SessionCaptureStrategyTest { val strategy = fixture.getSut() strategy.start() - strategy.captureReplay(false) {} + strategy.captureReplay(false) { _, _ -> } verify(fixture.scopes, never()).captureReplay(any(), any()) } @@ -319,7 +319,7 @@ class SessionCaptureStrategyTest { strategy.start() strategy.onConfigurationChanged(fixture.recorderConfig) - strategy.flush {} + strategy.flush { _, _ -> } verify(fixture.scopes) .captureReplay(argThat { event -> event is SentryReplayEvent && event.segmentId == 0 }, any()) @@ -352,7 +352,7 @@ class SessionCaptureStrategyTest { strategy.onConfigurationChanged(fixture.recorderConfig) strategy.onScreenshotRecorded(mock()) {} - strategy.flush {} + strategy.flush { _, _ -> } tasks.forEach(Runnable::run) assertThat(segmentIds).containsExactly(0, 1).inOrder() @@ -377,7 +377,7 @@ class SessionCaptureStrategyTest { val segmentStart = strategy.segmentTimestamp!!.time val requestedAt = now - strategy.flush {} + strategy.flush { _, _ -> } now += fixture.options.sessionReplay.sessionSegmentDuration tasks.forEach(Runnable::run) @@ -465,7 +465,7 @@ class SessionCaptureStrategyTest { val strategy = fixture.getSut(dateProvider = { now }) strategy.start() - strategy.captureReplay(true) {} + strategy.captureReplay(true) { _, _ -> } strategy.onScreenshotRecorded(mock()) {} verify(fixture.scopes, never()).captureReplay(any(), any())