From 2e416e2986a28568ccd0107439a31f1decd164ec Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 12 Nov 2026 14:34:18 -0500 Subject: [PATCH 1/5] fix(replay): cover render lag and recycled cells in background capture masks With screenshotModeBackgroundCapture, the off-main render can copy pixels that trail the first mask sample, and an owner present in only one sample was masked only where it was sampled. Mask background frames with settleVerdict instead of sweptRects: still frames cover both samples, drifted frames get the trail inflation, and motion or unpaired owners skip the frame. Co-Authored-By: Claude Opus 5.5 --- .changeset/background-capture-mask-lag.md | 5 + .../Replay/PostHogMaskSettleAnalysis.swift | 43 +++---- PostHog/Replay/PostHogReplayIntegration.swift | 13 +- PostHogTests/PostHogMaskScenarioTest.swift | 119 ++++++------------ test-audit/replay.md | 14 +-- 5 files changed, 73 insertions(+), 121 deletions(-) create mode 100644 .changeset/background-capture-mask-lag.md diff --git a/.changeset/background-capture-mask-lag.md b/.changeset/background-capture-mask-lag.md new file mode 100644 index 0000000000..aa3dc4fab9 --- /dev/null +++ b/.changeset/background-capture-mask-lag.md @@ -0,0 +1,5 @@ +--- +'posthog-ios': patch +--- + +With `screenshotModeBackgroundCapture` on, session replay masks drifting content over the position its pixels can trail to, and skips frames captured while the screen scrolls or animates, or while a masked cell is recycled, instead of uploading them with misaligned masks. diff --git a/PostHog/Replay/PostHogMaskSettleAnalysis.swift b/PostHog/Replay/PostHogMaskSettleAnalysis.swift index 0c63155345..3bf50381fc 100644 --- a/PostHog/Replay/PostHogMaskSettleAnalysis.swift +++ b/PostHog/Replay/PostHogMaskSettleAnalysis.swift @@ -111,35 +111,24 @@ return oldRects } - /// Per-owner union of two samples taken either side of a render: covers wherever the - /// content sat while the render ran. An owner present in only one sample was still on - /// screen for part of that window, so its rect is emitted as collected rather than - /// discarding the frame — a scroll that recycles cells changes the owner set constantly, - /// and dropping every such frame freezes the recording across the whole interaction. - /// Unlike `pairedOldRects` the result is a mask list, not positionally tied to `after`. - /// nil only for a repeated owner within one sample, where the pairing is genuinely - /// ambiguous and there is no safe rect to emit. - static func sweptRects(before: [MaskedRegion]?, after: [MaskedRegion]?) -> [CGRect]? { - guard let before, let after, let beforeByOwner = rectsByOwner(before) else { + /// Masks for a frame rendered off-main between two samples, or nil to skip the frame. + /// The off-main render copies the last committed frame, which can trail `before`, so + /// drifted masks take `settleVerdict`'s inflation, including its trail behind `before`. + /// Motion, an unpaired owner (a cell recycled mid-render), or a nil sample skips the frame: + /// no rect is known to cover where that content sat when the pixels were committed, and + /// the presentation-tree renderer the settled path falls back to is main-only. + static func backgroundCaptureMaskRects(before: [MaskedRegion]?, after: [MaskedRegion]?) -> [CGRect]? { + let verdict = settleVerdict(before: before, after: after) + switch verdict.band { + case .still: + // Within tolerance, but the pixels may still show `before`. + guard let after, let oldRects = pairedOldRects(before: before, after: after) else { return nil } + return zip(oldRects, after).map { $0.union($1.rect) } + case .drift: + return verdict.inflatedRects + case .motion: return nil } - - var rects: [CGRect] = [] - rects.reserveCapacity(max(before.count, after.count)) - var seenAfterOwners: Set = [] - seenAfterOwners.reserveCapacity(after.count) - for region in after { - guard seenAfterOwners.insert(region.owner).inserted else { - return nil - } - // No counterpart means the owner appeared mid-render; cover where it landed. - rects.append(beforeByOwner[region.owner].map { $0.union(region.rect) } ?? region.rect) - } - // Owners that went away mid-render were still displayed for part of it. - for region in before where !seenAfterOwners.contains(region.owner) { - rects.append(region.rect) - } - return rects } /// Banded by measured drift: diff --git a/PostHog/Replay/PostHogReplayIntegration.swift b/PostHog/Replay/PostHogReplayIntegration.swift index 149a7017e9..8f3eb0d93c 100644 --- a/PostHog/Replay/PostHogReplayIntegration.swift +++ b/PostHog/Replay/PostHogReplayIntegration.swift @@ -1627,10 +1627,11 @@ } /// The render sits between two mask samples instead of one: measure geometry, render - /// off-main, measure again, mask the per-owner union — provably covering wherever the - /// content sat while the render ran, so no threshold is needed. Always uses - /// `drawHierarchy`, never the presentation-tree renderer: that reads `layer.presentation()`, - /// which is main-only, and this path's other reads already sit inside `main.sync`. + /// off-main, measure again, then mask as `backgroundCaptureMaskRects` decides — swept and + /// trailed when the content drifted, skipped on motion, an unpaired owner, or a missing + /// sample. Always uses `drawHierarchy`, never the presentation-tree renderer: that reads + /// `layer.presentation()`, which is main-only, and this path's other reads already sit + /// inside `main.sync`. @discardableResult private func performBracketedBackgroundCapture(window: UIWindow, screenName: String?, postHog: PostHogSDK) -> Bool { defer { finishScreenshotRender() } @@ -1645,8 +1646,8 @@ let image = window.toImage(preferFidelityRenderer: true) let capture = DispatchQueue.main.sync { () -> ScreenshotCapture? in let after = self.collectMaskedRegions(in: window) - guard let rects = Self.sweptRects(before: before, after: after) else { - hedgeLog("[Session Replay] Skipping snapshot: mask samples could not be paired") + guard let rects = Self.backgroundCaptureMaskRects(before: before, after: after) else { + hedgeLog("[Session Replay] Skipping snapshot: mask geometry could not be covered during background capture") return nil } // No renderer preference: `renderImage: false` means this call never renders — the diff --git a/PostHogTests/PostHogMaskScenarioTest.swift b/PostHogTests/PostHogMaskScenarioTest.swift index aa45519052..28a9e43a64 100644 --- a/PostHogTests/PostHogMaskScenarioTest.swift +++ b/PostHogTests/PostHogMaskScenarioTest.swift @@ -498,46 +498,31 @@ #expect(inflated[0].maxY >= 125.31) } - @Test("swept union covers both sample positions, in after order") - func sweptRectsCoversBothSamplesInAfterOrder() throws { + @Test("background capture masks the trail behind the older sample") + func backgroundCaptureCoversTrailBehindBefore() throws { let a = NSObject() - let b = NSObject() - let before = [ - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), - region(b, CGRect(x: 0, y: 100, width: 100, height: 20)), - ] - // b moves; a is stationary. after is in swapped order vs before, so - // ordering must be recovered from `owner`, not index. - let after = [ - region(b, CGRect(x: 0, y: 130, width: 100, height: 20)), - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), - ] - let swept = try #require(PostHogReplayIntegration.sweptRects(before: before, after: after)) - #expect(swept.count == 2) - - // swept[0] pairs with after[0] (b): union of y=100..120 and y=130..150. - #expect(swept[0] == CGRect(x: 0, y: 100, width: 100, height: 50)) - - // swept[1] pairs with after[1] (a): stationary, so it collapses to a's rect. - #expect(swept[1] == CGRect(x: 0, y: 0, width: 100, height: 20)) - } + let before = [region(a, CGRect(x: 0, y: 100, width: 100, height: 20))] + let after = [region(a, CGRect(x: 0, y: 105, width: 100, height: 20))] + let rects = try #require(PostHogReplayIntegration.backgroundCaptureMaskRects(before: before, after: after)) - @Test("nil before makes sweptRects nil") - func sweptRectsNilBefore() { - let a = NSObject() - let after = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] - #expect(PostHogReplayIntegration.sweptRects(before: nil, after: after) == nil) + // The off-main render can copy pixels committed before `before` was sampled, here at + // y=95; a union of the two samples alone would leave y=95..100 visible. + #expect(rects.count == 1) + #expect(rects[0].contains(CGRect(x: 0, y: 95, width: 100, height: 30))) } - @Test("nil after makes sweptRects nil") - func sweptRectsNilAfter() { + @Test("background capture skips a frame whose cell was recycled mid-render") + func backgroundCaptureSkipsRecycledOwner() { let a = NSObject() + let b = NSObject() let before = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] - #expect(PostHogReplayIntegration.sweptRects(before: before, after: nil) == nil) + let after = [region(b, CGRect(x: 0, y: 200, width: 100, height: 20))] + // Where `a` sat when the pixels were committed was never sampled. + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(before: before, after: after) == nil) } - @Test("an owner that appears mid-render is covered, not dropped") - func sweptRectsCountMismatch() throws { + @Test("background capture skips a frame where an owner appeared mid-render") + func backgroundCaptureSkipsAppearedOwner() { let a = NSObject() let b = NSObject() let before = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] @@ -545,68 +530,42 @@ region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), region(b, CGRect(x: 0, y: 100, width: 100, height: 20)), ] - // b appeared mid-render, so it was displayed for part of the window and is covered - // rather than costing the whole frame. - let swept = try #require(PostHogReplayIntegration.sweptRects(before: before, after: after)) - #expect(swept == [ - CGRect(x: 0, y: 0, width: 100, height: 20), - CGRect(x: 0, y: 100, width: 100, height: 20), - ]) + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(before: before, after: after) == nil) } - @Test("duplicate owner in before makes sweptRects nil") - func sweptRectsDuplicateOwnerInBefore() { + @Test("background capture skips a frame that moved past the drift budget") + func backgroundCaptureSkipsMotion() { let a = NSObject() - let b = NSObject() - let before = [ - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), - ] - let after = [ - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), - region(b, CGRect(x: 0, y: 100, width: 100, height: 20)), - ] - #expect(PostHogReplayIntegration.sweptRects(before: before, after: after) == nil) + let before = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] + let after = [region(a, CGRect(x: 0, y: 200, width: 100, height: 20))] + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(before: before, after: after) == nil) + } + + @Test("background capture skips a frame with a missing sample") + func backgroundCaptureSkipsNilSample() { + let sample = [region(NSObject(), CGRect(x: 0, y: 0, width: 100, height: 20))] + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(before: nil, after: sample) == nil) + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(before: sample, after: nil) == nil) } - @Test("duplicate owner in after makes sweptRects nil") - func sweptRectsDuplicateOwnerInAfter() { + @Test("background capture masks both samples of a still frame, paired by owner") + func backgroundCaptureStillCoversBothSamples() throws { let a = NSObject() let b = NSObject() let before = [ region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), region(b, CGRect(x: 0, y: 100, width: 100, height: 20)), ] + // a moves 1pt, within the still tolerance; after is in swapped order. let after = [ - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), - region(a, CGRect(x: 0, y: 0, width: 100, height: 20)), + region(b, CGRect(x: 0, y: 100, width: 100, height: 20)), + region(a, CGRect(x: 0, y: 1, width: 100, height: 20)), ] - #expect(PostHogReplayIntegration.sweptRects(before: before, after: after) == nil) - } - - @Test("a fully recycled owner set covers both samples, not nil") - func sweptRectsDisjointOwnerSet() throws { - let a = NSObject() - let b = NSObject() - let before = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] - let after = [region(b, CGRect(x: 0, y: 200, width: 100, height: 20))] - // Neither owner can be paired, but both were on screen during the render window: - // `after` entries come first, then the ones that went away. - let swept = try #require(PostHogReplayIntegration.sweptRects(before: before, after: after)) - #expect(swept == [ - CGRect(x: 0, y: 200, width: 100, height: 20), - CGRect(x: 0, y: 0, width: 100, height: 20), + let rects = try #require(PostHogReplayIntegration.backgroundCaptureMaskRects(before: before, after: after)) + #expect(rects == [ + CGRect(x: 0, y: 100, width: 100, height: 20), + CGRect(x: 0, y: 0, width: 100, height: 21), ]) } - - @Test("a stationary owner's swept rect equals its rect unchanged") - func sweptRectsStationaryOwnerUnchanged() throws { - let a = NSObject() - let rect = CGRect(x: 10, y: 20, width: 100, height: 20) - let before = [region(a, rect)] - let after = [region(a, rect)] - let swept = try #require(PostHogReplayIntegration.sweptRects(before: before, after: after)) - #expect(swept == [rect]) - } } #endif diff --git a/test-audit/replay.md b/test-audit/replay.md index d4b230ebcd..4a4b0aa2ff 100644 --- a/test-audit/replay.md +++ b/test-audit/replay.md @@ -383,14 +383,12 @@ Production owner: presentation-aware mask collection. The harness requires visib | 450 | `emptyArraysStill` | R — legitimate no-mask geometry settles. | | 457 | `driftInflationCoversSweepInAfterOrder` | R — swept coverage and owner ordering; catches wrong pairing/under-inflation. | | 486 | `driftInflationCoversTrailBehindBefore` | R — displayed-pixel lag requires trailing inflation. | -| 502 | `sweptRectsCoversBothSamplesInAfterOrder` | R — union and owner ordering independently specified. | -| 526 | `sweptRectsNilBefore` | R — missing sample cannot manufacture a safe union. | -| 533 | `sweptRectsNilAfter` | R — same later-sample guard. | -| 540 | `sweptRectsCountMismatch` | R — newly appearing owner remains covered. | -| 558 | `sweptRectsDuplicateOwnerInBefore` | R — ambiguous duplicate pairing returns nil. | -| 573 | `sweptRectsDuplicateOwnerInAfter` | R — symmetric ambiguity guard. | -| 588 | `sweptRectsDisjointOwnerSet` | R — recycled owners cover both samples instead of losing disappeared content. | -| 603 | `sweptRectsStationaryOwnerUnchanged` | R — stationary union does not distort mask. | +| 502 | `backgroundCaptureCoversTrailBehindBefore` | R — off-main pixels can trail `before`; the mask covers that trail. | +| 515 | `backgroundCaptureSkipsRecycledOwner` | R — a recycled cell's committed position is unknown, so the frame is skipped. | +| 525 | `backgroundCaptureSkipsAppearedOwner` | R — an owner appearing mid-render cannot be paired, so the frame is skipped. | +| 537 | `backgroundCaptureSkipsMotion` | R — motion has no off-main aligned renderer, so the frame is skipped. | +| 545 | `backgroundCaptureSkipsNilSample` | R — a missing sample cannot manufacture safe masks. | +| 552 | `backgroundCaptureStillCoversBothSamples` | R — still frames still cover both samples, paired by owner. | ### 5. `PostHogMaskSnapshotTest.swift` From 4ec875480ef44441457b209ec0e61bb3d8328368 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 12 Nov 2026 15:13:22 -0500 Subject: [PATCH 2/5] fix(replay): wait before the background render so still frames have caught up On device, the off-main render still showed the pre-stop scroll position for 30-40ms after an abrupt stop. Skipping every moving frame meant the first accepted frame landed in that window, with masks a row off the text. Take the first mask sample 100ms before the render, so a still verdict spans longer than that lag. Co-Authored-By: Claude Opus 5.5 --- .../Replay/PostHogMaskSettleAnalysis.swift | 5 +++ PostHog/Replay/PostHogReplayIntegration.swift | 33 +++++++++++-------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/PostHog/Replay/PostHogMaskSettleAnalysis.swift b/PostHog/Replay/PostHogMaskSettleAnalysis.swift index 3bf50381fc..c4be394f94 100644 --- a/PostHog/Replay/PostHogMaskSettleAnalysis.swift +++ b/PostHog/Replay/PostHogMaskSettleAnalysis.swift @@ -41,6 +41,11 @@ /// invalidating them. static let settleWindowSeconds: TimeInterval = 0.025 + /// Gap between the first mask sample and the off-main background render. On device, that + /// render still showed the pre-stop scroll position for 30-40ms after an abrupt stop, so a + /// still verdict must span longer than that for the pixels to have caught up. + static let backgroundCaptureLeadSeconds: TimeInterval = 0.1 + /// At or below 80pt/s, geometry counts as unmoved and rects are used exactly as sampled. /// Raise only to stop idle screens paying for inflation, and only a little: this much /// displacement then goes uncompensated, so it is the one knob that trades directly diff --git a/PostHog/Replay/PostHogReplayIntegration.swift b/PostHog/Replay/PostHogReplayIntegration.swift index 8f3eb0d93c..c03fc1565e 100644 --- a/PostHog/Replay/PostHogReplayIntegration.swift +++ b/PostHog/Replay/PostHogReplayIntegration.swift @@ -1626,19 +1626,28 @@ ) } - /// The render sits between two mask samples instead of one: measure geometry, render - /// off-main, measure again, then mask as `backgroundCaptureMaskRects` decides — swept and - /// trailed when the content drifted, skipped on motion, an unpaired owner, or a missing - /// sample. Always uses `drawHierarchy`, never the presentation-tree renderer: that reads - /// `layer.presentation()`, which is main-only, and this path's other reads already sit - /// inside `main.sync`. + /// The render sits between two mask samples instead of one: measure geometry, wait + /// `backgroundCaptureLeadSeconds`, render off-main, measure again, then mask as + /// `backgroundCaptureMaskRects` decides — swept and trailed when the content drifted, + /// skipped on motion, an unpaired owner, or a missing sample. Always uses `drawHierarchy`, + /// never the presentation-tree renderer: that reads `layer.presentation()`, which is + /// main-only, and this path's other reads already sit inside `main.sync`. + private func scheduleBracketedBackgroundCapture(window: UIWindow, screenName: String?, postHog: PostHogSDK) { + guard let before = collectMaskedRegions(in: window) else { + finishScreenshotRender() + return + } + PostHogReplayIntegration.dispatchQueue.asyncAfter(deadline: .now() + Self.backgroundCaptureLeadSeconds) { [weak self] in + self?.performBracketedBackgroundCapture(window: window, before: before, screenName: screenName, postHog: postHog) + } + } + @discardableResult - private func performBracketedBackgroundCapture(window: UIWindow, screenName: String?, postHog: PostHogSDK) -> Bool { + private func performBracketedBackgroundCapture( + window: UIWindow, before: [MaskedRegion], screenName: String?, postHog: PostHogSDK + ) -> Bool { defer { finishScreenshotRender() } - guard let before = DispatchQueue.main.sync(execute: { self.collectMaskedRegions(in: window) }) else { - return false - } // Off-main on purpose, and the reason this mode exists: drawHierarchy on main was too // slow to keep up. UIKit documents it as main-thread-only, so it stays experimental // behind `screenshotModeBackgroundCapture` — the bracketing above is what keeps masks @@ -1728,9 +1737,7 @@ } if postHog.config.sessionReplayConfig.screenshotModeBackgroundCapture { - PostHogReplayIntegration.dispatchQueue.async { [weak self] in - self?.performBracketedBackgroundCapture(window: window, screenName: screenName, postHog: postHog) - } + scheduleBracketedBackgroundCapture(window: window, screenName: screenName, postHog: postHog) } else { scheduleSettledCapture(window: window, screenName: screenName, postHog: postHog) } From 939b5f9994ad0e4267786f797b37c5d134386f16 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 12 Nov 2026 15:46:32 -0500 Subject: [PATCH 3/5] docs(replay): state the measured margin for the background-capture lead Co-Authored-By: Claude Opus 5.5 --- PostHog/Replay/PostHogMaskSettleAnalysis.swift | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/PostHog/Replay/PostHogMaskSettleAnalysis.swift b/PostHog/Replay/PostHogMaskSettleAnalysis.swift index c4be394f94..63966f3a35 100644 --- a/PostHog/Replay/PostHogMaskSettleAnalysis.swift +++ b/PostHog/Replay/PostHogMaskSettleAnalysis.swift @@ -41,9 +41,10 @@ /// invalidating them. static let settleWindowSeconds: TimeInterval = 0.025 - /// Gap between the first mask sample and the off-main background render. On device, that - /// render still showed the pre-stop scroll position for 30-40ms after an abrupt stop, so a - /// still verdict must span longer than that for the pixels to have caught up. + /// Gap between the first mask sample and the off-main background render. On device, a render + /// taken right after an abrupt scroll stop still showed the pre-stop position; a still + /// verdict must span longer than that lag. 25ms already avoided it in testing, so this + /// leaves margin for slower devices. static let backgroundCaptureLeadSeconds: TimeInterval = 0.1 /// At or below 80pt/s, geometry counts as unmoved and rects are used exactly as sampled. From 27303a4276dc2b7ccde84a3b71722b5174051945 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 12 Nov 2026 15:57:21 -0500 Subject: [PATCH 4/5] fix(replay): keep a render-adjacent mask sample and drop samples on main The lead wait moved the only pre-render sample 100ms earlier, so content that moved, appeared or vanished during the wait could go unmasked, and the delayed sample could release its views on the replay queue. Sample again right before the render, require each consecutive pair to be coverable, and release every sample inside the final main.sync. --- .../Replay/PostHogMaskSettleAnalysis.swift | 15 +++++++++ PostHog/Replay/PostHogReplayIntegration.swift | 31 +++++++++++++++---- PostHogTests/PostHogMaskScenarioTest.swift | 26 ++++++++++++++++ test-audit/replay.md | 3 ++ 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/PostHog/Replay/PostHogMaskSettleAnalysis.swift b/PostHog/Replay/PostHogMaskSettleAnalysis.swift index 63966f3a35..443d428bb8 100644 --- a/PostHog/Replay/PostHogMaskSettleAnalysis.swift +++ b/PostHog/Replay/PostHogMaskSettleAnalysis.swift @@ -137,6 +137,21 @@ } } + /// Three-sample form: `lead` is taken `backgroundCaptureLeadSeconds` before `before`, so a + /// still span covers the render's lag, while `before` stays adjacent to the render and + /// catches anything that moved, appeared or vanished during the wait. Each consecutive + /// pair must be coverable on its own; the masks are the union of both. + static func backgroundCaptureMaskRects( + lead: [MaskedRegion]?, before: [MaskedRegion]?, after: [MaskedRegion]? + ) -> [CGRect]? { + guard let leading = backgroundCaptureMaskRects(before: lead, after: before), + let trailing = backgroundCaptureMaskRects(before: before, after: after) + else { + return nil + } + return leading + trailing + } + /// Banded by measured drift: /// - still (≤ tolerance): rects as collected. /// - drift (≤ budget): each mask inflated to the swept region (both sampled positions diff --git a/PostHog/Replay/PostHogReplayIntegration.swift b/PostHog/Replay/PostHogReplayIntegration.swift index c03fc1565e..1a258ee985 100644 --- a/PostHog/Replay/PostHogReplayIntegration.swift +++ b/PostHog/Replay/PostHogReplayIntegration.swift @@ -1626,36 +1626,55 @@ ) } - /// The render sits between two mask samples instead of one: measure geometry, wait - /// `backgroundCaptureLeadSeconds`, render off-main, measure again, then mask as + /// Three mask samples around an off-main render: measure geometry, wait + /// `backgroundCaptureLeadSeconds`, measure again, render, measure a third time, then mask as /// `backgroundCaptureMaskRects` decides — swept and trailed when the content drifted, /// skipped on motion, an unpaired owner, or a missing sample. Always uses `drawHierarchy`, /// never the presentation-tree renderer: that reads `layer.presentation()`, which is /// main-only, and this path's other reads already sit inside `main.sync`. private func scheduleBracketedBackgroundCapture(window: UIWindow, screenName: String?, postHog: PostHogSDK) { - guard let before = collectMaskedRegions(in: window) else { + var lead = collectMaskedRegions(in: window) + guard lead != nil else { finishScreenshotRender() return } PostHogReplayIntegration.dispatchQueue.asyncAfter(deadline: .now() + Self.backgroundCaptureLeadSeconds) { [weak self] in - self?.performBracketedBackgroundCapture(window: window, before: before, screenName: screenName, postHog: postHog) + guard let self else { + DispatchQueue.main.async { lead = nil } + return + } + self.performBracketedBackgroundCapture(window: window, lead: &lead, screenName: screenName, postHog: postHog) } } + /// `lead` is inout so it can be dropped on main: MaskedRegion retains its view, and a view's + /// last release (with its UIKit teardown) must not run on the replay queue. @discardableResult private func performBracketedBackgroundCapture( - window: UIWindow, before: [MaskedRegion], screenName: String?, postHog: PostHogSDK + window: UIWindow, lead: inout [MaskedRegion]?, screenName: String?, postHog: PostHogSDK ) -> Bool { defer { finishScreenshotRender() } + var before = DispatchQueue.main.sync { () -> [MaskedRegion]? in + let sample = self.collectMaskedRegions(in: window) + if sample == nil { lead = nil } + return sample + } + guard before != nil else { + return false + } // Off-main on purpose, and the reason this mode exists: drawHierarchy on main was too // slow to keep up. UIKit documents it as main-thread-only, so it stays experimental // behind `screenshotModeBackgroundCapture` — the bracketing above is what keeps masks // aligned with pixels despite the render happening on this thread. let image = window.toImage(preferFidelityRenderer: true) let capture = DispatchQueue.main.sync { () -> ScreenshotCapture? in + defer { + lead = nil + before = nil + } let after = self.collectMaskedRegions(in: window) - guard let rects = Self.backgroundCaptureMaskRects(before: before, after: after) else { + guard let rects = Self.backgroundCaptureMaskRects(lead: lead, before: before, after: after) else { hedgeLog("[Session Replay] Skipping snapshot: mask geometry could not be covered during background capture") return nil } diff --git a/PostHogTests/PostHogMaskScenarioTest.swift b/PostHogTests/PostHogMaskScenarioTest.swift index 28a9e43a64..137c91f5f2 100644 --- a/PostHogTests/PostHogMaskScenarioTest.swift +++ b/PostHogTests/PostHogMaskScenarioTest.swift @@ -567,5 +567,31 @@ CGRect(x: 0, y: 0, width: 100, height: 21), ]) } + + @Test("background capture skips content that moved during the lead wait and came back") + func backgroundCaptureSkipsBounceDuringLead() { + let a = NSObject() + let lead = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] + // Rendered at y=100, back at y=0 by the last sample. + let before = [region(a, CGRect(x: 0, y: 100, width: 100, height: 20))] + let after = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(lead: lead, before: before, after: after) == nil) + } + + @Test("background capture skips a private view that appeared during the lead wait and vanished") + func backgroundCaptureSkipsTransientOwner() { + let before = [region(NSObject(), CGRect(x: 0, y: 0, width: 100, height: 20))] + #expect(PostHogReplayIntegration.backgroundCaptureMaskRects(lead: [], before: before, after: []) == nil) + } + + @Test("background capture masks every sampled position when all three samples are still") + func backgroundCaptureStillAcrossThreeSamples() throws { + let a = NSObject() + let lead = [region(a, CGRect(x: 0, y: 0, width: 100, height: 20))] + let before = [region(a, CGRect(x: 0, y: 1, width: 100, height: 20))] + let after = [region(a, CGRect(x: 0, y: 2, width: 100, height: 20))] + let rects = try #require(PostHogReplayIntegration.backgroundCaptureMaskRects(lead: lead, before: before, after: after)) + #expect(rects == [CGRect(x: 0, y: 0, width: 100, height: 21), CGRect(x: 0, y: 1, width: 100, height: 21)]) + } } #endif diff --git a/test-audit/replay.md b/test-audit/replay.md index 4a4b0aa2ff..5afe149809 100644 --- a/test-audit/replay.md +++ b/test-audit/replay.md @@ -389,6 +389,9 @@ Production owner: presentation-aware mask collection. The harness requires visib | 537 | `backgroundCaptureSkipsMotion` | R — motion has no off-main aligned renderer, so the frame is skipped. | | 545 | `backgroundCaptureSkipsNilSample` | R — a missing sample cannot manufacture safe masks. | | 552 | `backgroundCaptureStillCoversBothSamples` | R — still frames still cover both samples, paired by owner. | +| 572 | `backgroundCaptureSkipsBounceDuringLead` | R — movement during the lead wait that returns by the last sample still skips. | +| 582 | `backgroundCaptureSkipsTransientOwner` | R — a private view present only at render time skips the frame. | +| 588 | `backgroundCaptureStillAcrossThreeSamples` | R — still frames mask every sampled position. | ### 5. `PostHogMaskSnapshotTest.swift` From e59029cd0a0eb3f70dada4b24785f0300b529157 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 12 Nov 2026 16:22:24 -0500 Subject: [PATCH 5/5] perf(replay): skip background frames before rendering when the lead pair fails --- PostHog/Replay/PostHogReplayIntegration.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/PostHog/Replay/PostHogReplayIntegration.swift b/PostHog/Replay/PostHogReplayIntegration.swift index 1a258ee985..913fef1d9a 100644 --- a/PostHog/Replay/PostHogReplayIntegration.swift +++ b/PostHog/Replay/PostHogReplayIntegration.swift @@ -1657,7 +1657,12 @@ var before = DispatchQueue.main.sync { () -> [MaskedRegion]? in let sample = self.collectMaskedRegions(in: window) - if sample == nil { lead = nil } + // The lead pair alone decides most motion frames; skip them before paying for a render. + guard Self.backgroundCaptureMaskRects(before: lead, after: sample) != nil else { + lead = nil + hedgeLog("[Session Replay] Skipping snapshot: mask geometry could not be covered during background capture") + return nil + } return sample } guard before != nil else {