Skip to content

fix(replay): Prevent concurrent PixelCopy frame access#5808

Open
romtsn wants to merge 9 commits into
mainfrom
rz/fix/pixelcopy-frame-race
Open

fix(replay): Prevent concurrent PixelCopy frame access#5808
romtsn wants to merge 9 commits into
mainfrom
rz/fix/pixelcopy-frame-race

Conversation

@romtsn

@romtsn romtsn commented Jul 21, 2026

Copy link
Copy Markdown
Member

📜 Description

Prevent concurrent access to the bitmap shared by PixelCopy and replay processing.

The strategy now drops a capture while another frame is in flight, keeps the gate held through
masking and SurfaceView compositing, suppresses last-frame emission during that work, and defers
bitmap cleanup until the outstanding PixelCopy callback completes.

💡 Motivation and Context

PixelCopy.request() returns before RenderThread finishes writing its destination. The replay
executor could therefore draw masks or SurfaceView content into the same bitmap, while close()
could recycle it before the asynchronous request completed. This could produce torn or improperly
masked frames and may contribute to native libhwui crashes.

Dropping an overlapping frame avoids blocking the main thread or allocating a second recording
bitmap. Replay time remains continuous; the previous frame is displayed longer when a capture is
dropped. This should be rare at the default 1 FPS, while sustained overload at higher frame rates
may reduce visual smoothness rather than emit a corrupt or improperly masked frame.

Fixes #5340
Refs #5340

💚 How did you test it?

  • ./gradlew ':sentry-android-replay:testDebugUnitTest' --tests='*PixelCopyStrategyTest*' --info
  • ./gradlew spotlessApply apiDump

Added regression coverage for requests overlapping PixelCopy, queued masking, last-frame emission,
and cleanup during an outstanding request.

📝 Checklist

  • I added GH Issue ID & Linear ID
  • I added tests to verify the changes.
  • No new PII added or SDK only sends newly added PII if sendDefaultPII is enabled.
  • I updated the docs if needed.
  • I updated the wizard if needed.
  • Review from the native team if needed.
  • No breaking change or entry added to the changelog.
  • No breaking change for hybrid SDKs or communicated to hybrid SDKs.
  • Public API changes reviewed by another Mobile SDK team member or implemented according to the develop docs spec.

🔮 Next steps

  • Harden capture submission around Window and SurfaceView lifecycle transitions separately.
  • Consider restoring RGB_565 when SurfaceView capture is disabled in a separate change.

Keep PixelCopy, masking, compositing, and cleanup from accessing the shared bitmap concurrently.

Fixes GH-5340

Co-Authored-By: Codex <noreply@openai.com>
@linear-code

linear-code Bot commented Jul 21, 2026

Copy link
Copy Markdown

JAVA-490

@sentry

sentry Bot commented Jul 21, 2026

Copy link
Copy Markdown

📲 Install Builds

Android

🔗 App Name App ID Version Configuration
SDK Size io.sentry.tests.size 8.50.0 (1) release

⚙️ sentry-android Build Distribution Settings

@github-actions

github-actions Bot commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

Performance metrics 🚀

  Plain With Sentry Diff
Startup time 388.86 ms 456.52 ms 67.66 ms
Size 0 B 0 B 0 B

Baseline results on branch: main

Startup times

Revision Plain With Sentry Diff
eb95ded 317.51 ms 369.08 ms 51.57 ms
2124a46 319.19 ms 415.04 ms 95.85 ms
c3ee041 310.64 ms 361.90 ms 51.26 ms
dcc6bbf 382.58 ms 462.13 ms 79.54 ms
7a19fee 315.46 ms 368.62 ms 53.16 ms
9054d65 330.94 ms 403.24 ms 72.30 ms
d500866 326.13 ms 378.70 ms 52.58 ms
ad8da22 365.86 ms 427.00 ms 61.14 ms
ed33deb 337.52 ms 484.06 ms 146.54 ms
d15471f 310.26 ms 377.04 ms 66.78 ms

App size

Revision Plain With Sentry Diff
eb95ded 0 B 0 B 0 B
2124a46 1.58 MiB 2.12 MiB 551.51 KiB
c3ee041 0 B 0 B 0 B
dcc6bbf 1.58 MiB 2.12 MiB 553.10 KiB
7a19fee 0 B 0 B 0 B
9054d65 1.58 MiB 2.29 MiB 723.38 KiB
d500866 0 B 0 B 0 B
ad8da22 1.58 MiB 2.29 MiB 719.83 KiB
ed33deb 1.58 MiB 2.13 MiB 559.52 KiB
d15471f 1.58 MiB 2.13 MiB 559.54 KiB

