Skip to content

Commit eb32cb5

Browse files
romtsnclaude
andauthored
fix(replay): Keep replays of this process in the startup cleanup (#6343)
* fix(replay): Keep replays of this process in the startup cleanup finalizePreviousReplay runs once on the shared executor and can run late, e.g. behind ANR processing. cleanupReplays then deleted every replay folder except the current replay id, which is empty after stop(), so it removed the folder of a replay that had just stopped, including segment videos the transport had not read yet. It could also read this process's replay id from the persisted scope after a flush and treat it as a previous replay to recover, which deletes the folder of the running replay. Track the replay ids started in this process, keep their folders in the cleanup and skip finalizing them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * changelog * fix(replay): Use CopyOnWriteArraySet for the replay ids of this process ConcurrentHashMap.newKeySet() requires API 24 and the min SDK is 21. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(replay): Share the replay ids of this process across SDK inits A second Sentry.init registers a new ReplayIntegration, whose startup cleanup would delete the folders of replays the first instance recorded, including videos still waiting for the transport. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 28c6417 commit eb32cb5

3 files changed

Lines changed: 109 additions & 7 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
### Fixes
66

77
- Session Replay: Fix a native crash (`SIGABRT` on the RenderThread) when stopping a replay that uses the canvas screenshot strategy ([#6342](https://github.com/getsentry/sentry-java/pull/6342))
8+
- Session Replay: Keep the segment videos of a replay that stopped before the startup cleanup of previous replays ran ([#6343](https://github.com/getsentry/sentry-java/pull/6343))
89
- Report the number of dropped spans in client reports when a batched span envelope item is discarded, instead of a quantity of 1 (e.g. for Flutter span streaming) ([#6265](https://github.com/getsentry/sentry-java/pull/6265))
910
- Session Replay: Keep the flushed video and do not reuse its segment id when `stop()` is called right after `flush()` in buffer mode ([#6340](https://github.com/getsentry/sentry-java/pull/6340))
1011
- Keep sending events from Android 7.1.0 and older devices after Sentry changes its TLS certificate authority ([#6227](https://github.com/getsentry/sentry-java/pull/6227))

‎sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import java.io.Closeable
5959
import java.io.File
6060
import java.util.Date
6161
import java.util.LinkedList
62+
import java.util.concurrent.CopyOnWriteArraySet
6263
import java.util.concurrent.CountDownLatch
6364
import java.util.concurrent.Executors
6465
import java.util.concurrent.ThreadFactory
@@ -85,6 +86,11 @@ public class ReplayIntegration(
8586
SentryIntegrationPackageStorage.getInstance()
8687
.addPackage("maven:io.sentry:sentry-android-replay", BuildConfig.VERSION_NAME)
8788
}
89+
90+
// Replays recorded by this process. Their folders hold segment videos the transport may still
91+
// read after the replay stopped, so the startup cleanup of previous replays must keep them.
92+
// Shared across instances, because a second SDK init registers a new ReplayIntegration.
93+
val replayIdsOfThisProcess = CopyOnWriteArraySet<String>()
8894
}
8995

9096
// needed for the Java's call site
@@ -247,6 +253,9 @@ public class ReplayIntegration(
247253
recorder?.start()
248254
strategy.start()
249255
val replayId: SentryId? = strategy.currentReplayId
256+
if (replayId != null && replayId != SentryId.EMPTY_ID) {
257+
replayIdsOfThisProcess += replayId.toString()
258+
}
250259
state.set(
251260
ReplayState(
252261
generation = current.generation + 1,
@@ -638,15 +647,13 @@ public class ReplayIntegration(
638647
}
639648

640649
private fun cleanupReplays(unfinishedReplayId: String = "") {
641-
// clean up old replays
650+
// clean up old replays, but keep the replays of this process and the previous process's
651+
// unfinished replay (its folder is cleaned up after its envelope is assembled)
652+
val keptReplayIds = replayIdsOfThisProcess + listOfNotNull(unfinishedReplayId.ifBlank { null })
642653
options.cacheDirPath?.let { cacheDir ->
643654
File(cacheDir).listFiles()?.forEach { file ->
644655
val name = file.name
645-
if (
646-
name.startsWith("replay_") &&
647-
!name.contains(replayId.toString()) &&
648-
!(unfinishedReplayId.isNotBlank() && name.contains(unfinishedReplayId))
649-
) {
656+
if (name.startsWith("replay_") && keptReplayIds.none { name.contains(it) }) {
650657
FileUtils.deleteRecursively(file)
651658
}
652659
}
@@ -663,7 +670,12 @@ public class ReplayIntegration(
663670
return@submitSafely
664671
}
665672
val previousReplayId = SentryId(previousReplayIdString)
666-
if (previousReplayId == SentryId.EMPTY_ID) {
673+
// when this task runs late, the persisted replay id can already be one this process recorded,
674+
// which is not a previous replay to recover
675+
if (
676+
previousReplayId == SentryId.EMPTY_ID ||
677+
previousReplayId.toString() in replayIdsOfThisProcess
678+
) {
667679
cleanupReplays()
668680
return@submitSafely
669681
}

‎sentry-android-replay/src/test/java/io/sentry/android/replay/ReplayIntegrationTest.kt‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1263,6 +1263,95 @@ class ReplayIntegrationTest {
12631263
assertFalse(evenOlderReplay.exists())
12641264
}
12651265

1266+
@Test
1267+
fun `delayed startup cleanup keeps replays recorded by this process`() {
1268+
val replayId = SentryId()
1269+
fixture.options.cacheDirPath = tmpDir.newFolder().absolutePath
1270+
val olderReplay =
1271+
File(fixture.options.cacheDirPath, "replay_${SentryId()}").also { it.mkdirs() }
1272+
// hold back the startup work, like a busy executor does
1273+
val deferredTasks = mutableListOf<Runnable>()
1274+
fixture.options.executorService = mock {
1275+
doAnswer { deferredTasks += it.arguments[0] as Runnable }
1276+
.whenever(mock)
1277+
.submit(any<Runnable>())
1278+
}
1279+
1280+
val captureStrategy = mock<CaptureStrategy> { on { currentReplayId }.thenReturn(replayId) }
1281+
val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy })
1282+
replay.register(fixture.scopes, fixture.options)
1283+
replay.startBuffering()
1284+
// a flushed segment video that is still waiting for the transport
1285+
val stoppedReplay =
1286+
File(fixture.options.cacheDirPath, "replay_$replayId").also {
1287+
it.mkdirs()
1288+
File(it, "0.mp4").writeBytes(byteArrayOf(1, 2, 3))
1289+
}
1290+
replay.stop()
1291+
1292+
deferredTasks.forEach { it.run() }
1293+
1294+
assertTrue(File(stoppedReplay, "0.mp4").exists())
1295+
assertFalse(olderReplay.exists())
1296+
}
1297+
1298+
@Test
1299+
fun `second SDK init keeps replays recorded by the first one`() {
1300+
val firstReplayId = SentryId()
1301+
fixture.options.cacheDirPath = tmpDir.newFolder().absolutePath
1302+
val firstStrategy = mock<CaptureStrategy> { on { currentReplayId }.thenReturn(firstReplayId) }
1303+
val first = fixture.getSut(context, replayCaptureStrategyProvider = { firstStrategy })
1304+
first.register(fixture.scopes, fixture.options)
1305+
first.startBuffering()
1306+
val firstReplay =
1307+
File(fixture.options.cacheDirPath, "replay_$firstReplayId").also {
1308+
it.mkdirs()
1309+
File(it, "0.mp4").writeBytes(byteArrayOf(1, 2, 3))
1310+
}
1311+
first.stop()
1312+
first.close()
1313+
1314+
// a new Sentry.init registers a new integration, which runs the startup cleanup again
1315+
val secondStrategy = mock<CaptureStrategy> { on { currentReplayId }.thenReturn(SentryId()) }
1316+
val second = fixture.getSut(context, replayCaptureStrategyProvider = { secondStrategy })
1317+
second.register(fixture.scopes, fixture.options)
1318+
1319+
assertTrue(File(firstReplay, "0.mp4").exists())
1320+
}
1321+
1322+
@Test
1323+
fun `delayed startup task does not finalize a replay recorded by this process`() {
1324+
val replayId = SentryId()
1325+
fixture.options.cacheDirPath = tmpDir.newFolder().absolutePath
1326+
fixture.options.addScopeObserver(PersistingScopeObserver(fixture.options))
1327+
val deferredTasks = mutableListOf<Runnable>()
1328+
fixture.options.executorService = mock {
1329+
doAnswer { deferredTasks += it.arguments[0] as Runnable }
1330+
.whenever(mock)
1331+
.submit(any<Runnable>())
1332+
}
1333+
1334+
val captureStrategy = mock<CaptureStrategy> { on { currentReplayId }.thenReturn(replayId) }
1335+
val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy })
1336+
replay.register(fixture.scopes, fixture.options)
1337+
replay.startBuffering()
1338+
val currentReplay =
1339+
File(fixture.options.cacheDirPath, "replay_$replayId").also {
1340+
it.mkdirs()
1341+
File(it, "0.mp4").writeBytes(byteArrayOf(1, 2, 3))
1342+
}
1343+
// the scope observer persisted this replay's id after a flush, before the startup task ran
1344+
File(fixture.options.cacheDirPath, PersistingScopeObserver.SCOPE_CACHE).also {
1345+
it.mkdirs()
1346+
File(it, PersistingScopeObserver.REPLAY_FILENAME).writeText("\"$replayId\"")
1347+
}
1348+
1349+
deferredTasks.forEach { it.run() }
1350+
1351+
assertTrue(File(currentReplay, "0.mp4").exists())
1352+
verify(fixture.scopes, never()).captureReplay(any(), any())
1353+
}
1354+
12661355
@Test
12671356
fun `onScreenshotRecorded supplies screen from scope to replay cache`() {
12681357
val captureStrategy =

0 commit comments

Comments
 (0)