Skip to content

Commit b9aa06f

Browse files
runningcodeclaude
andcommitted
fix(replay): Drop the buffer at too-long jumps and re-read raced segment requests
Buffer mode now drops what it recorded before a forward wall-clock jump longer than sessionDuration: the pre-jump frames, touch events and already buffered segments. It keeps recording on the new timeline, so an error soon after no longer sends one replay spanning hours or years. Session mode already stops at the same jump. Segment requests (pause, flush, stop, configuration change, error flush) read their times when made, so a busy executor doesn't stretch the segment. If a frame moved the recording onto a new timeline in between, those times and the frames the task finds were on different timelines: a backward jump could produce a frozen segment minutes long, and a buffer flush right after a forward jump could stretch one frame over the whole jump. The strategies now track the timeline their queued work is on, and a request's task reads its times again on that timeline when it differs from the one the request read. Without a jump nothing is re-read, so every value stays what it was. resume() no longer re-anchors the clock. Otherwise every request until its queued task runs would look like it raced a jump. A jump while paused is followed by the first frame after resume, like any other. Refs GH-6522 Refs JAVA-829 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d93efe8 commit b9aa06f

7 files changed

Lines changed: 244 additions & 64 deletions

File tree

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

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,13 @@ constructor(
9191
*/
9292
private val timelineLock = AutoClosableReentrantLock()
9393

94+
/**
95+
* The timeline the work queued on [replayExecutor] is on: the frames it stored and the segment it
96+
* is building. Only [stampFrame] restarts the clock, and that frame's task moves this onto the
97+
* new timeline, so the two differ only while such a task is queued.
98+
*/
99+
@Volatile protected var executorTimeline: AnchoredClock = clock.timeline
100+
94101
private val gestureConverter = ReplayGestureConverter({ clock.nowMillis() }, ticker)
95102

96103
protected val isTerminating = AtomicBoolean(false)
@@ -172,8 +179,9 @@ constructor(
172179
}
173180

174181
override fun resume() {
175-
// a new segment starts here anyway, so a wall-clock jump while paused needs no segment closed
176-
val resumedAt = DateUtils.getDateTime(timelineLock.acquire().use { clock.restart() })
182+
// not re-anchored here: that would make every segment request until the task below runs look
183+
// like it raced a jump. The first frame after a jump while paused follows it like any other.
184+
val resumedAt = DateUtils.getDateTime(clock.nowMillis())
177185
// Keep the timeline update behind queued frames and pause/flush segment creation.
178186
replayExecutor.submit(ReplayRunnable("$TAG.resume") { segmentTimestamp = resumedAt })
179187
}
@@ -252,12 +260,10 @@ constructor(
252260
} else {
253261
val oldTimeline = clock.timeline
254262
val oldTimelineEnd = oldTimeline.nowMillis()
255-
val newTimelineStart = clock.restart()
263+
val newTimeline = clock.restart()
256264
val oldEvents = generateSequence { currentEvents.pollFirst() }.toCollection(ArrayDeque())
257-
StampedFrame(
258-
newTimelineStart,
259-
TimelineJump(oldTimeline, oldTimelineEnd, newTimelineStart, oldEvents),
260-
)
265+
val jump = TimelineJump(oldTimeline, oldTimelineEnd, newTimeline, oldEvents)
266+
StampedFrame(jump.newTimelineStart, jump)
261267
}
262268
}
263269

@@ -307,9 +313,30 @@ constructor(
307313
protected class TimelineJump(
308314
val oldTimeline: AnchoredClock,
309315
val oldTimelineEnd: Long,
310-
val newTimelineStart: Long,
316+
val newTimeline: AnchoredClock,
311317
val oldEvents: Deque<RRWebEvent>,
312-
)
318+
) {
319+
val newTimelineStart: Long = newTimeline.startTime().epochMillis
320+
}
321+
322+
/**
323+
* The times a segment request reads when it is made, so a busy executor doesn't stretch the
324+
* segment. If a frame moved the recording onto a new timeline in between, what the request read
325+
* and the frames its task finds are on different timelines, so the task reads again with [read]
326+
* on the timeline the queued work is on.
327+
*/
328+
protected inner class SegmentRequest<T : Any>(private val read: (AnchoredClock) -> T) {
329+
// null while the task of a frame that followed a jump is still queued: the clock is on the new
330+
// timeline already, the frames are not
331+
private val timeline = clock.timeline.takeIf { it === executorTimeline }
332+
private val requested = timeline?.let(read)
333+
334+
/** Called from the request's task: the times to use, and the timeline they are on. */
335+
fun resolve(): Pair<T, AnchoredClock> {
336+
val current = executorTimeline
337+
return (requested?.takeIf { timeline === current } ?: read(current)) to current
338+
}
339+
}
313340