Previous results on branch: rz/fix/pixelcopy-frame-race

Startup times

Revision Plain With Sentry Diff
1976346 313.33 ms 371.69 ms 58.35 ms
8dd71e1 473.33 ms 530.16 ms 56.83 ms
fab3793 330.67 ms 352.10 ms 21.43 ms
fcda53a 318.75 ms 365.57 ms 46.82 ms

App size

Revision Plain With Sentry Diff
1976346 0 B 0 B 0 B
8dd71e1 0 B 0 B 0 B
fab3793 0 B 0 B 0 B
fcda53a 0 B 0 B 0 B

romtsn and others added 3 commits July 22, 2026 12:50
Re-arm the recorder's content-change gate when a capture is skipped because another frame is still in flight. This ensures the latest UI state is retried on the next capture interval.

Refs GH-5340
Co-Authored-By: OpenAI Codex <noreply@openai.com>
@romtsn
romtsn marked this pull request as ready for review July 22, 2026 15:17
Two bugbot findings on #5808:

- Frame gate stuck on callback errors: viewhierarchy traversal or
  captureSurfaceViews throwing between the PixelCopy success check and
  the executor submit left frameInFlight = true forever, silently
  wedging all future captures. Wrap the post-success block in a
  try/finally that releases the gate unless work was successfully
  handed off.
- Cleanup lost after executor shutdown: close() typically runs after
  ReplayIntegration has shut down the replay executor, so submit()
  returns null and the bitmap + maskRenderer were never released. Fall
  back to running cleanup inline in that case.
The mask branch already knows via 'submitted == null' whether the executor
took ownership; the surface-view branch always hands off. Flatten to
explicit finishFrame() calls on the two failure paths (mask null-submit,
outer catch) instead of tracking handoff state across a try/finally.
resetUnstableCaptures = !changedDuringCapture,
)
}
} catch (e: Throwable) {

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.

My understanding is that we are creating this PR because we discovered some crashes.
How will we know that these changes are working if we are catching all the Throwables?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

the crash happens in the native layer which try-catch wouldn't have caught anyway, but I still narrowed this to RuntimeException only, thanks for your vigilance!

}
}
)
if (submitted == null) {

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.

Same here, it can also be null when immediately run.

@romtsn romtsn Jul 22, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

good catch, I refactored the executor service to distinguish between rejection and inline execution in 241129a, thanks!

romtsn added 2 commits July 22, 2026 20:54
ReplayExecutorService.submit previously returned null both when the caller
was on the worker thread (task ran inline) and when the executor rejected
the submission (task did NOT run). Callers had no way to tell them apart.

Return a CompletedFuture sentinel for inline execution; null now means
only rejection. Also narrow PixelCopyStrategy's frame-processing catch
from Throwable to RuntimeException so OOM/LinkageError still propagate.
Cleanup body is already idempotent (screenshot.isRecycled check,
MaskRenderer.close guards on isInitialized + isRecycled). A stray extra
scheduleCleanup would just submit a no-op — not worth the AtomicBoolean.
…ose race

The mock executor closed the strategy on every submit(); since close()
itself submits the cleanup task, this recursed
close() -> scheduleCleanup() -> submit() until the stack overflowed.
Close only when the mask task is submitted.

The prior "does not crash" assertion was also vacuous under the
frameInFlight gate (passed even with the isClosed guard removed). Assert
instead that no screenshot is emitted once close() races masking, which
fails if the guard in applyMaskingAndNotify is removed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 08d009a. Configure here.

if (isClosed.get()) {
scheduleCleanup()
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cleanup races with new capture

High Severity

finishFrame clears frameInFlight before checking isClosed, so a new capture can take the gate and start PixelCopy while the old finishFrame still proceeds to scheduleCleanup after close flips isClosed. That recycles the shared screenshot while RenderThread may still be writing, reintroducing the concurrent bitmap access this change aims to prevent.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 08d009a. Configure here.

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: race between PixelCopy.request and executor compositing/masking on shared screenshot bitmap

2 participants