Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
- Session Replay: Send Ktor client network request start and end times in milliseconds, so the requests line up with the replay ([#6619](https://github.com/getsentry/sentry-java/pull/6619))
- Nav3: Stop attributing errors and spans from an Activity or ViewPager2 page without a `SentryNavEffect` to the most recently visited Nav3 root ([#6483](https://github.com/getsentry/sentry-java/pull/6483))
- Android: Count deep sleep in breadcrumb, screenshot and view hierarchy debounce windows, so the first low-memory or battery breadcrumb after a long Doze is no longer dropped ([#6590](https://github.com/getsentry/sentry-java/pull/6590))
- Session Replay no longer drops or freezes video when the device clock changes mid-recording ([#6542](https://github.com/getsentry/sentry-java/pull/6542))
- The video since the last segment sent before the change (up to 5s) is dropped, and breadcrumbs and errors stay aligned with the video. When recording only for errors, what was buffered before the change is dropped, so the replay of a later error starts after it.
- A forward change longer than the session duration (1h) ends a full-session recording, as reaching that duration does.
- Android: Mark transactions and spans that finish after their deadline as `deadline_exceeded`, so `ui.load` transactions with TTID, TTFD or app start values that are hours long after a device sleep no longer report `ok` ([#6599](https://github.com/getsentry/sentry-java/pull/6599))
- Android: Register network callbacks on API 24โ€“25 when `AndroidConnectionStatusProvider` is created with a custom `Handler`, instead of failing because the `Handler` overload needs API 26 ([#6634](https://github.com/getsentry/sentry-java/pull/6634))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,12 @@ import io.sentry.android.replay.gestures.ReplayGestureConverter
import io.sentry.android.replay.util.ReplayRunnable
import io.sentry.protocol.SentryId
import io.sentry.rrweb.RRWebEvent
import io.sentry.time.AnchoredClock
import io.sentry.time.Deadline
import io.sentry.time.MonotonicTicker
import io.sentry.time.Timestamp
import io.sentry.transport.ICurrentDateProvider
import io.sentry.util.AutoClosableReentrantLock
import java.io.File
import java.util.Date
import java.util.Deque
Expand All @@ -56,20 +59,35 @@ internal abstract class BaseCaptureStrategy
constructor(
private val options: SentryOptions,
private val scopes: IScopes?,
// TODO [v9]: We should consider replacing this with AnchoredClock in V9.
// TODO [v9]: Remove ICurrentDateProvider and anchor on options.epochClock (JAVA-827).
dateProvider: ICurrentDateProvider,
private val ticker: MonotonicTicker,
protected val replayExecutor: ScheduledExecutorService,
protected val persistingExecutor: ScheduledExecutorService,
private val replayCacheProvider: ((replayId: SentryId) -> ReplayCache)? = null,
/** The timeline of the recording this strategy takes over, if it continues one. */
continuedTimeline: AnchoredClock? = null,
) : CaptureStrategy {
internal companion object {
private const val TAG = "CaptureStrategy"
// https://github.com/getsentry/sentry-javascript/blob/30eb68fff5077211c30c61ba74625e66ab514870/packages/replay-internal/src/coreHandlers/handleAfterSendEvent.ts#L41
private const val MAX_CONTEXT_VALUES = 100
}

private val gestureConverter = ReplayGestureConverter(dateProvider, ticker)
protected val clock =
ReplayClock(
{ Timestamp.ofEpochNanos(DateUtils.millisToNanos(dateProvider.currentTimeMillis)) },
ticker,
continuedTimeline,
)

/**
* Screenshots arrive on more than one thread, so checking for a jump and restarting the clock
* happen together, and two frames can't both follow one jump.
*/
private val timelineLock = AutoClosableReentrantLock()

private val gestureConverter = ReplayGestureConverter({ clock.nowMillis() }, ticker)

protected val isTerminating = AtomicBoolean(false)
protected var cache: ReplayCache? = null
Expand Down Expand Up @@ -132,7 +150,7 @@ constructor(
this.currentSegment = segmentId
this.replayType = replayType ?: (if (this is SessionCaptureStrategy) SESSION else BUFFER)

segmentTimestamp = DateUtils.getCurrentDateTime()
segmentTimestamp = DateUtils.getDateTime(clock.nowMillis())
replayDeadline = Deadline.after(ticker, options.sessionReplay.sessionDuration, MILLISECONDS)
// the same values MainEventProcessor applies to current-run segments
recordingMetadata =
Expand All @@ -150,7 +168,8 @@ constructor(
}

override fun resume() {
val resumedAt = DateUtils.getCurrentDateTime()
// only frames follow a jump, so the first frame after a jump while paused does
val resumedAt = DateUtils.getDateTime(clock.nowMillis())
// Keep the timeline update behind queued frames and pause/flush segment creation.
replayExecutor.submit(ReplayRunnable("$TAG.resume") { segmentTimestamp = resumedAt })
}
Expand Down Expand Up @@ -216,6 +235,31 @@ constructor(
this.recorderConfig = recorderConfig
}

/**
* Stamps a frame captured now. If the wall clock jumped since the previous frame, the recording
* first moves onto a new timeline anchored on it, unless the jump is forward by more than
* [maxForwardJumpMillis].
*/
protected fun stampFrame(maxForwardJumpMillis: Long = Long.MAX_VALUE): StampedFrame =
timelineLock.acquire().use {
val jumpMillis = clock.wallClockJumpMillis()
when {
jumpMillis == 0L -> StampedFrame(clock.nowMillis())
jumpMillis > maxForwardJumpMillis -> StampedFrame(clock.nowMillis(), jumpedTooFar = true)
else -> StampedFrame(clock.restart().startTime().epochMillis, jumped = true)
}
}

/**
* Called from the task of a frame that [StampedFrame.jumped], before the frame is stored. The
* frames and touch events recorded so far are on the old timeline and would land in the wrong
* place on the new one, so they are dropped, with the segment they were part of.
*/
protected fun dropOldTimeline() {
cache?.rotate(until = Long.MAX_VALUE)
currentEvents.clear()
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Touches after a jump cleared by delayed drop

Low Severity

dropOldTimeline clears the shared currentEvents inside the jump frame's executor task, which can run well after stampFrame restarts the clock. Touches recorded in that window are already stamped on the new timeline. They get cleared along with the old ones and silently disappear from the replay.

Additional Locations (1)
Fix in Cursorย Fix in Web

Reviewed by Cursor Bugbot for commit 1db10e9. Configure here.

override fun onTouchEvent(event: MotionEvent) {
recorderConfig?.let { config ->
val rrwebEvents = gestureConverter.convert(event, config)
Expand Down Expand Up @@ -245,6 +289,14 @@ constructor(
}
}

protected class StampedFrame(
val timestamp: Long,
/** The recording moved onto a new timeline at this frame. */
val jumped: Boolean = false,
/** The wall clock jumped forward too far to follow, so the frame stayed on the old timeline. */
val jumpedTooFar: Boolean = false,
)

private inline fun <T> persistableAtomicNullable(
initialValue: T? = null,
propertyName: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,18 @@ constructor(
) {
// have to do it before submitting, otherwise if the queue is busy, the timestamp won't be
// reflecting the exact time of when it was captured
val frameTimestamp = dateProvider.currentTimeMillis
val frame = stampFrame()
// a later frame may move the clock onto a new timeline before this task runs
val bufferLimit = frame.timestamp - options.sessionReplay.errorReplayDuration
replayExecutor.submit(
ReplayRunnable("$TAG.add_frame") {
cache?.store(frameTimestamp)
if (frame.jumped) {
// first, so this frame isn't dropped with the old timeline's
dropOldTimeline()
bufferedSegments.rotate(bufferLimit = Long.MAX_VALUE)
}
cache?.store(frame.timestamp)

val now = dateProvider.currentTimeMillis
val bufferLimit = now - options.sessionReplay.errorReplayDuration
screenAtStart = cache?.rotate(bufferLimit)
bufferedSegments.rotate(bufferLimit)
},
Expand Down Expand Up @@ -175,7 +180,7 @@ constructor(
return this
}
// we hand over replayExecutor and persistingExecutor to the new strategy to preserve order of
// execution
// execution, and the timeline, which the segments about to be flushed are on
val captureStrategy =
SessionCaptureStrategy(
options,
Expand All @@ -184,6 +189,7 @@ constructor(
ticker,
replayExecutor,
persistingExecutor,
continuedTimeline = clock.timeline,
)
captureStrategy.recorderConfig = recorderConfig
captureStrategy.start(
Expand All @@ -196,7 +202,7 @@ constructor(

override fun onTouchEvent(event: MotionEvent) {
super.onTouchEvent(event)
val bufferLimit = dateProvider.currentTimeMillis - options.sessionReplay.errorReplayDuration
val bufferLimit = clock.nowMillis() - options.sessionReplay.errorReplayDuration
rotateEvents(currentEvents, bufferLimit)
}

Expand Down Expand Up @@ -260,17 +266,19 @@ constructor(
return
}
val errorReplayDuration = options.sessionReplay.errorReplayDuration
val now = dateProvider.currentTimeMillis
val currentSegmentTimestamp =
cache?.firstFrameTimestamp()?.let {
// in buffer mode we have to set the timestamp of the first frame as the actual start
DateUtils.getDateTime(it)
} ?: DateUtils.getDateTime(now - errorReplayDuration)
val duration = now - currentSegmentTimestamp.time
val now = clock.nowMillis()
val replayId = currentReplayId

replayExecutor.submit(
ReplayRunnable("$TAG.$taskName") {
// read here, behind queued frames, so a frame that followed a wall-clock jump has dropped
// the old timeline's frames already
val currentSegmentTimestamp =
cache?.firstFrameTimestamp()?.let {
// in buffer mode we have to set the timestamp of the first frame as the actual start
DateUtils.getDateTime(it)
} ?: DateUtils.getDateTime(now - errorReplayDuration)
val duration = now - currentSegmentTimestamp.time
val segment =
createSegmentInternal(
duration,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package io.sentry.android.replay.capture

import io.sentry.time.AnchoredClock
import io.sentry.time.EpochClock
import io.sentry.time.MonotonicTicker
import io.sentry.time.Timestamp
import java.util.concurrent.TimeUnit.NANOSECONDS
import kotlin.math.abs

/**
* The timeline a recording stamps its frames, segments and touch events on.
*
* Those stamps are subtracted from each other: a segment is the frames within 5s of its start, and
* the buffer is the last 30s. So they come from one [AnchoredClock], where a wall-clock change
* can't drop frames or freeze the video. Breadcrumbs, errors and spans, though, are stamped from
* the wall clock elsewhere in the SDK, and the player places them on the video by that stamp. So
* the timeline must not drift away from the wall clock either: when [wallClockJumpMillis] reports a
* jump, the recording drops what it recorded on the current timeline and [restart]s on the wall
* clock.
*
* Reads are safe from any thread. Checking for a jump and then restarting is a check-then-act, so
* [BaseCaptureStrategy] does both under its timeline lock.
*/
internal class ReplayClock(
private val epochClock: EpochClock,
private val ticker: MonotonicTicker,
continued: AnchoredClock? = null,
) {
internal companion object {
// just under the 1.1s the player shows as a gap in the video
const val JUMP_TOLERANCE_MS = 1000L
}

/** The current timeline. [restart] replaces it, so a reference read once stays consistent. */
@Volatile
var timeline: AnchoredClock = continued ?: AnchoredClock.create(epochClock, ticker)
private set

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

/** Anchors a new timeline on the wall clock and returns it. */
fun restart(): AnchoredClock {
val next = AnchoredClock.create(epochClock, ticker)
timeline = next
return next
}

/**
* How far the wall clock has jumped away from the timeline, positive when it moved forward, or
* `0` while the two agree within [JUMP_TOLERANCE_MS].
*/
fun wallClockJumpMillis(): Long {
val jump = epochClock.now().epochMillis - nowMillis()
return if (abs(jump) > JUMP_TOLERANCE_MS) jump else 0
}
}

internal val Timestamp.epochMillis: Long
get() = NANOSECONDS.toMillis(epochNanos())

internal fun AnchoredClock.nowMillis(): Long = now().epochMillis
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package io.sentry.android.replay.capture

import android.graphics.Bitmap
import io.sentry.DateUtils
import io.sentry.IScopes
import io.sentry.SentryLevel.DEBUG
import io.sentry.SentryLevel.INFO
Expand All @@ -11,6 +12,7 @@ import io.sentry.android.replay.ScreenshotRecorderConfig
import io.sentry.android.replay.capture.CaptureStrategy.ReplaySegment
import io.sentry.android.replay.util.ReplayRunnable
import io.sentry.protocol.SentryId
import io.sentry.time.AnchoredClock
import io.sentry.time.MonotonicTicker
import io.sentry.transport.ICurrentDateProvider
import java.util.Date
Expand All @@ -33,11 +35,12 @@ internal class SessionCaptureStrategy
constructor(
private val options: SentryOptions,
private val scopes: IScopes?,
private val dateProvider: ICurrentDateProvider,
dateProvider: ICurrentDateProvider,
ticker: MonotonicTicker,
executor: ScheduledExecutorService,
persistingExecutor: ScheduledExecutorService,
replayCacheProvider: ((replayId: SentryId) -> ReplayCache)? = null,
continuedTimeline: AnchoredClock? = null,
) :
BaseCaptureStrategy(
options,
Expand All @@ -47,6 +50,7 @@ constructor(
executor,
persistingExecutor,
replayCacheProvider,
continuedTimeline,
) {
internal companion object {
private const val TAG = "SessionCaptureStrategy"
Expand Down Expand Up @@ -114,10 +118,20 @@ constructor(
// have to do it before submitting, otherwise if the queue is busy, the timestamp won't be
// reflecting the exact time of when it was captured
val currentConfig = recorderConfig
val frameTimestamp = dateProvider.currentTimeMillis
val deadlineExceeded = replayDeadline?.hasPassed() == true
val frame = stampFrame(maxForwardJumpMillis = options.sessionReplay.sessionDuration)
val frameTimestamp = frame.timestamp
// a recording can't span a forward jump longer than its cap, so one ends it like the cap does
val deadlineExceeded = replayDeadline?.hasPassed() == true || frame.jumpedTooFar
replayExecutor.submit(
ReplayRunnable("$TAG.add_frame") {
if (frame.jumped) {
// first, so this frame isn't dropped with the old timeline's
dropOldTimeline()
// a stopped recording has none, and must stay stopped
if (segmentTimestamp != null) {
segmentTimestamp = DateUtils.getDateTime(frameTimestamp)
}
}
cache?.store(frameTimestamp)

val currentSegmentTimestamp = segmentTimestamp
Expand Down Expand Up @@ -198,7 +212,7 @@ constructor(
return
}

val requestedAt = dateProvider.currentTimeMillis
val requestedAt = clock.nowMillis()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Segment request racing a jump mixes timelines

Medium Severity

requestedAt (and now in buffer mode) is read on the calling thread, but the segment start is read later in the task. A segment request can race a frame that follows a jump: it can read the clock before the restart and have its task run after the jump task, or the other way round. The duration then comes from two timelines. It ends up minutes or hours too long, or negative.

Additional Locations (1)
Fix in Cursorย Fix in Web

Reviewed by Cursor Bugbot for commit 1db10e9. Configure here.

val replayId = currentReplayId
replayExecutor.submit(
ReplayRunnable("$TAG.$taskName") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1505,10 +1505,7 @@ class ReplayIntegrationTest {
BufferCaptureStrategy(
fixture.options,
fixture.scopes,
// make time jump so session strategy will immediately cut a segment on next frame
ICurrentDateProvider {
System.currentTimeMillis() + fixture.options.sessionReplay.sessionSegmentDuration
},
CurrentDateProvider.getInstance(),
fixture.options.monotonicTicker,
// run tasks synchronously in tests
mock {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ import io.sentry.android.replay.ReplayIntegrationWithRecorderTest.LifecycleState
import io.sentry.android.replay.util.ReplayShadowMediaCodec
import io.sentry.rrweb.RRWebMetaEvent
import io.sentry.rrweb.RRWebVideoEvent
import io.sentry.time.MonotonicTicker
import io.sentry.time.TestMonotonicTicker
import io.sentry.transport.CurrentDateProvider
import io.sentry.transport.ICurrentDateProvider
import io.sentry.util.thread.NoOpThreadChecker
import java.io.File
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.BeforeTest
import kotlin.test.assertEquals
Expand All @@ -45,7 +48,12 @@ class ReplayIntegrationWithRecorderTest {
@get:Rule val tmpDir = TemporaryFolder()

internal class Fixture {
val options = SentryOptions().apply { threadChecker = NoOpThreadChecker.getInstance() }
val ticker = TestMonotonicTicker()
val options =
object : SentryOptions() {
override fun getMonotonicTicker(): MonotonicTicker = ticker
}
.apply { threadChecker = NoOpThreadChecker.getInstance() }
val scopes = mock<IScopes>()

fun getSut(
Expand Down Expand Up @@ -83,11 +91,8 @@ class ReplayIntegrationWithRecorderTest {
fun `works with different recorder`() {
val captured = AtomicBoolean(false)
whenever(fixture.scopes.captureReplay(any(), anyOrNull())).then { captured.set(true) }
// fake current time to trigger segment creation, CurrentDateProvider.getInstance() should
// be used in prod
val dateProvider = ICurrentDateProvider {
System.currentTimeMillis() + fixture.options.sessionReplay.sessionSegmentDuration
}
var now = System.currentTimeMillis()
val dateProvider = ICurrentDateProvider { now }

fixture.options.sessionReplay.isTrackConfiguration = false
fixture.options.sessionReplay.sessionSampleRate = 1.0
Expand Down Expand Up @@ -165,6 +170,9 @@ class ReplayIntegrationWithRecorderTest {
val flutterConfig = ScreenshotRecorderConfig(100, 200, 1f, 1f, 1, 20_000)
replay.onConfigurationChanged(flutterConfig)

// a whole segment later, so the frame closes it
now += fixture.options.sessionReplay.sessionSegmentDuration
fixture.ticker.advance(fixture.options.sessionReplay.sessionSegmentDuration, MILLISECONDS)
replay.onScreenshotRecorded(screenshot, frameTimestamp = 1)

// verify
Expand Down
Loading
Loading