314341
private inline fun <T> persistableAtomicNullable(
315342
initialValue: T? = null,

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

Lines changed: 41 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ constructor(
137137
replayExecutor.submit(
138138
ReplayRunnable("$TAG.add_frame") {
139139
// first, so the old timeline is encoded and rotated without this frame
140-
frame.jump?.let { bufferTimeline(it, currentConfig) }
140+
frame.jump?.let { followJump(it, currentConfig) }
141141
cache?.store(frame.timestamp)
142142

143143
screenAtStart = cache?.rotate(bufferLimit)
@@ -146,8 +146,26 @@ constructor(
146146
)
147147
}
148148

149+
/**
150+
* Moves the buffer onto the new timeline. What was recorded before the jump stays buffered, as a
151+
* segment of its own, unless the clock jumped forward by more than the session duration.
152+
*/
153+
private fun followJump(jump: TimelineJump, currentConfig: ScreenshotRecorderConfig?) {
154+
if (jump.newTimelineStart - jump.oldTimelineEnd > options.sessionReplay.sessionDuration) {
155+
// an error soon after would send one replay spanning the jump, hours or years long; session
156+
// mode stops at the same jump instead
157+
bufferedSegments.discardWhere { true }
158+
} else {
159+
bufferOldTimeline(jump, currentConfig)
160+
}
161+
// frames left from the old timeline would be encoded into the new one's segments
162+
cache?.rotate(until = jump.oldTimelineEnd)
163+
// last, so a segment request can't see the new timeline before the cache is on it
164+
executorTimeline = jump.newTimeline
165+
}
166+
149167
/** Buffers the frames up to where the old timeline ended as a segment of their own. */
150-
private fun bufferTimeline(jump: TimelineJump, currentConfig: ScreenshotRecorderConfig?) {
168+
private fun bufferOldTimeline(jump: TimelineJump, currentConfig: ScreenshotRecorderConfig?) {
151169
val firstFrameTimestamp = cache?.firstFrameTimestamp()
152170
if (!isTerminating.get() && currentConfig != null && firstFrameTimestamp != null) {
153171
val segment =
@@ -164,8 +182,6 @@ constructor(
164182
)
165183
buffer(segment, jump.oldTimeline)
166184
}
167-
// frames left from the old timeline would be encoded into the new one's segments
168-
cache?.rotate(until = jump.oldTimelineEnd)
169185
}
170186

171187
private fun buffer(segment: ReplaySegment, timeline: AnchoredClock) {
@@ -252,13 +268,16 @@ constructor(
252268
}
253269
}
254270

255-
private fun MutableList<BufferedSegment>.rotate() {
271+
private fun MutableList<BufferedSegment>.rotate() =
272+
// it can be that the buffered segment is half-way older than the buffer limit, but
273+
// we only drop it if its end timestamp is older
274+
discardWhere { it.endedMoreThan(options.sessionReplay.errorReplayDuration) }
275+
276+
private fun MutableList<BufferedSegment>.discardWhere(predicate: (BufferedSegment) -> Boolean) {
256277
// TODO: can be a single while-loop
257278
var removed = false
258279
removeAll {
259-
// it can be that the buffered segment is half-way older than the buffer limit, but
260-
// we only drop it if its end timestamp is older
261-
if (it.endedMoreThan(options.sessionReplay.errorReplayDuration)) {
280+
if (predicate(it)) {
262281
currentSegment--
263282
deleteFile(it.segment.replay.videoFile)
264283
removed = true
@@ -296,19 +315,13 @@ constructor(
296315
)
297316
return
298317
}
299-
val errorReplayDuration = options.sessionReplay.errorReplayDuration
300-
val timeline = clock.timeline
301-
val now = timeline.nowMillis()
302-
val currentSegmentTimestamp =
303-
cache?.firstFrameTimestamp()?.let {
304-
// in buffer mode we have to set the timestamp of the first frame as the actual start
305-
DateUtils.getDateTime(it)
306-
} ?: DateUtils.getDateTime(now - errorReplayDuration)
307-
val duration = now - currentSegmentTimestamp.time
318+
val request = SegmentRequest(::wholeBuffer)
308319
val replayId = currentReplayId
309320

310321
replayExecutor.submit(
311322
ReplayRunnable("$TAG.$taskName") {
323+
val (window, timeline) = request.resolve()
324+
val (currentSegmentTimestamp, duration) = window
312325
val segment =
313326
createSegmentInternal(
314327
duration,
@@ -324,4 +337,15 @@ constructor(
324337
},
325338
)
326339
}
340+
341+
/** The start and duration of a segment of the whole buffer, up to now on [timeline]. */
342+
private fun wholeBuffer(timeline: AnchoredClock): Pair<Date, Long> {
343+
val now = timeline.nowMillis()
344+
val start =
345+
cache?.firstFrameTimestamp()?.let {
346+
// in buffer mode we have to set the timestamp of the first frame as the actual start
347+
DateUtils.getDateTime(it)
348+
} ?: DateUtils.getDateTime(now - options.sessionReplay.errorReplayDuration)
349+
return start to now - start.time
350+
}
327351
}

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ internal class ReplayClock(
3737

3838
fun nowMillis(): Long = timeline.nowMillis()
3939

40-
/** Anchors a new timeline on the wall clock and returns its start. */
41-
fun restart(): Long {
40+
/** Anchors a new timeline on the wall clock and returns it. */
41+
fun restart(): AnchoredClock {
4242
val next = AnchoredClock.create(epochClock, ticker)
4343
timeline = next
44-
return next.startTime().epochMillis
44+
return next
4545
}
4646

4747
/**

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

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ constructor(
125125
replayExecutor.submit(
126126
ReplayRunnable("$TAG.add_frame") {
127127
// first, so the old timeline is encoded and rotated without this frame
128-
frame.jump?.let { closeTimeline(it, currentConfig) }
128+
frame.jump?.let { followJump(it, currentConfig) }
129129
cache?.store(frameTimestamp)
130130

131131
val currentSegmentTimestamp = segmentTimestamp
@@ -182,29 +182,32 @@ constructor(
182182
/**
183183
* Captures the segment up to where the old timeline ended, and starts the next on the new one.
184184
*/
185-
private fun closeTimeline(jump: TimelineJump, currentConfig: ScreenshotRecorderConfig?) {
186-
val currentSegmentTimestamp = segmentTimestamp ?: return
187-
if (!isTerminating.get() && currentConfig != null) {
188-
val segment =
189-
createSegmentInternal(
190-
jump.oldTimelineEnd - currentSegmentTimestamp.time,
191-
currentSegmentTimestamp,
192-
currentReplayId,
193-
currentSegment,
194-
currentConfig.recordingHeight,
195-
currentConfig.recordingWidth,
196-
currentConfig.frameRate,
197-
currentConfig.bitRate,
198-
events = jump.oldEvents,
199-
)
200-
if (segment is ReplaySegment.Created) {
201-
segment.capture(scopes)
202-
currentSegment++
185+
private fun followJump(jump: TimelineJump, currentConfig: ScreenshotRecorderConfig?) {
186+
val currentSegmentTimestamp = segmentTimestamp
187+
if (currentSegmentTimestamp != null) {
188+
if (!isTerminating.get() && currentConfig != null) {
189+
val segment =
190+
createSegmentInternal(
191+
jump.oldTimelineEnd - currentSegmentTimestamp.time,
192+
currentSegmentTimestamp,
193+
currentReplayId,
194+
currentSegment,
195+
currentConfig.recordingHeight,
196+
currentConfig.recordingWidth,
197+
currentConfig.frameRate,
198+
currentConfig.bitRate,
199+
events = jump.oldEvents,
200+
)
201+
if (segment is ReplaySegment.Created) {
202+
segment.capture(scopes)
203+
currentSegment++
204+
}
203205
}
206+
segmentTimestamp = DateUtils.getDateTime(jump.newTimelineStart)
204207
}
205208
// frames left from the old timeline would be encoded into the new one's segments
206209
cache?.rotate(until = jump.oldTimelineEnd)
207-
segmentTimestamp = DateUtils.getDateTime(jump.newTimelineStart)
210+
executorTimeline = jump.newTimeline
208211
}
209212

210213
override fun onConfigurationChanged(recorderConfig: ScreenshotRecorderConfig) {
@@ -234,13 +237,14 @@ constructor(
234237
return
235238
}
236239

237-
val requestedAt = clock.nowMillis()
240+
val request = SegmentRequest { it.nowMillis() }
238241
val replayId = currentReplayId
239242
replayExecutor.submit(
240243
ReplayRunnable("$TAG.$taskName") {
241244
// Keep the request time so executor delays do not extend the segment, but read the mutable
242245
// timeline here so a queued natural boundary cannot make it stale.
243246
val currentSegmentTimestamp = segmentTimestamp ?: return@ReplayRunnable
247+
val requestedAt = request.resolve().first
244248
val segment =
245249
createSegmentInternal(
246250
requestedAt - currentSegmentTimestamp.time,

0 commit comments

Comments
 (0)