Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(visual-review): absorb small vertical shifts instead of flagging the whole page (#96238)

Julian Bezc43654e84406
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 7bd1d5d5786c..ae6afb93da4c 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9095,7 +9095,7 @@ snapshots:
scenes-app-visual-review-run--ready-to-finalize--dark:
hash: v1.k794b7964.879549ba86b942a0497ef5b08bb0172ac58c62fe8da41a21584c82bea231db20.lG7LsOxr5tzXDBwFMJwt3c7IgoQuIH6h8qlUZnPNJVw
scenes-app-visual-review-run--ready-to-finalize--light:
- hash: v1.k794b7964.0d8d3ddc1d9df90c6cd478955c3cdf9d8558b5c815cda8b0229df186ca9631b6.6Y2TI_P5yWT2O5LWBnfmoteb9CA1FxlTBMRi4F8L1tQ
+ hash: v1.k794b7964.197e6fe1cc9dba0da720ef1e1cfc94b3601d775aa389e49230465a2b65797d47.Tqyss84UbEfq4Gra3v9eMtLs4zfONfl5fSfff9FlmZA
scenes-app-visual-review-run--tracking-only-master-run--dark:
hash: v1.k794b7964.16fda1278ef2eb5cec07ca3903959e2701d2ff01e37c20a9b4e5cd013a765dd0.TQ9RJbHXN6hccxpL_rOIK0ylVS9s8KVzCjNgCZWqi6w
scenes-app-visual-review-run--tracking-only-master-run--light:
diff --git a/frontend/src/lib/components/VisualImageDiffViewer/OverlayRect.tsx b/frontend/src/lib/components/VisualImageDiffViewer/OverlayRect.tsx
new file mode 100644
index 000000000000..187bb160b6de
--- /dev/null
+++ b/frontend/src/lib/components/VisualImageDiffViewer/OverlayRect.tsx
@@ -0,0 +1,55 @@
+// A one-row band is a zero-area rect once the SVG scales it down. The stroke
+// is non-scaling so it still draws, but the fill needs a floor to be visible.
+const MIN_OVERLAY_SIDE_PX = 3
+
+interface OverlayRectProps {
+ x: number
+ y: number
+ width: number
+ height: number
+ fill: string
+ stroke: string
+ strokeWidth: number
+ strokeDasharray?: string
+ opacity?: number
+ onHover?: (index: number | null) => void
+ index?: number
+}
+
+/** One overlay rectangle, clamped so a one-pixel side still has an area to fill. */
+export function OverlayRect({
+ x,
+ y,
+ width,
+ height,
+ fill,
+ stroke,
+ strokeWidth,
+ strokeDasharray,
+ opacity,
+ onHover,
+ index,
+}: OverlayRectProps): JSX.Element {
+ const hoverable = !!onHover && index !== undefined
+ return (
+ <rect
+ x={x}
+ y={y}
+ width={Math.max(width, MIN_OVERLAY_SIDE_PX)}
+ height={Math.max(height, MIN_OVERLAY_SIDE_PX)}
+ fill={fill}
+ stroke={stroke}
+ strokeWidth={strokeWidth}
+ strokeDasharray={strokeDasharray}
+ opacity={opacity}
+ vectorEffect="non-scaling-stroke"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ pointerEvents: hoverable ? 'auto' : 'none',
+ cursor: hoverable ? 'pointer' : undefined,
+ }}
+ onMouseEnter={hoverable ? () => onHover(index) : undefined}
+ onMouseLeave={hoverable ? () => onHover(null) : undefined}
+ />
+ )
+}
diff --git a/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.test.tsx b/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.test.tsx
index 86f22785eba7..c3f842059d65 100644
--- a/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.test.tsx
+++ b/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.test.tsx
@@ -3,7 +3,7 @@ import '@testing-library/jest-dom'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { VisualImageDiffViewer } from './VisualImageDiffViewer'
+import { type DiffOverlayBand, VisualImageDiffViewer } from './VisualImageDiffViewer'
describe('VisualImageDiffViewer', () => {
afterEach(() => {
@@ -31,4 +31,66 @@ describe('VisualImageDiffViewer', () => {
const zoomedImage = document.querySelector('[data-attr="visual-review-zoomed-image"] img')
expect(zoomedImage).toHaveAttribute('src', expectedUrl)
})
+
+ it.each<[string, DiffOverlayBand, string, string]>([
+ ['fills the rows an insert added', { y: 10, rows: 20, kind: 'inserted' }, '10', '20'],
+ ['draws a deletion as a seam instead of a region', { y: 40, rows: 20, kind: 'deleted' }, '40', '3'],
+ ['keeps a deletion at the bottom edge in frame', { y: 100, rows: 20, kind: 'deleted' }, '97', '3'],
+ ])('%s', (_case, band, expectedY, expectedHeight) => {
+ render(
+ <VisualImageDiffViewer
+ baselineUrl="/before.png"
+ currentUrl="/after.png"
+ diffUrl="/diff.png"
+ diffPercentage={1}
+ result="changed"
+ mode="diff"
+ imageWidth={100}
+ imageHeight={100}
+ diffOverlayBands={[band]}
+ />
+ )
+
+ const bandRect = document.querySelector('svg[viewBox="0 0 100 100"] rect')
+ expect(bandRect).toHaveAttribute('y', expectedY)
+ expect(bandRect).toHaveAttribute('height', expectedHeight)
+ })
+
+ // With a 100x200 baseline and a 100x100 current the shared canvas is 100x200.
+ // An aligned diff is recorded at the current size and must cover half of it;
+ // an unaligned diff is recorded at the padded canvas size and must fill it.
+ it.each<[string, number, string, string | null]>([
+ ['maps a current-sized diff onto the shorter current image', 100, '50%', '50%'],
+ ['leaves a union-sized diff filling the shared canvas', 200, '100%', null],
+ ])('%s', async (_case, diffHeight, expectedDiffHeight, expectedOverlayHeight) => {
+ const user = userEvent.setup()
+
+ render(
+ <VisualImageDiffViewer
+ baselineUrl="/before.png"
+ currentUrl="/after.png"
+ diffUrl="/diff.png"
+ diffPercentage={1}
+ result="changed"
+ mode="blend"
+ imageWidth={100}
+ imageHeight={100}
+ baselineWidth={100}
+ baselineHeight={200}
+ currentWidth={100}
+ currentHeight={100}
+ diffOverlayWidth={100}
+ diffOverlayHeight={diffHeight}
+ diffOverlayBands={[{ y: 40, rows: 5, kind: 'inserted' }]}
+ />
+ )
+
+ await user.click(screen.getByLabelText('Diff overlay'))
+ expect(screen.getByAltText('Diff overlay').style.height).toBe(expectedDiffHeight)
+
+ // A union-sized diff puts the bands in coords that match neither image,
+ // so the viewer skips the overlay instead of placing it wrongly.
+ const overlayLayer = document.querySelector(`svg[viewBox="0 0 100 ${diffHeight}"]`)?.parentElement
+ expect(overlayLayer?.style.height ?? null).toBe(expectedOverlayHeight)
+ })
})
diff --git a/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx b/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx
index 06241168c6b2..c0597e7c5d6a 100644
--- a/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx
+++ b/frontend/src/lib/components/VisualImageDiffViewer/VisualImageDiffViewer.tsx
@@ -5,6 +5,8 @@ import { LemonSegmentedButton, LemonSlider, LemonSwitch, LemonTag, type LemonTag
import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { cn } from 'lib/utils/css-classes'
+import { OverlayRect } from './OverlayRect'
+
export type VisualDiffResult = 'changed' | 'new' | 'removed' | 'unchanged'
export type ComparisonMode = 'sideBySide' | 'blend' | 'split' | 'diff'
@@ -17,6 +19,17 @@ export interface DiffOverlayBox {
height: number
}
+/**
+ * A run of rows the current image gained or lost, in natural image coordinates.
+ * A deleted band's rows are not in the current image, so its `y` is the seam the
+ * removed rows left behind, not the top of a region that is still there.
+ */
+export interface DiffOverlayBand {
+ y: number
+ rows: number
+ kind: 'inserted' | 'deleted'
+}
+
export interface VisualImageDiffViewerProps {
baselineUrl: string | null
currentUrl: string | null
@@ -47,6 +60,14 @@ export interface VisualImageDiffViewerProps {
* viewBox + preserveAspectRatio="none". Empty array == no overlays.
*/
diffOverlayBoxes?: DiffOverlayBox[]
+ /**
+ * Rows the current image gained or lost, in the same vertical coord space
+ * as `diffOverlayBoxes`. Each band spans the full width, so it carries no
+ * x. Drawn in their own color because a band is where content moved, not
+ * where it changed, and unlike clusters they stay visible when the cluster
+ * toggle is off.
+ */
+ diffOverlayBands?: DiffOverlayBand[]
/**
* Natural-pixel dimensions of the bbox coord space — the diff
* image's dimensions, which equal current/baseline when sizes
@@ -97,6 +118,8 @@ interface ImagePanelProps {
imgStyle?: React.CSSProperties
/** When set, draw bbox outlines over the image at these natural-coord positions. */
overlayBoxes?: DiffOverlayBox[]
+ /** Shift bands, drawn in the same coord space as `overlayBoxes`. */
+ overlayBands?: DiffOverlayBand[]
overlayWidth?: number
overlayHeight?: number
/** Highlighted cluster index — that one box renders emphasized. */
@@ -113,13 +136,15 @@ function ImagePanel({
imgClassName,
imgStyle,
overlayBoxes,
+ overlayBands,
overlayWidth,
overlayHeight,
highlightedOverlayIndex,
onOverlayHover,
onClick,
}: ImagePanelProps): JSX.Element {
- const hasOverlay = !!url && !!overlayBoxes && overlayBoxes.length > 0 && !!overlayWidth && !!overlayHeight
+ const boxCount = (overlayBoxes?.length ?? 0) + (overlayBands?.length ?? 0)
+ const hasOverlay = !!url && boxCount > 0 && !!overlayWidth && !!overlayHeight
const image = url ? (
// `block` on the inline-block wrapper kills the implicit
// baseline-descender gap that nudges the SVG overlay a few
@@ -136,7 +161,8 @@ function ImagePanel({
/>
{hasOverlay && (
<BboxOverlay
- boxes={overlayBoxes!}
+ boxes={overlayBoxes ?? []}
+ bands={overlayBands}
width={overlayWidth!}
height={overlayHeight!}
highlightedIndex={highlightedOverlayIndex ?? null}
@@ -174,6 +200,8 @@ function ImagePanel({
interface BboxOverlayProps {
boxes: DiffOverlayBox[]
+ /** Rows the current image gained or lost. Not numbered and not hoverable. */
+ bands?: DiffOverlayBand[]
/** Natural pixel coord space the bboxes live in. */
width: number
height: number
@@ -185,11 +213,22 @@ interface BboxOverlayProps {
// Warm orange palette to match the mockup — distinct from the
// blue-tinted "Before/After" labels and the green/red of result tags.
+// These are literal colors rather than tokens because they are drawn over a
+// screenshot, so they have to read the same whatever theme the page is in.
const OVERLAY_STROKE = 'rgb(245, 134, 52)'
const OVERLAY_FILL_DEFAULT = 'rgba(245, 134, 52, 0.10)'
const OVERLAY_FILL_HIGHLIGHT = 'rgba(245, 134, 52, 0.28)'
-function BboxOverlay({ boxes, width, height, highlightedIndex, onHover }: BboxOverlayProps): JSX.Element {
+// Violet for shift bands, so a band is never read as a change region.
+const BAND_STROKE = 'rgb(124, 92, 214)'
+const BAND_FILL = 'rgba(124, 92, 214, 0.22)'
+
+// A deleted band marks a seam, not a region, so it gets a fixed thin height
+// instead of the rows it removed. A deletion at the bottom edge sits at
+// y = height, so the seam is clamped to keep it inside the image.
+const BAND_SEAM_HEIGHT = 3
+
+function BboxOverlay({ boxes, bands, width, height, highlightedIndex, onHover }: BboxOverlayProps): JSX.Element {
return (
<>
<svg
@@ -204,11 +243,40 @@ function BboxOverlay({ boxes, width, height, highlightedIndex, onHover }: BboxOv
viewBox={`0 0 ${width} ${height}`}
preserveAspectRatio="none"
>
+ {/* A band spans the whole image, so it reads as a rule across the
+ * diff rather than as a region of it. Inserted rows are there to
+ * fill. Deleted rows are not, so their band marks the solid seam
+ * they left behind instead of covering the rows below it. */}
+ {(bands ?? []).map((band, i) =>
+ band.kind === 'deleted' ? (
+ <OverlayRect
+ key={`band-${i}`}
+ x={0}
+ y={Math.max(0, Math.min(band.y, height - BAND_SEAM_HEIGHT))}
+ width={width}
+ height={BAND_SEAM_HEIGHT}
+ fill={BAND_STROKE}
+ stroke={BAND_STROKE}
+ strokeWidth={2}
+ />
+ ) : (
+ <OverlayRect
+ key={`band-${i}`}
+ x={0}
+ y={band.y}
+ width={width}
+ height={band.rows}
+ fill={BAND_FILL}
+ stroke={BAND_STROKE}
+ strokeWidth={2}
+ />
+ )
+ )}
{boxes.map((b, i) => {
const isHighlighted = highlightedIndex === i
const isDimmed = highlightedIndex !== null && !isHighlighted
return (
- <rect
+ <OverlayRect
key={i}
x={b.x}
y={b.y}
@@ -219,14 +287,8 @@ function BboxOverlay({ boxes, width, height, highlightedIndex, onHover }: BboxOv
strokeWidth={isHighlighted ? 3 : 2}
strokeDasharray={isHighlighted ? undefined : '4 3'}
opacity={isDimmed ? 0.4 : 1}
- vectorEffect="non-scaling-stroke"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- pointerEvents: onHover ? 'auto' : 'none',
- cursor: onHover ? 'pointer' : undefined,
- }}
- onMouseEnter={onHover ? () => onHover(i) : undefined}
- onMouseLeave={onHover ? () => onHover(null) : undefined}
+ onHover={onHover}
+ index={i}
/>
)
})}
@@ -301,6 +363,7 @@ export function VisualImageDiffViewer({
currentWidth,
currentHeight,
diffOverlayBoxes,
+ diffOverlayBands,
diffOverlayWidth,
diffOverlayHeight,
highlightedOverlayIndex,
@@ -316,6 +379,13 @@ export function VisualImageDiffViewer({
const hasOverlayBoxes = !!diffOverlayBoxes && diffOverlayBoxes.length > 0
const [showClusters, setShowClusters] = useState(true)
const overlayBoxesIfShown = showClusters ? diffOverlayBoxes : undefined
+ // Bands stay on with the cluster toggle off. A shift band is what the
+ // toggle is meant to leave behind: where the page moved, not what changed.
+ const hasOverlayContent = (overlayBoxesIfShown?.length ?? 0) + (diffOverlayBands?.length ?? 0) > 0
+ // Overlays live in the diff image's coord space. When that space is the
+ // padded size they line up with neither the baseline nor the current
+ // image, so every surface that draws over one of those two has to check.
+ const overlayCoordsMatch = overlayCoordWidth === imageWidth && overlayCoordHeight === imageHeight
const supportsComparison = isComparisonResult(result)
const hasBothImages = Boolean(baselineUrl && currentUrl)
const hasDiffImage = Boolean(diffUrl)
@@ -372,6 +442,17 @@ export function VisualImageDiffViewer({
return pixelated
}
+ // The diff raster and the overlays live in the diff image's coord space, so
+ // on the shared canvas they cover that space's fraction of it, the way an
+ // image layer does. The diff is current-sized when the pair aligned, and it
+ // then has to land on the current image instead of stretching over the empty
+ // area a taller baseline leaves behind. Without alignment the diff is the
+ // padded union size, and this leaves it filling the whole canvas.
+ const diffLayerIsFractional = Boolean(
+ stageAspectRatio && canvasWidth && canvasHeight && overlayCoordWidth && overlayCoordHeight
+ )
+ const diffLayerClass = diffLayerIsFractional ? 'absolute top-0 left-0' : 'absolute top-0 left-0 w-full h-full'
+
const [internalMode, setInternalMode] = useState<ComparisonMode>('sideBySide')
const requestedMode = controlledMode ?? internalMode
const mode: ComparisonMode = effectiveMode(requestedMode, supportsComparison, hasDiffImage)
@@ -473,6 +554,7 @@ export function VisualImageDiffViewer({
label="Diff"
emptyTitle="No diff image available"
overlayBoxes={overlayBoxesIfShown}
+ overlayBands={diffOverlayBands}
overlayWidth={overlayCoordWidth}
overlayHeight={overlayCoordHeight}
highlightedOverlayIndex={highlightedOverlayIndex}
@@ -487,8 +569,6 @@ export function VisualImageDiffViewer({
// judge against, and bboxes were computed against current.
// Skip when the bbox coord space doesn't match the rendered
// image (size-mismatch case).
- const overlaySafeOnAfter =
- !!overlayBoxesIfShown && overlayCoordWidth === imageWidth && overlayCoordHeight === imageHeight
return (
<div className="flex flex-col gap-3 p-3 lg:flex-row lg:justify-center lg:items-start">
<ImagePanel
@@ -512,7 +592,8 @@ export function VisualImageDiffViewer({
onClick={
currentUrl ? () => setZoomedImage({ url: currentUrl, label: 'After snapshot' }) : undefined
}
- overlayBoxes={overlaySafeOnAfter ? overlayBoxesIfShown : undefined}
+ overlayBoxes={overlayCoordsMatch ? overlayBoxesIfShown : undefined}
+ overlayBands={overlayCoordsMatch ? diffOverlayBands : undefined}
overlayWidth={overlayCoordWidth}
overlayHeight={overlayCoordHeight}
highlightedOverlayIndex={highlightedOverlayIndex}
@@ -611,9 +692,12 @@ export function VisualImageDiffViewer({
<img
src={diffUrl as string}
alt="Diff overlay"
- className="absolute top-0 left-0 w-full h-full mix-blend-screen pointer-events-none"
+ className={cn(diffLayerClass, 'mix-blend-screen pointer-events-none')}
// eslint-disable-next-line react/forbid-dom-props
- style={{ opacity: diffOverlayOpacity / 100 }}
+ style={{
+ ...layerStyle(overlayCoordWidth, overlayCoordHeight),
+ opacity: diffOverlayOpacity / 100,
+ }}
/>
)}
@@ -625,19 +709,24 @@ export function VisualImageDiffViewer({
* in padded coords that don't align with either
* baseline or current). */}
{(mode === 'blend' || mode === 'split') &&
- !!overlayBoxesIfShown &&
- overlayBoxesIfShown.length > 0 &&
+ hasOverlayContent &&
!!overlayCoordWidth &&
!!overlayCoordHeight &&
- overlayCoordWidth === imageWidth &&
- overlayCoordHeight === imageHeight && (
- <BboxOverlay
- boxes={overlayBoxesIfShown}
- width={overlayCoordWidth}
- height={overlayCoordHeight}
- highlightedIndex={highlightedOverlayIndex ?? null}
- onHover={onOverlayHover}
- />
+ overlayCoordsMatch && (
+ <div
+ className={cn(diffLayerClass, 'pointer-events-none')}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={layerStyle(overlayCoordWidth, overlayCoordHeight)}
+ >
+ <BboxOverlay
+ boxes={overlayBoxesIfShown ?? []}
+ bands={diffOverlayBands}
+ width={overlayCoordWidth}
+ height={overlayCoordHeight}
+ highlightedIndex={highlightedOverlayIndex ?? null}
+ onHover={onOverlayHover}
+ />
+ </div>
)}
{/* Split drag handle — inside image area */}
@@ -690,19 +779,24 @@ export function VisualImageDiffViewer({
* After side still syncs with the sidebar
* panel (without it the After-side bboxes were
* silently non-interactive). */}
- {!!overlayBoxesIfShown &&
- overlayBoxesIfShown.length > 0 &&
+ {hasOverlayContent &&
!!overlayCoordWidth &&
!!overlayCoordHeight &&
- overlayCoordWidth === imageWidth &&
- overlayCoordHeight === imageHeight && (
- <BboxOverlay
- boxes={overlayBoxesIfShown}
- width={overlayCoordWidth}
- height={overlayCoordHeight}
- highlightedIndex={highlightedOverlayIndex ?? null}
- onHover={onOverlayHover}
- />
+ overlayCoordsMatch && (
+ <div
+ className={cn(diffLayerClass, 'pointer-events-none')}
+ // eslint-disable-next-line react/forbid-dom-props
+ style={layerStyle(overlayCoordWidth, overlayCoordHeight)}
+ >
+ <BboxOverlay
+ boxes={overlayBoxesIfShown ?? []}
+ bands={diffOverlayBands}
+ width={overlayCoordWidth}
+ height={overlayCoordHeight}
+ highlightedIndex={highlightedOverlayIndex ?? null}
+ onHover={onOverlayHover}
+ />
+ </div>
)}
</div>
</div>
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index a0a603b44c89..2b67be8364ce 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -588,6 +588,8 @@ SPECTACULAR_SETTINGS = {
# The published name is already derived by a different choice set, so the
# entry holds this one apart.
"SlackSummaryCadenceEnum": ["daily", "weekly", "monthly"],
+ # visual_review facade enums are framework-free StrEnums, so no Choices class derives a name.
+ "ShiftBandKindEnum": ["inserted", "deleted"],
"ExperimentStatusEnum": ["draft", "running", "paused", "exposure_frozen", "stopped"],
"ErrorTrackingIssueStatusEnum": ["archived", "active", "resolved", "pending_release", "suppressed", "all"],
"TaskArtifactStatusEnum": ["active", "failed"],
diff --git a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
index ae59d5834cd7..ef59f985bed3 100644
--- a/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
+++ b/posthog/test/repo_invariants/dataclass_frozen_baseline.txt
@@ -218,7 +218,6 @@
1 products/tasks/backend/temporal/slack_relay/activities.py
1 products/tasks/backend/temporal/task_management/activities/ensure_execute_sandbox_started.py
1 products/tasks/backend/tests/agent_log_fixtures.py
-1 products/visual_review/backend/diff.py
1 products/warehouse_sources/backend/models/ssh_tunnel.py
1 products/warehouse_sources/backend/temporal/data_imports/cdc/workflows.py
1 products/warehouse_sources/backend/temporal/data_imports/pipelines/core/delta/memory_governor.py
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index ac62c9479aa6..c1e7578204ec 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -50,7 +50,7 @@ Backend completes the run
- tolerated hash cache: skip diffing for known sub-threshold pairs
- detect removals: baseline identifiers missing from RunSnapshot rows
- verify uploads, create artifact records, link to snapshots
- - two-tier diff (Celery): pixel diff → SSIM for tall-page dilution
+ - diff (Celery): row alignment absorbs small vertical shifts, then pixel diff → SSIM for tall-page dilution
- post GitHub Check (pass/fail)
│
▼
@@ -128,10 +128,16 @@ Add `--tolerate-drift` to report the drift and still exit 0. Use it on the defau
Working end to end: CI upload → async diff → GitHub Check → web review → approve → baseline commit → clean re-run. Multi-repo per team, snapshot change history across runs, run supersession, GitHub commit status checks on transitions.
-**Tolerated hashes** — when the two-tier diff classifies a snapshot as below-threshold noise, it caches the `(identifier, baseline_hash, alternate_hash)` tuple.
+**Tolerated hashes** — when the diff classifies a snapshot as below-threshold noise, it caches the `(identifier, baseline_hash, alternate_hash)` tuple.
Future runs skip diffing entirely for cached pairs.
Developers can also manually tolerate a snapshot from the UI.
+**Row alignment** — a panel that grows by a pixel moves everything below it down, which a top-aligned pixel diff reads as a page-wide change.
+Before thresholding, the diff pairs the rows that exist in both images, so the classifier sees only what actually changed.
+A shift of one or two rows with nothing else changed is absorbed as noise, and the snapshot keeps the shift in `diff_metadata.row_shift` plus a diff image that shows the moved row, so the run leaves a trace instead of disappearing.
+A taller shift is `change_kind=layout`, which still needs review.
+The cap is measured against the committed baseline on every run, so absorbed shifts cannot accumulate into a page that quietly moved.
+
**Quarantine** — known-flaky identifiers can be quarantined per repo and run type.
Quarantined snapshots are still captured and diffed but excluded from gating.
A quarantined snapshot is not committed to the baseline, with one exception: a quarantined `new` snapshot that a person approved by identifier.
diff --git a/products/visual_review/backend/diff.py b/products/visual_review/backend/diff.py
index 9ce12a347d36..b2055ff5e0a9 100644
--- a/products/visual_review/backend/diff.py
+++ b/products/visual_review/backend/diff.py
@@ -6,12 +6,17 @@ diff_count, ssim, diff_image, thumbnail, and clusters without paying for
re-decode.
"""
-from dataclasses import dataclass
+import io
+from typing import Any
from blake3 import blake3
-from pixelhog import Comparison
+from PIL import Image
+from pixelhog import ClustersResult, Comparison, RowAlignment
-from .diff_metadata import ClusterSummary, DiffCluster
+from posthog.dataclasses import frozen
+
+from .diff_metadata import ClusterSummary, DiffCluster, RowShift, ShiftBand
+from .facade.contracts import SHIFT_ABSORB_MAX_ROWS
# Aligned-bbox merge tunables passed through to pixelhog's clusters().
# Catches the "list shifted vertically" pattern where every row of a
@@ -41,20 +46,113 @@ CLUSTER_MIN_SIDE = 4
CLUSTER_DILATION = 8
CLUSTER_MAX = 20
+# Row alignment costs up to rows x edit budget, and the upload pixel cap alone
+# still admits a one pixel wide image with tens of millions of rows. Real pages
+# top out well under this, so past it the pair keeps the naive diff.
+ALIGN_MAX_ROWS = 32_768
+# The relocation check decodes each image a second time, one after the other,
+# and only for a shift within the absorb cap. Past this many pixels that is
+# too much memory next to pixelhog's own buffers, so the check is skipped and
+# a shift with both inserts and deletes is treated as moved content, which
+# sends it to a reviewer instead of absorbing it.
+RELOCATION_CHECK_MAX_PIXELS = 16_000_000
+
-@dataclass
+@frozen
class CompareResult:
diff_image: bytes | None
diff_hash: str
diff_percentage: float # 0.0 to 100.0 — fraction of pixels that differ
diff_pixel_count: int
- ssim_score: float # 0.0 to 1.0 — 1.0 = identical, lower = more different
+ # 0.0 to 1.0 — 1.0 = identical, lower = more different. Measured over the
+ # matched rows when the pair aligned, so it is the effective score the
+ # classifier reads either way.
+ ssim_score: float
+ # Dimensions of `diff_image`, which is the padded size for a naive diff and
+ # the current image's own size for an aligned one. The percentages above
+ # are always measured over the padded size.
width: int
height: int
thumbnail: bytes | None
thumbnail_hash: str
size_mismatch: bool # baseline and current have different dimensions
cluster_summary: ClusterSummary | None # None when not computed (size mismatch / no thumbnail-only mode)
+ # What still differs once row alignment paired the rows that exist in
+ # both images: the residual plus the rows the shift added or removed, so
+ # a band of new rows is a change the size of its own area. Falls back to
+ # the naive numbers above when `row_shift` is None, so a caller that
+ # always stores these keeps the unaligned behavior for free.
+ aligned_diff_pixel_count: int
+ aligned_diff_percentage: float
+ # None when there was nothing to align, or when pixelhog could not align
+ # the pair because the two images differ by more than its budget.
+ row_shift: RowShift | None
+
+
+def _relocated_rows(baseline_bytes: bytes, current_bytes: bytes, alignment: RowAlignment, total_pixels: int) -> int:
+ """Inserted rows whose pixels equal a deleted row's: content that moved, not padding that appeared.
+
+ An element that moved stood out somewhere in the interior: the band
+ differs from the rows above and below it, in the current image where it
+ landed or in the baseline where it left. Padding that grew blends into a
+ neighbor, and padding that a page shift exposed at one edge while it
+ cropped the other has no interior side, so neither counts. The images
+ are decoded again for this, one at a time, and only for a shift small
+ enough that the answer can still absorb it.
+ """
+ deleted = [seg for seg in alignment.segments if seg.kind == "delete"]
+ inserted = [seg for seg in alignment.segments if seg.kind == "insert"]
+ if not deleted or not inserted:
+ return 0
+ if max(alignment.inserted_rows, alignment.deleted_rows) > SHIFT_ABSORB_MAX_ROWS:
+ return 0
+ if total_pixels > RELOCATION_CHECK_MAX_PIXELS:
+ return sum(seg.len for seg in inserted)
+
+ def row(image: Image.Image, y: int) -> bytes:
+ return image.crop((0, y, image.width, y + 1)).tobytes()
+
+ def stands_out(image: Image.Image, start: int, end: int, band: list[bytes]) -> bool:
+ if start == 0 or end >= image.height:
+ return False
+ return row(image, start - 1) != band[0] and row(image, end) != band[-1]
+
+ baseline = Image.open(io.BytesIO(baseline_bytes)).convert("RGBA")
+ # Row pixels -> whether that deleted band stood out where it was.
+ deleted_rows: dict[bytes, bool] = {}
+ for seg in deleted:
+ start, end = seg.baseline_start, seg.baseline_start + seg.len
+ band = [row(baseline, y) for y in range(start, end)]
+ stood_out = stands_out(baseline, start, end, band)
+ for pixels in band:
+ deleted_rows[pixels] = deleted_rows.get(pixels, False) or stood_out
+ del baseline
+
+ current = Image.open(io.BytesIO(current_bytes)).convert("RGBA")
+ relocated = 0
+ for seg in inserted:
+ start, end = seg.current_start, seg.current_start + seg.len
+ band = [row(current, y) for y in range(start, end)]
+ if any(pixels not in deleted_rows for pixels in band):
+ continue
+ if stands_out(current, start, end, band) or any(deleted_rows[pixels] for pixels in band):
+ relocated += seg.len
+ return relocated
+
+
+def _to_cluster_summary(clusters_result: ClustersResult) -> ClusterSummary:
+ return ClusterSummary(
+ items=[
+ DiffCluster(
+ bbox=(c.bbox.x, c.bbox.y, c.bbox.width, c.bbox.height),
+ px=c.pixel_count,
+ centroid=c.centroid,
+ )
+ for c in clusters_result.clusters
+ ],
+ total=clusters_result.total_clusters,
+ truncated=clusters_result.truncated,
+ )
def compare_images(
@@ -71,12 +169,16 @@ def compare_images(
every metric against the padded buffers — including clusters. The
padded region surfaces as a cluster of its own, which is the right
answer ("here's the new content area") rather than something to hide.
+
+ Row alignment runs on top of that. When it succeeds, the diff image, the
+ clusters and the SSIM describe the residual instead of the whole page
+ below a shift, and the shift itself is reported separately as a row
+ count. The naive pixel numbers stay on the result so a caller can still
+ see what the shift would have cost without alignment.
"""
cmp = Comparison(baseline_bytes, current_bytes)
diff_pixel_count = cmp.diff_count(threshold=threshold)
- ssim_score = cmp.ssim()
- diff_image = cmp.diff_image(threshold=threshold, alpha=0.1)
thumbnail = cmp.current_thumbnail(width=THUMB_WIDTH, height=THUMB_HEIGHT) if with_thumbnail else None
width = cmp.width
@@ -84,32 +186,74 @@ def compare_images(
total_pixels = width * height
diff_percentage = (diff_pixel_count / total_pixels * 100) if total_pixels > 0 else 0.0
+ # Nothing to align when no pixel differs, which is also true of a pair
+ # that only differs in how its PNG was encoded.
+ alignment: RowAlignment | None = None
+ if 0 < diff_pixel_count and height <= ALIGN_MAX_ROWS:
+ alignment = cmp.row_alignment(threshold=threshold)
+ aligned = alignment is not None and alignment.aligned
+
+ row_shift: RowShift | None = None
+ aligned_diff_pixel_count = diff_pixel_count
+ aligned_diff_percentage = diff_percentage
+ # Dimensions of the diff image the result carries, which is what the diff
+ # artifact row records and what the frontend scales its overlays by.
+ diff_width, diff_height = width, height
+ if alignment is not None and aligned:
+ # The rows a shift added or removed have no counterpart, so the residual
+ # does not see them. They still are a change the size of their area:
+ # two rows on a tall page is nothing, two rows on a small component is
+ # a bar across it. A same-height move shows as both an insert and a
+ # delete of the same rows, so the larger side is the area, not the sum.
+ band_pixel_count = max(alignment.inserted_rows, alignment.deleted_rows) * width
+ aligned_diff_pixel_count = alignment.residual_count + band_pixel_count
+ aligned_diff_percentage = (aligned_diff_pixel_count / total_pixels * 100) if total_pixels > 0 else 0.0
+ residual_percentage = (alignment.residual_count / total_pixels * 100) if total_pixels > 0 else 0.0
+ ssim_score = cmp.aligned_ssim(alignment)
+ row_shift = RowShift(
+ inserted_rows=alignment.inserted_rows,
+ deleted_rows=alignment.deleted_rows,
+ changed_rows=alignment.changed_rows,
+ residual_pixel_count=alignment.residual_count,
+ relocated_rows=_relocated_rows(baseline_bytes, current_bytes, alignment, total_pixels),
+ residual_percentage=round(residual_percentage, 4),
+ raw_diff_percentage=round(diff_percentage, 4),
+ bands=[ShiftBand(y=b.y, rows=b.rows, kind=b.kind) for b in alignment.bands],
+ )
+ diff_image = cmp.aligned_diff_image(alignment, threshold=threshold, alpha=0.1)
+ # The aligned diff image is drawn in current-image coordinates, so when
+ # the baseline was the taller of the two it is shorter than the padded
+ # buffers every metric above was measured against. The percentages stay
+ # over the padded total; only the image dimensions follow the image.
+ diff_width, diff_height = cmp.current_size
+ else:
+ ssim_score = cmp.ssim()
+ diff_image = cmp.diff_image(threshold=threshold, alpha=0.1)
+
diff_hash = blake3(diff_image).hexdigest() if diff_image else ""
thumbnail_hash = blake3(thumbnail).hexdigest() if thumbnail else ""
+ # Typed loosely on purpose: the tunables are int and float together, so a
+ # narrower value type makes the ** expansion fail against pixelhog's
+ # per-parameter types.
+ cluster_kwargs: dict[str, Any] = {
+ "threshold": threshold,
+ "min_pixels": CLUSTER_MIN_PIXELS,
+ "min_side": CLUSTER_MIN_SIDE,
+ "dilation": CLUSTER_DILATION,
+ "max_clusters": CLUSTER_MAX,
+ "merge_gap": CLUSTER_MERGE_GAP_PX,
+ "merge_overlap": CLUSTER_MERGE_OVERLAP_RATIO,
+ }
cluster_summary: ClusterSummary | None = None
- if with_clusters and diff_pixel_count > 0:
- clusters_result = cmp.clusters(
- threshold=threshold,
- min_pixels=CLUSTER_MIN_PIXELS,
- min_side=CLUSTER_MIN_SIDE,
- dilation=CLUSTER_DILATION,
- max_clusters=CLUSTER_MAX,
- merge_gap=CLUSTER_MERGE_GAP_PX,
- merge_overlap=CLUSTER_MERGE_OVERLAP_RATIO,
- )
- cluster_summary = ClusterSummary(
- items=[
- DiffCluster(
- bbox=(c.bbox.x, c.bbox.y, c.bbox.width, c.bbox.height),
- px=c.pixel_count,
- centroid=c.centroid,
- )
- for c in clusters_result.clusters
- ],
- total=clusters_result.total_clusters,
- truncated=clusters_result.truncated,
+ has_pixels_to_cluster = aligned_diff_pixel_count > 0 if aligned else diff_pixel_count > 0
+ if with_clusters and has_pixels_to_cluster:
+ clusters_result = (
+ cmp.aligned_clusters(alignment, **cluster_kwargs)
+ if alignment is not None and aligned
+ else cmp.clusters(**cluster_kwargs)
)
+ cluster_summary = _to_cluster_summary(clusters_result)
return CompareResult(
diff_image=diff_image,
@@ -117,10 +261,13 @@ def compare_images(
diff_percentage=round(diff_percentage, 4),
diff_pixel_count=diff_pixel_count,
ssim_score=ssim_score,
- width=width,
- height=height,
+ width=diff_width,
+ height=diff_height,
thumbnail=thumbnail,
thumbnail_hash=thumbnail_hash,
size_mismatch=cmp.size_mismatch,
cluster_summary=cluster_summary,
+ aligned_diff_pixel_count=aligned_diff_pixel_count,
+ aligned_diff_percentage=round(aligned_diff_percentage, 4),
+ row_shift=row_shift,
)
diff --git a/products/visual_review/backend/diff_metadata.py b/products/visual_review/backend/diff_metadata.py
index 3ae77af20e1f..5fbdee70f4fb 100644
--- a/products/visual_review/backend/diff_metadata.py
+++ b/products/visual_review/backend/diff_metadata.py
@@ -13,6 +13,8 @@ API contracts) because this is internal storage shape, not a public DTO.
from __future__ import annotations
+from typing import Literal
+
from pydantic import BaseModel, ConfigDict, Field
@@ -43,6 +45,56 @@ class ClusterSummary(BaseModel):
truncated: bool
+class ShiftBand(BaseModel):
+ """One run of rows the current image gained or lost.
+
+ A deleted band has no rows of its own in the current image; `y` is the
+ seam the removed rows left behind and `rows` counts what went away.
+ """
+
+ model_config = ConfigDict(frozen=True)
+
+ y: int = Field(ge=0, description="First row of the band, in current-image coordinates")
+ rows: int = Field(ge=0, description="How many rows the band covers")
+ kind: Literal["inserted", "deleted"]
+
+
+class RowShift(BaseModel):
+ """A vertical shift between baseline and current, separated from the real change.
+
+ Row alignment pairs the rows that exist in both images, so the pixels
+ below an inserted row stop counting as differences. `residual_*` is what
+ is left after that pairing, which is the number the classifier thresholds
+ on. `raw_diff_percentage` keeps what the same pair measured without
+ alignment, so the UI can say what the shift would have cost.
+ """
+
+ model_config = ConfigDict(frozen=True)
+
+ inserted_rows: int = Field(ge=0)
+ deleted_rows: int = Field(ge=0)
+ changed_rows: int = Field(ge=0)
+ residual_pixel_count: int = Field(ge=0)
+ # Inserted rows whose pixels equal a deleted row's: content that moved
+ # somewhere else on the page, not padding that appeared. Every inserted
+ # row when the image was too big to check. Zero on rows written before
+ # this field existed.
+ relocated_rows: int = Field(ge=0, default=0)
+ residual_percentage: float
+ raw_diff_percentage: float
+ bands: list[ShiftBand]
+
+ @property
+ def shifted_rows(self) -> int:
+ """How far the rows moved. What the absorb cap judges.
+
+ A page that grew has only inserts and one that shrank has only deletes.
+ A same-height translation shows up as both, so the larger side is the
+ movement, not the sum.
+ """
+ return max(self.inserted_rows, self.deleted_rows)
+
+
class DiffMetadata(BaseModel):
"""Container for everything the diff pipeline writes into the
`diff_metadata` JSONB column.
@@ -56,3 +108,7 @@ class DiffMetadata(BaseModel):
cluster_summary: ClusterSummary | None = None
size_mismatch: bool = False # baseline and current had different dimensions; pixelhog padded to largest
+ # Present whenever row alignment succeeded, including on snapshots the
+ # classifier absorbed as noise. An absorbed row keeps its shift here so
+ # the UI can show what moved instead of showing nothing.
+ row_shift: RowShift | None = None
diff --git a/products/visual_review/backend/diffing.py b/products/visual_review/backend/diffing.py
index 862c7ef03bb4..8664703ff21d 100644
--- a/products/visual_review/backend/diffing.py
+++ b/products/visual_review/backend/diffing.py
@@ -18,9 +18,9 @@ from pixelhog import thumbnail as pixelhog_thumbnail
from .db import WRITER_DB
from .diff import THUMB_HEIGHT, THUMB_WIDTH, CompareResult, compare_images
from .diff_metadata import DiffMetadata
-from .facade.contracts import PIXEL_DIFF_THRESHOLD_PERCENT, SSIM_DISSIMILARITY_THRESHOLD
+from .facade.contracts import PIXEL_DIFF_THRESHOLD_PERCENT, SHIFT_ABSORB_MAX_ROWS, SSIM_DISSIMILARITY_THRESHOLD
from .facade.enums import ChangeKind, ClassificationReason, SnapshotResult, ToleratedReason
-from .models import RunSnapshot, ToleratedHash
+from .models import Artifact, RunSnapshot, ToleratedHash
logger = structlog.get_logger(__name__)
@@ -33,11 +33,34 @@ def classify_compare_result(result: CompareResult) -> ChangeKind | None:
drives `_diff_snapshot` below; keeping it here means the production
branch and the tests can't drift.
+ When the pair aligned, the pixel tier reads the residual first and the
+ area of the rows the shift added or removed after the cap, and
+ `ssim_score` is already measured over the matched rows, so a page that
+ only moved down is judged on what changed rather than on everything the
+ shift dragged along. A shift taller than the absorb cap is its own kind, because moving
+ a block is a change a reviewer can act on even when the content in it is
+ identical. So is a thin element that moved somewhere else on the page:
+ its rows show up as an insert whose pixels equal a delete's, which the
+ counts alone would read as a tiny shift.
+
Size mismatch is *not* a kind — pixelhog pads to the largest dims and
we still get a real pixel/SSIM answer over that padded image. The fact
that sizes differed is recorded separately on `DiffMetadata`.
"""
- if result.diff_percentage >= PIXEL_DIFF_THRESHOLD_PERCENT:
+ shift = result.row_shift
+ residual_percentage = shift.residual_percentage if shift else result.diff_percentage
+ shifted_rows = shift.shifted_rows if shift else 0
+
+ # Content that changed inside the matched rows is a pixel change no matter
+ # what moved. A move past the cap is a layout change even when its band
+ # alone covers a lot of the page, which is why the band's area is judged
+ # only after that: it decides whether a small move on a small component
+ # is a bar across it or noise.
+ if residual_percentage >= PIXEL_DIFF_THRESHOLD_PERCENT:
+ return ChangeKind.PIXEL
+ if shifted_rows > SHIFT_ABSORB_MAX_ROWS or (shift is not None and shift.relocated_rows > 0):
+ return ChangeKind.LAYOUT
+ if result.aligned_diff_percentage >= PIXEL_DIFF_THRESHOLD_PERCENT:
return ChangeKind.PIXEL
if (1.0 - result.ssim_score) >= SSIM_DISSIMILARITY_THRESHOLD:
return ChangeKind.STRUCTURAL
@@ -67,18 +90,12 @@ def _store_thumbnail(snapshot: RunSnapshot, result: CompareResult) -> None:
artifact.save(update_fields=["thumbnail"])
-def _store_diff(
- snapshot: RunSnapshot,
- result: CompareResult,
- change_kind: ChangeKind,
-) -> None:
- """Upload diff artifact and update snapshot metrics + classification."""
- from .logic import artifact_store, snapshot_diffs
-
- if not result.diff_image:
- return
+def _write_diff_artifact(snapshot: RunSnapshot, result: CompareResult) -> Artifact:
+ """Upload the diff image and return the artifact row pointing at it."""
+ from .logic import artifact_store
- diff_artifact = artifact_store.write_artifact_bytes(
+ assert result.diff_image is not None
+ return artifact_store.write_artifact_bytes(
repo_id=snapshot.run.repo_id,
content_hash=result.diff_hash,
content=result.diff_image,
@@ -87,19 +104,37 @@ def _store_diff(
team_id=snapshot.team_id,
)
- diff_metadata = DiffMetadata(
+
+def _diff_metadata(result: CompareResult) -> DiffMetadata:
+ """The metadata block both storage paths write."""
+ return DiffMetadata(
cluster_summary=result.cluster_summary,
size_mismatch=result.size_mismatch,
+ row_shift=result.row_shift,
)
+
+def _store_diff(
+ snapshot: RunSnapshot,
+ result: CompareResult,
+ change_kind: ChangeKind,
+) -> None:
+ """Upload diff artifact and update snapshot metrics + classification."""
+ from .logic import snapshot_diffs
+
+ if not result.diff_image:
+ return
+
+ # The aligned metrics equal the naive ones when the pair could not be
+ # aligned, so this stores the honest cost of the change either way.
snapshot_diffs.update_snapshot_diff(
snapshot_id=snapshot.id,
- diff_artifact=diff_artifact,
- diff_percentage=result.diff_percentage,
- diff_pixel_count=result.diff_pixel_count,
+ diff_artifact=_write_diff_artifact(snapshot, result),
+ diff_percentage=result.aligned_diff_percentage,
+ diff_pixel_count=result.aligned_diff_pixel_count,
ssim_score=result.ssim_score,
change_kind=change_kind,
- diff_metadata=diff_metadata,
+ diff_metadata=_diff_metadata(result),
team_id=snapshot.team_id,
)
@@ -108,11 +143,69 @@ def _store_diff(
snapshot_id=str(snapshot.id),
identifier=snapshot.identifier,
change_kind=change_kind.value,
- diff_percentage=result.diff_percentage,
- diff_pixel_count=result.diff_pixel_count,
+ diff_percentage=result.aligned_diff_percentage,
+ diff_pixel_count=result.aligned_diff_pixel_count,
ssim_score=result.ssim_score,
size_mismatch=result.size_mismatch,
cluster_count=result.cluster_summary.total if result.cluster_summary else 0,
+ inserted_rows=result.row_shift.inserted_rows if result.row_shift else 0,
+ deleted_rows=result.row_shift.deleted_rows if result.row_shift else 0,
+ )
+
+
+def _store_absorbed(snapshot: RunSnapshot, result: CompareResult) -> None:
+ """Reclassify a below-threshold snapshot as noise and record what it cost.
+
+ The aligned metrics equal the naive ones when nothing aligned, so an
+ absorbed shift is recorded at what it really cost (a residual of a
+ fraction of a percent) instead of at the whole page below the shift.
+ `FlakinessEntry.headroom` is measured against these numbers.
+
+ A shift that actually moved rows also keeps its diff image and its
+ metadata, so a reviewer can see the line that moved. A pair that aligned
+ with nothing moved is plain noise and gets neither, because that would be
+ an artifact upload per snapshot for a picture of nothing.
+ """
+ from .logic import snapshot_diffs
+
+ shift = result.row_shift
+ has_shift = shift is not None and shift.shifted_rows > 0
+
+ # The diff image is a courtesy for the reviewer, not the decision. The task
+ # runs the diff pass once, so a lost upload must not leave a noise row
+ # sitting CHANGED with no kind and fail the gate for it.
+ diff_artifact: Artifact | None = None
+ if has_shift and result.diff_image:
+ try:
+ diff_artifact = _write_diff_artifact(snapshot, result)
+ except Exception as e:
+ logger.warning(
+ "visual_review.absorbed_diff_upload_failed",
+ snapshot_id=str(snapshot.id),
+ identifier=snapshot.identifier,
+ error=str(e),
+ )
+ snapshot_diffs.update_snapshot_diff(
+ snapshot_id=snapshot.id,
+ diff_artifact=diff_artifact,
+ diff_percentage=result.aligned_diff_percentage,
+ diff_pixel_count=result.aligned_diff_pixel_count,
+ ssim_score=result.ssim_score,
+ change_kind=None,
+ diff_metadata=_diff_metadata(result) if has_shift else None,
+ absorbed=True,
+ team_id=snapshot.team_id,
+ )
+
+ logger.info(
+ "visual_review.diff_below_threshold",
+ snapshot_id=str(snapshot.id),
+ identifier=snapshot.identifier,
+ diff_percentage=result.aligned_diff_percentage,
+ ssim_score=result.ssim_score,
+ inserted_rows=shift.inserted_rows if shift else 0,
+ deleted_rows=shift.deleted_rows if shift else 0,
+ residual_percentage=shift.residual_percentage if shift else None,
)
@@ -121,9 +214,14 @@ def _diff_snapshot(snapshot: RunSnapshot) -> bool:
Classification (in priority order):
1. Pixel diff above threshold -> CHANGED, kind=pixel
- 2. SSIM dissimilarity above threshold -> CHANGED, kind=structural
+ 2. Rows inserted or deleted past the absorb cap -> CHANGED, kind=layout
+ 3. SSIM dissimilarity above threshold -> CHANGED, kind=structural
(tall-page dilution safety net)
- 3. Both below -> UNCHANGED (noise), auto-populate tolerance cache.
+ 4. All below -> UNCHANGED (noise), auto-populate tolerance cache.
+
+ When the pair aligned, the thresholds run on the residual and on the SSIM
+ of the matched rows, so a page that moved down by a row or two is absorbed
+ instead of reading as a page-wide change.
Size mismatch is recorded as `diff_metadata.size_mismatch` and surfaced
separately in the UI — a snapshot can have a different viewport AND a
@@ -160,22 +258,7 @@ def _diff_snapshot(snapshot: RunSnapshot) -> bool:
_store_diff(snapshot, result, kind)
return True
- # Both tiers below threshold — genuine noise, reclassify and cache for future runs
- snapshot.result = SnapshotResult.UNCHANGED
- snapshot.classification_reason = ClassificationReason.BELOW_THRESHOLD
- snapshot.diff_percentage = result.diff_percentage
- snapshot.diff_pixel_count = result.diff_pixel_count
- snapshot.ssim_score = result.ssim_score
- snapshot.save(
- update_fields=["result", "classification_reason", "diff_percentage", "diff_pixel_count", "ssim_score"]
- )
- logger.info(
- "visual_review.diff_below_threshold",
- snapshot_id=str(snapshot.id),
- identifier=snapshot.identifier,
- diff_percentage=result.diff_percentage,
- ssim_score=result.ssim_score,
- )
+ _store_absorbed(snapshot, result)
# Auto-populate tolerance cache so future runs skip diffing for this hash.
# Explicit team_id in the lookup (not just defaults) so the IDOR audit
@@ -190,7 +273,7 @@ def _diff_snapshot(snapshot: RunSnapshot) -> bool:
defaults={
"reason": ToleratedReason.AUTO_THRESHOLD,
"source_run": snapshot.run,
- "diff_percentage": result.diff_percentage,
+ "diff_percentage": result.aligned_diff_percentage,
},
)
return True
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 158a2dd7d507..ea4f90cf6859 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -21,10 +21,14 @@ from uuid import UUID
from django.contrib.auth import get_user_model
+from posthog.dataclasses import frozen
from posthog.egress.github.transport import GitHubRateLimitError
from posthog.helpers.trigram_search import search_match_type_from_instance
-from ..diff_metadata import DiffMetadata
+from ..diff_metadata import (
+ DiffMetadata,
+ RowShift as StoredRowShift,
+)
from ..logic import (
approvals,
artifact_store,
@@ -42,7 +46,7 @@ from ..logic import (
toleration,
)
from . import contracts
-from .enums import ActorType, RunPurpose
+from .enums import ActorType, RunPurpose, ShiftBandKind
User = get_user_model()
@@ -109,17 +113,38 @@ def _to_artifact(artifact, repo_id: UUID) -> contracts.Artifact:
)
-def _parse_diff_metadata(
- diff_metadata_raw: dict | None,
-) -> tuple[contracts.ClusterSummary | None, bool]:
- """Translate the compact storage shape into the verbose wire shape.
+def _to_row_shift(parsed: StoredRowShift | None) -> contracts.RowShift | None:
+ """Translate the stored row shift into the wire shape.
- Returns `(cluster_summary, size_mismatch)`. The cluster_summary side
- is None for legacy rows and identical-pair rows; size_mismatch
- defaults to False everywhere it isn't explicitly recorded.
+ Takes the already validated model rather than the raw column, so a caller
+ that has parsed `DiffMetadata` does not pay for a second validation. The
+ contract carries fewer fields than storage does: the pixel counts behind
+ the residual are diagnostics, not something the UI renders.
"""
+ if parsed is None:
+ return None
+ return contracts.RowShift(
+ inserted_rows=parsed.inserted_rows,
+ deleted_rows=parsed.deleted_rows,
+ residual_percentage=parsed.residual_percentage,
+ raw_diff_percentage=parsed.raw_diff_percentage,
+ bands=[contracts.ShiftBand(y=b.y, rows=b.rows, kind=ShiftBandKind(b.kind)) for b in parsed.bands],
+ )
+
+
+@frozen
+class _ParsedDiffMetadata:
+ # cluster_summary and row_shift are None for legacy rows and identical-pair
+ # rows; size_mismatch is False wherever it was not explicitly recorded.
+ cluster_summary: contracts.ClusterSummary | None = None
+ size_mismatch: bool = False
+ row_shift: contracts.RowShift | None = None
+
+
+def _parse_diff_metadata(diff_metadata_raw: dict | None) -> _ParsedDiffMetadata:
+ """Translate the compact storage shape into the verbose wire shape."""
if not diff_metadata_raw:
- return None, False
+ return _ParsedDiffMetadata()
parsed = DiffMetadata.model_validate(diff_metadata_raw)
cluster_summary: contracts.ClusterSummary | None = None
if parsed.cluster_summary is not None:
@@ -140,14 +165,18 @@ def _parse_diff_metadata(
total=cs.total,
truncated=cs.truncated,
)
- return cluster_summary, parsed.size_mismatch
+ return _ParsedDiffMetadata(
+ cluster_summary=cluster_summary,
+ size_mismatch=parsed.size_mismatch,
+ row_shift=_to_row_shift(parsed.row_shift),
+ )
def _to_snapshot(
snapshot, repo_id: UUID, user_basic_infos: dict[int, contracts.UserBasicInfo] | None = None
) -> contracts.Snapshot:
reviewed_by = (user_basic_infos or {}).get(snapshot.reviewed_by_id) if snapshot.reviewed_by_id else None
- cluster_summary, size_mismatch = _parse_diff_metadata(snapshot.diff_metadata)
+ diff_meta = _parse_diff_metadata(snapshot.diff_metadata)
return contracts.Snapshot(
id=snapshot.id,
run_id=snapshot.run_id,
@@ -168,8 +197,9 @@ def _to_snapshot(
metadata=snapshot.metadata or {},
ssim_score=snapshot.ssim_score,
change_kind=snapshot.change_kind or "",
- cluster_summary=cluster_summary,
- size_mismatch=size_mismatch,
+ cluster_summary=diff_meta.cluster_summary,
+ size_mismatch=diff_meta.size_mismatch,
+ row_shift=diff_meta.row_shift,
)
@@ -529,30 +559,33 @@ def get_run_snapshots(
return contracts.RunSnapshots(snapshots=dtos, quarantined_count=quarantined_count)
+def _to_history_entry(entry, repo_id: UUID) -> contracts.SnapshotHistoryEntry:
+ # Validate the stored column once and read both fields off it. The history
+ # contract has no `cluster_summary`, so the parse stops at the pydantic
+ # model rather than building the cluster dataclasses that would be thrown
+ # away. Defaults mirror `DiffMetadata`.
+ stored = DiffMetadata.model_validate(entry.diff_metadata or {})
+ return contracts.SnapshotHistoryEntry(
+ run_id=entry.run_id,
+ snapshot_id=entry.id,
+ result=entry.result,
+ branch=entry.run.branch,
+ commit_sha=entry.run.commit_sha,
+ created_at=entry.run.created_at,
+ pr_number=entry.run.pr_number,
+ diff_percentage=entry.diff_percentage,
+ review_state=entry.review_state,
+ current_artifact=_to_artifact(entry.current_artifact, repo_id) if entry.current_artifact else None,
+ ssim_score=entry.ssim_score,
+ change_kind=entry.change_kind or "",
+ size_mismatch=stored.size_mismatch,
+ row_shift=_to_row_shift(stored.row_shift),
+ )
+
+
def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[contracts.SnapshotHistoryEntry]:
entries = history.get_snapshot_history(repo_id, identifier, run_type)
- return [
- contracts.SnapshotHistoryEntry(
- run_id=e.run_id,
- snapshot_id=e.id,
- result=e.result,
- branch=e.run.branch,
- commit_sha=e.run.commit_sha,
- created_at=e.run.created_at,
- pr_number=e.run.pr_number,
- diff_percentage=e.diff_percentage,
- review_state=e.review_state,
- current_artifact=_to_artifact(e.current_artifact, repo_id) if e.current_artifact else None,
- ssim_score=e.ssim_score,
- change_kind=e.change_kind or "",
- # Read the flag directly instead of round-tripping through the
- # full Pydantic parse — `cluster_summary` isn't on the history
- # entry contract and we'd just be allocating cluster dataclasses
- # to throw away. The default mirrors `DiffMetadata.size_mismatch`.
- size_mismatch=bool((e.diff_metadata or {}).get("size_mismatch", False)),
- )
- for e in entries
- ]
+ return [_to_history_entry(entry, repo_id) for entry in entries]
def mark_snapshot_as_tolerated(
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index 1ca29765efdc..3b499782c889 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -20,7 +20,9 @@ from uuid import UUID
from pydantic.dataclasses import dataclass
-# Two-tier classification thresholds, applied by `diffing.classify_compare_result`:
+from .enums import ShiftBandKind
+
+# Classification thresholds, applied by `diffing.classify_compare_result`:
#
# 1. Pixel diff ratio — fast path for obvious changes. Snapshots above
# this are immediately classified as CHANGED.
@@ -29,6 +31,8 @@ from pydantic.dataclasses import dataclass
# a measurable structural shift that SSIM catches.
#
# Only when both are below threshold is the snapshot reclassified as UNCHANGED.
+# When the pair aligned, both are measured after alignment, so a vertical
+# shift is judged on what actually changed rather than on everything below it.
#
# They live here rather than next to the classifier because they are also what
# `FlakinessEntry.headroom` is measured against, so a consumer reading that
@@ -37,6 +41,17 @@ from pydantic.dataclasses import dataclass
PIXEL_DIFF_THRESHOLD_PERCENT = 2.5
SSIM_DISSIMILARITY_THRESHOLD = 0.01 # 1% structural difference
+# How many inserted or deleted rows the classifier absorbs as noise before it
+# calls the change a layout change.
+#
+# Every run measures its shift against the committed baseline, not against the
+# previous run, so an absorbed shift cannot accumulate into a page that has
+# quietly moved by twenty rows. Two rows is also the point where the change
+# stops being actionable: a reviewer cannot do anything about one or two pixels
+# of spacing, but a taller band is a block that appeared or disappeared and
+# somebody should look at it.
+SHIFT_ABSORB_MAX_ROWS = 2
+
# --- Input DTOs ---
@@ -205,6 +220,49 @@ class ClusterSummary:
truncated: bool
+@dataclass(frozen=True)
+class ShiftBand:
+ """One run of rows the current image gained or lost.
+
+ A deleted band has no rows of its own in the current image, so `y` is the
+ seam the removed rows left behind and `rows` counts what went away.
+ """
+
+ y: int
+ rows: int
+ kind: ShiftBandKind
+
+
+@dataclass(frozen=True)
+class RowShift:
+ """A vertical shift between baseline and current, separated from the real change.
+
+ Row alignment pairs the rows that exist in both images, so the pixels
+ below an inserted row stop counting as differences. `residual_percentage`
+ is what survives that pairing. The snapshot's `diff_percentage` adds the
+ area of the rows the shift added or removed, and that combined number is
+ what the pixel threshold judges. `raw_diff_percentage` is what the same
+ pair measured without alignment, which is how the UI can say what the
+ shift would otherwise have cost.
+ """
+
+ inserted_rows: int
+ deleted_rows: int
+ residual_percentage: float
+ raw_diff_percentage: float
+ bands: list[ShiftBand]
+
+ @property
+ def shifted_rows(self) -> int:
+ """How far the rows moved. What the absorb cap judges.
+
+ A page that grew has only inserts and one that shrank has only deletes.
+ A same-height translation shows up as both, so the larger side is the
+ movement, not the sum.
+ """
+ return max(self.inserted_rows, self.deleted_rows)
+
+
@dataclass(frozen=True)
class Snapshot:
"""A snapshot with its comparison results."""
@@ -239,6 +297,10 @@ class Snapshot:
change_kind: str = ""
cluster_summary: ClusterSummary | None = None
size_mismatch: bool = False
+ # The vertical shift the diff pipeline measured, if it could align the
+ # pair. Present on absorbed (UNCHANGED) snapshots as well, because a shift
+ # small enough to absorb is still the only trace of why the pixels moved.
+ row_shift: RowShift | None = None
@dataclass(frozen=True)
@@ -419,6 +481,9 @@ class SnapshotHistoryEntry:
ssim_score: float | None = None
change_kind: str = ""
size_mismatch: bool = False
+ # Same meaning as on `Snapshot`, and present on absorbed rows too, so the
+ # history view can show which runs only moved rather than changed.
+ row_shift: RowShift | None = None
@dataclass(frozen=True)
diff --git a/products/visual_review/backend/facade/enums.py b/products/visual_review/backend/facade/enums.py
index 82246d44d395..75dfb0f73480 100644
--- a/products/visual_review/backend/facade/enums.py
+++ b/products/visual_review/backend/facade/enums.py
@@ -72,10 +72,11 @@ class ClassificationReason(StrEnum):
class ChangeKind(StrEnum):
"""What kind of change a CHANGED snapshot represents.
- Set when a snapshot's `result` is CHANGED. The two-tier classifier
- distinguishes a pixel-level diff (lots of pixels differ) from a
- structural/perceptual change caught by SSIM (few pixels but a measurable
- perceptual difference). Empty for snapshots that haven't been diffed yet (legacy data).
+ Set when a snapshot's `result` is CHANGED. The classifier distinguishes a
+ pixel-level diff (lots of pixels differ) from a structural/perceptual
+ change caught by SSIM (few pixels but a measurable perceptual difference),
+ and from a layout change where rows moved. Empty for snapshots that
+ haven't been diffed yet (legacy data).
Size mismatch is *not* a kind here — a snapshot can have a different
viewport AND a content change. The flag lives in `diff_metadata`
@@ -84,6 +85,21 @@ class ChangeKind(StrEnum):
PIXEL = "pixel" # Pixel diff above threshold — a chunk of pixels visibly changed
STRUCTURAL = "structural" # SSIM caught a perceptual change; pixel diff was below threshold
+ # Rows were inserted or deleted past the absorb cap, so the page moved
+ # vertically. The content in the rows that exist in both images is within
+ # both thresholds; what changed is where things sit.
+ LAYOUT = "layout"
+
+
+class ShiftBandKind(StrEnum):
+ """Whether a shift band marks rows the current image gained or lost.
+
+ Named explicitly in ENUM_NAME_OVERRIDES (ShiftBandKindEnum) so the OpenAPI
+ component does not collide with the other `kind` fields across products.
+ """
+
+ INSERTED = "inserted"
+ DELETED = "deleted"
class FlakinessState(StrEnum):
diff --git a/products/visual_review/backend/logic/history.py b/products/visual_review/backend/logic/history.py
index 85b4e202290e..a88add9af30d 100644
--- a/products/visual_review/backend/logic/history.py
+++ b/products/visual_review/backend/logic/history.py
@@ -15,6 +15,13 @@ WITH ordered AS (
SELECT rs.id,
rs.baseline_artifact_id,
LAG(rs.baseline_artifact_id) OVER (ORDER BY r.created_at) AS prev_baseline_id,
+ (
+ rs.result = 'unchanged'
+ AND GREATEST(
+ COALESCE((rs.diff_metadata -> 'row_shift' ->> 'inserted_rows')::int, 0),
+ COALESCE((rs.diff_metadata -> 'row_shift' ->> 'deleted_rows')::int, 0)
+ ) > 0
+ ) AS absorbed_shift,
r.created_at
FROM visual_review_runsnapshot rs
JOIN visual_review_run r ON r.id = rs.run_id
@@ -23,10 +30,22 @@ WITH ordered AS (
AND r.branch = ANY(%s)
AND r.status = 'completed'
AND rs.identifier = %s
+),
+periods AS (
+ SELECT *,
+ SUM(CASE WHEN prev_baseline_id IS DISTINCT FROM baseline_artifact_id THEN 1 ELSE 0 END)
+ OVER (ORDER BY created_at) AS baseline_period
+ FROM ordered
+),
+ranked AS (
+ SELECT *,
+ ROW_NUMBER() OVER (PARTITION BY baseline_period, absorbed_shift ORDER BY created_at) AS nth_in_period
+ FROM periods
)
SELECT id
-FROM ordered
+FROM ranked
WHERE prev_baseline_id IS DISTINCT FROM baseline_artifact_id
+ OR (absorbed_shift AND nth_in_period = 1)
ORDER BY created_at DESC
"""
@@ -37,7 +56,13 @@ def get_snapshot_history(repo_id: UUID, identifier: str, run_type: str) -> list[
Returns one entry per *baseline transition* — every time the committed
`.snapshots.yml` baseline actually moved. LAG-on-`baseline_artifact_id`
(over ASC ordering) keeps the FIRST run of each baseline period, so the
- user sees the inception event plus every change since.
+ user sees the inception event plus every change since. An absorbed shift
+ is an entry too, even though the baseline stayed put, because absorbing
+ it leaves no baseline change behind and this is where its trace shows.
+ Only absorbed rows qualify (an actionable change recurs on every run
+ until its baseline moves), and only the first one in each baseline period,
+ so a shift master keeps absorbing, with or without jitter in the image,
+ does not become an entry per run.
Why LAG on `baseline_artifact_id` and not `current_artifact_id`:
- `current_artifact_id` is the bytes captured by THIS run. Pixel jitter
diff --git a/products/visual_review/backend/logic/snapshot_diffs.py b/products/visual_review/backend/logic/snapshot_diffs.py
index 3b7a94986d71..cc7f53d3202f 100644
--- a/products/visual_review/backend/logic/snapshot_diffs.py
+++ b/products/visual_review/backend/logic/snapshot_diffs.py
@@ -5,48 +5,65 @@ from __future__ import annotations
from uuid import UUID
from ..diff_metadata import DiffMetadata
-from ..facade.enums import ChangeKind, SnapshotResult
+from ..facade.enums import ChangeKind, ClassificationReason, SnapshotResult
from ..models import Artifact, RunSnapshot
def update_snapshot_diff(
snapshot_id: UUID,
- diff_artifact: Artifact,
diff_percentage: float,
diff_pixel_count: int,
ssim_score: float,
- change_kind: ChangeKind,
- diff_metadata: DiffMetadata,
+ change_kind: ChangeKind | None,
+ diff_artifact: Artifact | None = None,
+ diff_metadata: DiffMetadata | None = None,
+ absorbed: bool = False,
team_id: int | None = None,
) -> RunSnapshot:
+ """Attach computed diff metrics to a snapshot, in one row write.
+
+ Serves both outcomes of the diff pipeline. A CHANGED snapshot carries a
+ `change_kind`, its diff image and its metadata. A snapshot the classifier
+ absorbed is UNCHANGED with no kind, and passes an artifact and metadata
+ only when it has a row shift worth showing; `None` for either leaves that
+ column alone rather than clearing it.
+
+ `absorbed` flips the row to UNCHANGED / BELOW_THRESHOLD in the same save as
+ the metrics. The diff pipeline retries CHANGED rows with no kind and no
+ artifact, so the metrics and the terminal state must never land apart.
+ """
qs = RunSnapshot.objects.select_related("run")
if team_id is not None:
qs = qs.filter(team_id=team_id)
snapshot = qs.get(id=snapshot_id)
- if diff_artifact.repo_id != snapshot.run.repo_id:
- raise ValueError(
- f"Cross-repo artifact reference: artifact repo {diff_artifact.repo_id} "
- f"!= snapshot repo {snapshot.run.repo_id}"
- )
- if snapshot.result != SnapshotResult.CHANGED:
- raise ValueError(f"Cannot attach diff to snapshot with result={snapshot.result}, expected 'changed'")
- snapshot.diff_artifact = diff_artifact
+ if snapshot.result not in (SnapshotResult.CHANGED, SnapshotResult.UNCHANGED):
+ raise ValueError(f"Cannot attach diff to snapshot with result={snapshot.result}")
snapshot.diff_percentage = diff_percentage
snapshot.diff_pixel_count = diff_pixel_count
snapshot.ssim_score = ssim_score
- snapshot.change_kind = change_kind.value
- # The Pydantic dump is the only legal write path into this column; reads
- # go through DiffMetadata.model_validate. Storage is JSONB; the schema
- # lives in diff_metadata.py.
- snapshot.diff_metadata = diff_metadata.model_dump(mode="json")
- snapshot.save(
- update_fields=[
- "diff_artifact",
- "diff_percentage",
- "diff_pixel_count",
- "ssim_score",
- "change_kind",
- "diff_metadata",
- ]
- )
+ snapshot.change_kind = change_kind.value if change_kind else ""
+ update_fields = ["diff_percentage", "diff_pixel_count", "ssim_score", "change_kind"]
+
+ if diff_artifact is not None:
+ if diff_artifact.repo_id != snapshot.run.repo_id:
+ raise ValueError(
+ f"Cross-repo artifact reference: artifact repo {diff_artifact.repo_id} "
+ f"!= snapshot repo {snapshot.run.repo_id}"
+ )
+ snapshot.diff_artifact = diff_artifact
+ update_fields.append("diff_artifact")
+
+ if diff_metadata is not None:
+ # The Pydantic dump is the only legal write path into this column; reads
+ # go through DiffMetadata.model_validate. Storage is JSONB; the schema
+ # lives in diff_metadata.py.
+ snapshot.diff_metadata = diff_metadata.model_dump(mode="json")
+ update_fields.append("diff_metadata")
+
+ if absorbed:
+ snapshot.result = SnapshotResult.UNCHANGED
+ snapshot.classification_reason = ClassificationReason.BELOW_THRESHOLD
+ update_fields.extend(["result", "classification_reason"])
+
+ snapshot.save(update_fields=update_fields)
return snapshot
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index a9e1bebfd6e1..9c3fba6e9e05 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -35,8 +35,10 @@ from ..facade.contracts import (
QuarantineSourceRun,
RecomputeResult,
Repo,
+ RowShift,
Run,
RunSummary,
+ ShiftBand,
Snapshot,
SnapshotHistoryEntry,
SnapshotManifestItem,
@@ -45,7 +47,7 @@ from ..facade.contracts import (
UploadTarget,
UserBasicInfo,
)
-from ..facade.enums import FlakinessState
+from ..facade.enums import FlakinessState, ShiftBandKind
# --- Output Serializers ---
@@ -84,6 +86,44 @@ class ClusterSummarySerializer(DataclassSerializer):
dataclass = ClusterSummary
+class ShiftBandSerializer(DataclassSerializer):
+ y = serializers.IntegerField(help_text="First row of the band, in current-image coordinates.")
+ rows = serializers.IntegerField(help_text="How many rows the band covers.")
+ kind = serializers.ChoiceField(
+ choices=[(kind.value, kind.value) for kind in ShiftBandKind],
+ help_text=(
+ "'inserted' when the current image gained these rows, 'deleted' when it lost them. "
+ "A deleted band has no rows of its own in the current image, so its y is the seam "
+ "the removed rows left behind."
+ ),
+ )
+
+ class Meta:
+ dataclass = ShiftBand
+
+
+class RowShiftSerializer(DataclassSerializer):
+ bands = ShiftBandSerializer(
+ many=True,
+ help_text="Where the shift happened, in current-image coordinates.",
+ )
+ inserted_rows = serializers.IntegerField(help_text="Rows the current image gained.")
+ deleted_rows = serializers.IntegerField(help_text="Rows the current image lost.")
+ residual_percentage = serializers.FloatField(
+ help_text=(
+ "Percentage of pixels that differ inside the rows present in both images, 0 to 100. "
+ "Excludes the shift itself. The stored diff_percentage adds the area of the rows the shift "
+ "added or removed, and that combined number is what the pixel threshold judges."
+ )
+ )
+ raw_diff_percentage = serializers.FloatField(
+ help_text="Percentage of pixels that differ without alignment, which is what the shift would have cost."
+ )
+
+ class Meta:
+ dataclass = RowShift
+
+
class SnapshotSerializer(DataclassSerializer):
# Explicitly mark artifact fields as nullable for OpenAPI schema
current_artifact = ArtifactSerializer(allow_null=True, required=False)
@@ -91,6 +131,7 @@ class SnapshotSerializer(DataclassSerializer):
diff_artifact = ArtifactSerializer(allow_null=True, required=False)
reviewed_by = UserBasicInfoSerializer(allow_null=True, required=False)
cluster_summary = ClusterSummarySerializer(allow_null=True, required=False)
+ row_shift = RowShiftSerializer(allow_null=True, required=False)
class Meta:
dataclass = Snapshot
@@ -233,6 +274,7 @@ class FinalizeRunInputSerializer(DataclassSerializer):
class SnapshotHistoryEntrySerializer(DataclassSerializer):
current_artifact = ArtifactSerializer(allow_null=True, required=False)
+ row_shift = RowShiftSerializer(allow_null=True, required=False)
class Meta:
dataclass = SnapshotHistoryEntry
diff --git a/products/visual_review/backend/tests/conftest.py b/products/visual_review/backend/tests/conftest.py
index 6f660e3af1fc..0b0eead5a7b7 100644
--- a/products/visual_review/backend/tests/conftest.py
+++ b/products/visual_review/backend/tests/conftest.py
@@ -5,11 +5,13 @@ Shared PostHog test fixtures (team, user, django_db_setup) are inherited
from products/conftest.py which re-exports posthog/conftest.py.
"""
+import io
import re
import json
import base64
import hashlib
import subprocess
+from collections.abc import Sequence
from contextlib import AbstractContextManager
from pathlib import Path
@@ -19,6 +21,7 @@ from unittest.mock import MagicMock
from django.db import connections
import responses
+from PIL import Image
from posthog.models.scoping import team_scope
@@ -26,6 +29,38 @@ from products.visual_review.backend.models import Repo
PRODUCT_DATABASES = {"default", "visual_review_db_writer", "visual_review_db_reader"}
+# --- Image builders shared by the diff tests ---
+
+
+def to_png(image: Image.Image) -> bytes:
+ buffer = io.BytesIO()
+ image.save(buffer, format="PNG")
+ return buffer.getvalue()
+
+
+def open_png(png_bytes: bytes) -> Image.Image:
+ return Image.open(io.BytesIO(png_bytes)).convert("RGBA")
+
+
+def make_striped_png(row_colors: Sequence[tuple[int, int, int, int]], width: int = 20) -> bytes:
+ # Every row gets its own color, so no two rows hash alike and row alignment
+ # has exactly one answer, which lets a test assert a band position.
+ image = Image.new("RGBA", (width, len(row_colors)))
+ for y, color in enumerate(row_colors):
+ image.paste(color, (0, y, width, y + 1))
+ return to_png(image)
+
+
+def insert_background_rows(png_bytes: bytes, y: int, rows: int, fill: tuple[int, int, int, int]) -> bytes:
+ # Pushes everything below `y` down by `rows` rows of `fill`, which is what a
+ # panel that gained a pixel of padding does to a full-page screenshot.
+ image = open_png(png_bytes)
+ width, height = image.size
+ out = Image.new("RGBA", (width, height + rows), fill)
+ out.paste(image.crop((0, 0, width, y)), (0, 0))
+ out.paste(image.crop((0, y, width, height)), (0, y + rows))
+ return to_png(out)
+
@pytest.fixture(scope="package", autouse=True)
def _enable_pg_trgm_on_visual_review_db(django_db_setup, django_db_blocker):
diff --git a/products/visual_review/backend/tests/test_diff.py b/products/visual_review/backend/tests/test_diff.py
index 9225d0cac314..c3f2eae833bb 100644
--- a/products/visual_review/backend/tests/test_diff.py
+++ b/products/visual_review/backend/tests/test_diff.py
@@ -4,7 +4,8 @@ import io
from PIL import Image
-from products.visual_review.backend.diff import compare_images
+from products.visual_review.backend.diff import ALIGN_MAX_ROWS, compare_images
+from products.visual_review.backend.tests.conftest import make_striped_png, to_png
def _make_png(width: int, height: int, color: tuple[int, int, int, int]) -> bytes:
@@ -15,6 +16,17 @@ def _make_png(width: int, height: int, color: tuple[int, int, int, int]) -> byte
return buffer.getvalue()
+def _red_row_indices(image: Image.Image) -> set[int]:
+ rows: set[int] = set()
+ for y in range(image.height):
+ for x in range(image.width):
+ pixel = image.getpixel((x, y))
+ if isinstance(pixel, tuple) and pixel[:3] == (255, 0, 0):
+ rows.add(y)
+ break
+ return rows
+
+
class TestCompareImages:
def test_identical_images_zero_diff(self):
red = (255, 0, 0, 255)
@@ -28,6 +40,8 @@ class TestCompareImages:
assert result.width == 10
assert result.height == 10
assert len(result.diff_hash) == 64 # BLAKE3 hex
+ # No pixel differs, so there is nothing to align and no alignment runs.
+ assert result.row_shift is None
def test_completely_different_images_full_diff(self):
red = (255, 0, 0, 255)
@@ -93,3 +107,51 @@ class TestCompareImages:
diff_img = Image.open(io.BytesIO(result.diff_image))
assert diff_img.size == (10, 10)
assert diff_img.mode in ("RGB", "RGBA")
+
+ def test_inserted_row_diff_image_marks_only_that_row(self):
+ # Each row has its own color, so row alignment has one answer and the
+ # diff image can only be red where the new row landed. Without
+ # alignment every row below the insert would come back red.
+ baseline_rows = [(10 * i % 250, 40, 200, 255) for i in range(20)]
+ current_rows = [*baseline_rows[:8], (255, 255, 255, 255), *baseline_rows[8:]]
+
+ result = compare_images(make_striped_png(baseline_rows), make_striped_png(current_rows))
+
+ assert result.row_shift is not None
+ assert result.row_shift.inserted_rows == 1
+ assert [(b.y, b.rows, b.kind) for b in result.row_shift.bands] == [(8, 1, "inserted")]
+
+ assert result.diff_image is not None
+ diff_img = Image.open(io.BytesIO(result.diff_image)).convert("RGBA")
+ assert diff_img.size == (20, 21) # the current image, one row taller than the baseline
+ assert _red_row_indices(diff_img) == {8}
+
+ def test_alignment_skipped_past_the_row_cap(self):
+ rows = ALIGN_MAX_ROWS + 1
+ baseline = _make_png(1, rows, (255, 255, 255, 255))
+ current = Image.new("RGBA", (1, rows), (255, 255, 255, 255))
+ current.putpixel((0, 0), (0, 0, 0, 255))
+
+ result = compare_images(baseline, to_png(current))
+
+ assert result.diff_pixel_count == 1
+ assert result.row_shift is None
+ assert result.aligned_diff_pixel_count == result.diff_pixel_count
+
+ def test_deleted_row_result_dimensions_follow_the_diff_image(self):
+ # The baseline is the taller of the two, so the padded buffers the
+ # metrics run over are 20x20 while the aligned diff image is the
+ # current image at 20x19. The result has to report the image's own
+ # size, because it is what the diff artifact row records and what the
+ # frontend scales its cluster and band overlays by.
+ baseline_rows = [(10 * i % 250, 40, 200, 255) for i in range(20)]
+ current_rows = [*baseline_rows[:8], *baseline_rows[9:]]
+
+ result = compare_images(make_striped_png(baseline_rows), make_striped_png(current_rows))
+
+ assert result.row_shift is not None
+ assert [(b.y, b.rows, b.kind) for b in result.row_shift.bands] == [(8, 1, "deleted")]
+
+ assert result.diff_image is not None
+ diff_img = Image.open(io.BytesIO(result.diff_image))
+ assert (result.width, result.height) == diff_img.size == (20, 19)
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index 454d63f58bf8..5df766bfceef 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -166,6 +166,23 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
team_id=self.team.id,
)
+ # The row shift the diff pipeline stored has to survive the trip
+ # through the facade DTO and the serializer, because the badge and the
+ # band overlays are built from it.
+ RunSnapshot.objects.filter(run_id=create_result.run_id, identifier="Button").update(
+ diff_metadata={
+ "row_shift": {
+ "inserted_rows": 1,
+ "deleted_rows": 0,
+ "changed_rows": 0,
+ "residual_pixel_count": 0,
+ "residual_percentage": 0.0,
+ "raw_diff_percentage": 2.4,
+ "bands": [{"y": 210, "rows": 1, "kind": "inserted"}],
+ }
+ }
+ )
+
response = self.client.get(f"/api/projects/{self.team.id}/visual_review/runs/{create_result.run_id}/snapshots/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
@@ -175,6 +192,13 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
identifiers = {s["identifier"] for s in results}
self.assertEqual(identifiers, {"Button", "Card"})
+ by_identifier = {s["identifier"]: s for s in results}
+ row_shift = by_identifier["Button"]["row_shift"]
+ self.assertEqual(row_shift["inserted_rows"], 1)
+ self.assertEqual(row_shift["raw_diff_percentage"], 2.4)
+ self.assertEqual(row_shift["bands"], [{"y": 210, "rows": 1, "kind": "inserted"}])
+ self.assertIsNone(by_identifier["Card"]["row_shift"])
+
@parameterized.expand(
[
("excluded_by_default", "", {"Card"}),
@@ -412,6 +436,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
run_type: str = RunType.STORYBOOK,
run_status: str = RunStatus.COMPLETED,
result: str = SnapshotResult.UNCHANGED,
+ diff_metadata: dict | None = None,
) -> RunSnapshot:
"""Create one Run + one RunSnapshot directly, with full control over result and status."""
artifact, _ = artifact_store.get_or_create_artifact(
@@ -451,6 +476,7 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
current_artifact=artifact,
baseline_artifact=baseline_artifact,
result=result,
+ diff_metadata=diff_metadata if diff_metadata is not None else {},
)
def _history_url(self, identifier: str, run_type: str = RunType.STORYBOOK) -> str:
@@ -482,9 +508,83 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
)
# Tolerated drift on master: current_ flickers, baseline stays at
# base-2 — must NOT create a new entry (the prod bug behind 252
- # fake events on a single tolerated-drift story).
+ # fake events on a single tolerated-drift story). The pair aligned
+ # with nothing moved, which is a row shift of zero, not a shift.
+ self._seed_history_row(
+ sha="ddd0000",
+ branch="master",
+ content_hash="hash-jitter",
+ baseline_content_hash="base-2",
+ diff_metadata={
+ "row_shift": {
+ "inserted_rows": 0,
+ "deleted_rows": 0,
+ "changed_rows": 3,
+ "residual_pixel_count": 40,
+ "residual_percentage": 0.01,
+ "raw_diff_percentage": 0.01,
+ "bands": [],
+ }
+ },
+ )
+ # Absorbed shift on master: baseline stays at base-2, but the rows
+ # moved, and that trace only lives in history — must be an entry.
+ self._seed_history_row(
+ sha="ddd0001",
+ branch="master",
+ content_hash="hash-shift",
+ baseline_content_hash="base-2",
+ diff_metadata={
+ "row_shift": {
+ "inserted_rows": 1,
+ "deleted_rows": 0,
+ "changed_rows": 0,
+ "residual_pixel_count": 0,
+ "residual_percentage": 0.0,
+ "raw_diff_percentage": 3.2,
+ "bands": [{"y": 20, "rows": 1, "kind": "inserted"}],
+ }
+ },
+ )
+ # Master keeps absorbing a shift against the same baseline, with jitter
+ # giving every run its own image: one entry per baseline period, not
+ # one per run.
self._seed_history_row(
- sha="ddd0000", branch="master", content_hash="hash-jitter", baseline_content_hash="base-2"
+ sha="ddd0002",
+ branch="master",
+ content_hash="hash-shift-jitter",
+ baseline_content_hash="base-2",
+ diff_metadata={
+ "row_shift": {
+ "inserted_rows": 1,
+ "deleted_rows": 0,
+ "changed_rows": 0,
+ "residual_pixel_count": 0,
+ "residual_percentage": 0.0,
+ "raw_diff_percentage": 3.2,
+ "bands": [{"y": 20, "rows": 1, "kind": "inserted"}],
+ }
+ },
+ )
+ # An actionable layout change recurs on every run until its baseline
+ # moves, so it rides the baseline transition instead of its shift.
+ self._seed_history_row(
+ sha="ddd0003",
+ branch="master",
+ content_hash="hash-layout",
+ baseline_content_hash="base-2",
+ result=SnapshotResult.CHANGED,
+ diff_metadata={
+ "row_shift": {
+ "inserted_rows": 40,
+ "deleted_rows": 0,
+ "changed_rows": 0,
+ "residual_pixel_count": 0,
+ "residual_percentage": 0.0,
+ "raw_diff_percentage": 12.0,
+ "bands": [{"y": 80, "rows": 40, "kind": "inserted"}],
+ }
+ },
)
# PR-branch run — filtered out by branch.
@@ -515,12 +615,13 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
body = response.json()
results = body["results"]
# Two baseline transitions: aaa1111 (inception, base-1) and bbb1111
- # (transition to base-2). aaa2222 collapses into aaa1111's period;
- # ddd0000 collapses into bbb1111's.
- self.assertEqual(body["count"], 2)
+ # (transition to base-2), plus the absorbed shift ddd0001. aaa2222
+ # collapses into aaa1111's period; ddd0000 collapses into bbb1111's.
+ self.assertEqual(body["count"], 3)
# Output is newest-first.
- self.assertEqual(results[0]["commit_sha"], "bbb1111")
- self.assertEqual(results[1]["commit_sha"], "aaa1111")
+ self.assertEqual([entry["commit_sha"] for entry in results], ["ddd0001", "bbb1111", "aaa1111"])
+ self.assertEqual(results[0]["row_shift"]["inserted_rows"], 1)
+ self.assertIsNone(results[1]["row_shift"])
for entry in results:
self.assertIn("snapshot_id", entry)
self.assertIn("review_state", entry)
diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.py
index 97349a06dc30..d7096cc7c02d 100644
--- a/products/visual_review/backend/tests/test_tasks.py
+++ b/products/visual_review/backend/tests/test_tasks.py
@@ -24,7 +24,12 @@ from products.visual_review.backend.facade.enums import (
from products.visual_review.backend.logic import artifact_store, runs
from products.visual_review.backend.models import RunSnapshot, ToleratedHash
from products.visual_review.backend.tasks.tasks import post_approval_comment, process_run_diffs
-from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES, VisualReviewTeamScopedTestMixin
+from products.visual_review.backend.tests.conftest import (
+ PRODUCT_DATABASES,
+ VisualReviewTeamScopedTestMixin,
+ insert_background_rows,
+ make_striped_png,
+)
def _make_png(color: tuple[int, int, int, int], size: tuple[int, int] = (10, 10)) -> bytes:
@@ -42,6 +47,56 @@ def _make_png_with_single_changed_pixel() -> bytes:
return buffer.getvalue()
+# Every row has its own color, so row alignment has one answer: the page below
+# an insert moved down and nothing else changed.
+STRIPED_PAGE_ROWS = [(10 + (y * 2) % 240, 40 + y % 100, 200 - y % 150, 255) for y in range(100)]
+
+
+def _prepare_one_diff(repo, mocker, baseline_png: bytes, current_png: bytes):
+ stored_bytes = {"old_hash": baseline_png, "new_hash": current_png}
+ artifact_store.get_or_create_artifact(repo.id, "old_hash", "visual_review/old_hash")
+ artifact_store.get_or_create_artifact(repo.id, "new_hash", "visual_review/new_hash")
+ create_result = api.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc123",
+ branch="main",
+ snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
+ baseline_hashes={"Button": "old_hash"},
+ ),
+ team_id=repo.team_id,
+ )
+ with (
+ patch(
+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
+ return_value=({"Button": "old_hash"}, 0),
+ ),
+ patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay"),
+ ):
+ runs.complete_run(create_result.run_id)
+
+ mocker.patch(
+ "products.visual_review.backend.storage.ArtifactStorage.read",
+ autospec=True,
+ side_effect=lambda _storage, content_hash: stored_bytes.get(content_hash),
+ )
+ write = mocker.patch(
+ "products.visual_review.backend.storage.ArtifactStorage.write",
+ autospec=True,
+ side_effect=lambda _storage, content_hash, content: (
+ stored_bytes.setdefault(content_hash, content) and f"visual_review/{content_hash}"
+ ),
+ )
+ return create_result.run_id, write
+
+
+def _process_one_diff(repo, mocker, baseline_png: bytes, current_png: bytes) -> RunSnapshot:
+ run_id, _write = _prepare_one_diff(repo, mocker, baseline_png, current_png)
+ assert process_diffs(run_id) == 1
+ return RunSnapshot.objects.get(run_id=run_id)
+
+
@pytest.mark.django_db(databases=PRODUCT_DATABASES)
class TestProcessRunDiffs:
@pytest.fixture
@@ -332,48 +387,13 @@ class TestProcessRunDiffs:
assert compare_images.call_count == 1
def test_process_diffs_counts_below_threshold_comparisons(self, repo, mocker):
- stored_bytes = {
- "old_hash": _make_png((255, 0, 0, 255), size=(100, 100)),
- "new_hash": _make_png_with_single_changed_pixel(),
- }
- artifact_store.get_or_create_artifact(repo.id, "old_hash", "visual_review/old_hash")
- artifact_store.get_or_create_artifact(repo.id, "new_hash", "visual_review/new_hash")
- create_result = api.create_run(
- CreateRunInput(
- repo_id=repo.id,
- run_type=RunType.STORYBOOK,
- commit_sha="abc123",
- branch="main",
- snapshots=[SnapshotManifestItem(identifier="Button", content_hash="new_hash")],
- baseline_hashes={"Button": "old_hash"},
- ),
- team_id=repo.team_id,
+ snapshot = _process_one_diff(
+ repo,
+ mocker,
+ baseline_png=_make_png((255, 0, 0, 255), size=(100, 100)),
+ current_png=_make_png_with_single_changed_pixel(),
)
- with (
- patch(
- "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",
- return_value=({"Button": "old_hash"}, 0),
- ),
- patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay"),
- ):
- runs.complete_run(create_result.run_id)
- mocker.patch(
- "products.visual_review.backend.storage.ArtifactStorage.read",
- autospec=True,
- side_effect=lambda _storage, content_hash: stored_bytes.get(content_hash),
- )
- mocker.patch(
- "products.visual_review.backend.storage.ArtifactStorage.write",
- autospec=True,
- side_effect=lambda _storage, content_hash, content: (
- stored_bytes.setdefault(content_hash, content) and f"visual_review/{content_hash}"
- ),
- )
-
- assert process_diffs(create_result.run_id) == 1
-
- snapshot = RunSnapshot.objects.get(run_id=create_result.run_id)
assert snapshot.result == SnapshotResult.UNCHANGED
assert snapshot.classification_reason == ClassificationReason.BELOW_THRESHOLD
assert snapshot.diff_pixel_count is not None
@@ -387,6 +407,56 @@ class TestProcessRunDiffs:
alternate_hash="new_hash",
).exists()
+ def test_absorbed_shift_survives_a_failed_diff_upload(self, repo, mocker):
+ # The diff pass runs once per run. A noise row that stayed CHANGED
+ # because its courtesy diff image did not upload would fail the gate
+ # for a change nobody can see.
+ run_id, _write = _prepare_one_diff(
+ repo,
+ mocker,
+ baseline_png=make_striped_png(STRIPED_PAGE_ROWS, width=100),
+ current_png=insert_background_rows(
+ make_striped_png(STRIPED_PAGE_ROWS, width=100), y=20, rows=1, fill=(255, 255, 255, 255)
+ ),
+ )
+ mocker.patch.object(diffing, "_write_diff_artifact", side_effect=RuntimeError("object storage down"))
+
+ assert process_diffs(run_id) == 1
+
+ snapshot = RunSnapshot.objects.get(run_id=run_id)
+ assert snapshot.result == SnapshotResult.UNCHANGED
+ assert snapshot.classification_reason == ClassificationReason.BELOW_THRESHOLD
+ assert snapshot.diff_artifact is None
+ assert snapshot.diff_metadata["row_shift"]["inserted_rows"] == 1
+
+ def test_process_diffs_absorbs_a_one_row_shift_but_keeps_its_trace(self, repo, mocker):
+ # The whole point of row alignment: a page that moved down by a row is
+ # noise, but the run still has to say what moved, and the tolerated
+ # hash has to record what the run really cost. Recording the naive
+ # percentage here would eat the flakiness headroom of a clean story.
+ snapshot = _process_one_diff(
+ repo,
+ mocker,
+ baseline_png=make_striped_png(STRIPED_PAGE_ROWS, width=100),
+ current_png=insert_background_rows(
+ make_striped_png(STRIPED_PAGE_ROWS, width=100), y=20, rows=1, fill=(255, 255, 255, 255)
+ ),
+ )
+
+ assert snapshot.result == SnapshotResult.UNCHANGED
+ assert snapshot.classification_reason == ClassificationReason.BELOW_THRESHOLD
+ assert snapshot.diff_metadata["row_shift"]["inserted_rows"] == 1
+ assert snapshot.diff_metadata["row_shift"]["raw_diff_percentage"] > snapshot.diff_percentage
+ assert snapshot.diff_artifact is not None
+
+ tolerated = ToleratedHash.objects.get(
+ repo_id=repo.id,
+ identifier="Button",
+ baseline_hash="old_hash",
+ alternate_hash="new_hash",
+ )
+ assert tolerated.diff_percentage == snapshot.diff_percentage
+
class TestCountProcessedDiffs(VisualReviewTeamScopedTestMixin, BaseTest):
databases = PRODUCT_DATABASES
diff --git a/products/visual_review/backend/tests/test_thumbnails.py b/products/visual_review/backend/tests/test_thumbnails.py
index a0ca76915559..2136e3ca5959 100644
--- a/products/visual_review/backend/tests/test_thumbnails.py
+++ b/products/visual_review/backend/tests/test_thumbnails.py
@@ -1,4 +1,5 @@
import io
+from dataclasses import replace
import pytest
from posthog.test.base import APIBaseTest
@@ -77,6 +78,9 @@ def _make_compare_result(thumbnail: bytes = b"fake-webp") -> CompareResult:
thumbnail_hash="thumb_hash_auto",
size_mismatch=False,
cluster_summary=None,
+ aligned_diff_pixel_count=100,
+ aligned_diff_percentage=5.0,
+ row_shift=None,
)
@@ -123,9 +127,7 @@ class TestStoreThumbnail:
repo = _make_repo(team)
_run, snapshot = _make_run_with_snapshot(repo)
- result = _make_compare_result()
- result.thumbnail = None
- result.thumbnail_hash = ""
+ result = replace(_make_compare_result(), thumbnail=None, thumbnail_hash="")
_store_thumbnail(snapshot, result)
diff --git a/products/visual_review/backend/tests/test_two_tier_diff.py b/products/visual_review/backend/tests/test_two_tier_diff.py
index 9518ad957502..0e96cc82d02f 100644
--- a/products/visual_review/backend/tests/test_two_tier_diff.py
+++ b/products/visual_review/backend/tests/test_two_tier_diff.py
@@ -9,8 +9,13 @@ from PIL import Image, ImageDraw
from products.visual_review.backend.diff import compare_images
from products.visual_review.backend.diffing import classify_compare_result
-from products.visual_review.backend.facade.contracts import PIXEL_DIFF_THRESHOLD_PERCENT, SSIM_DISSIMILARITY_THRESHOLD
+from products.visual_review.backend.facade.contracts import (
+ PIXEL_DIFF_THRESHOLD_PERCENT,
+ SHIFT_ABSORB_MAX_ROWS,
+ SSIM_DISSIMILARITY_THRESHOLD,
+)
from products.visual_review.backend.facade.enums import ChangeKind
+from products.visual_review.backend.tests.conftest import insert_background_rows, make_striped_png, open_png, to_png
def _make_png(width: int, height: int, color: tuple[int, int, int, int]) -> bytes:
@@ -52,8 +57,26 @@ def _make_tall_settings_page(width: int = 400, height: int = 3000, extra_element
return buf.getvalue()
+PAGE_BACKGROUND = (245, 245, 245, 255)
+
+
+def _insert_rows(png_bytes: bytes, y: int, rows: int) -> bytes:
+ return insert_background_rows(png_bytes, y, rows, PAGE_BACKGROUND)
+
+
+def _grow_rows(png_bytes: bytes, y: int, rows: int) -> bytes:
+ # A panel that grows repeats its edge row, so the new rows match the row above them.
+ image = open_png(png_bytes)
+ width, height = image.size
+ out = Image.new("RGBA", (width, height + rows))
+ out.paste(image.crop((0, 0, width, y)), (0, 0))
+ for i in range(rows):
+ out.paste(image.crop((0, y - 1, width, y)), (0, y + i))
+ out.paste(image.crop((0, y, width, height)), (0, y + rows))
+ return to_png(out)
+
+
def _classify(baseline_bytes: bytes, current_bytes: bytes) -> ChangeKind | None:
- """Run the production classifier on a fresh compare result."""
result = compare_images(baseline_bytes, current_bytes, with_thumbnail=False)
return classify_compare_result(result)
@@ -183,3 +206,176 @@ class TestClusterSummary:
dumped = original.model_dump(mode="json")
roundtripped = DiffMetadata.model_validate(dumped)
assert roundtripped == original
+
+
+class TestRowShiftClassification:
+ # A panel that grows by a pixel moves everything below it down, which a
+ # top-aligned pixel diff reads as a page-wide change. Row alignment pairs
+ # the rows that exist in both images so the diff describes what changed.
+
+ @pytest.mark.parametrize(
+ "inserted_rows, expected_kind",
+ [
+ pytest.param(1, None, id="one_row_absorbed"),
+ pytest.param(SHIFT_ABSORB_MAX_ROWS, None, id="cap_still_absorbed"),
+ pytest.param(SHIFT_ABSORB_MAX_ROWS + 1, ChangeKind.LAYOUT, id="past_cap_is_layout"),
+ ],
+ )
+ def test_background_row_insert_ladder(self, inserted_rows: int, expected_kind: ChangeKind | None):
+ baseline = _make_tall_settings_page()
+ current = _insert_rows(baseline, y=200, rows=inserted_rows)
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert result.row_shift.inserted_rows == inserted_rows
+ assert result.row_shift.deleted_rows == 0
+ # Everything below the seam is identical once the rows are paired.
+ assert result.row_shift.residual_percentage < 0.01
+ # Without alignment the same pair reads as a large pixel diff.
+ assert result.diff_percentage > PIXEL_DIFF_THRESHOLD_PERCENT
+ assert result.row_shift.raw_diff_percentage == result.diff_percentage
+
+ bands = result.row_shift.bands
+ assert len(bands) == 1
+ assert (bands[0].rows, bands[0].kind) == (inserted_rows, "inserted")
+ # The rows around y=200 are page background, and the aligner is free to
+ # put the seam anywhere inside that identical run, so the band lands
+ # near the insert rather than exactly on it.
+ assert 200 <= bands[0].y <= 215
+
+ assert classify_compare_result(result) == expected_kind
+
+ @pytest.mark.parametrize(
+ "page_height, moved_rows, expected_kind",
+ [
+ pytest.param(3000, SHIFT_ABSORB_MAX_ROWS, None, id="cap_still_absorbed"),
+ pytest.param(3000, SHIFT_ABSORB_MAX_ROWS + 1, ChangeKind.LAYOUT, id="past_cap_is_layout"),
+ # On a short page the doubled band area alone would cross the pixel threshold.
+ pytest.param(100, SHIFT_ABSORB_MAX_ROWS, None, id="cap_on_a_short_page"),
+ ],
+ )
+ def test_same_height_translation_counts_the_movement_once(
+ self, page_height: int, moved_rows: int, expected_kind: ChangeKind | None
+ ):
+ # A page that keeps its height while its content moves down shows up
+ # as the same number of inserted and deleted rows. Summing both sides
+ # would double the movement and push a cap-sized shift into layout.
+ baseline = _make_tall_settings_page(height=page_height)
+ grown = open_png(_grow_rows(baseline, y=page_height // 2, rows=moved_rows))
+ current = to_png(grown.crop((0, 0, grown.width, grown.height - moved_rows)))
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert (result.row_shift.inserted_rows, result.row_shift.deleted_rows) == (moved_rows, moved_rows)
+ assert result.row_shift.shifted_rows == moved_rows
+
+ assert classify_compare_result(result) == expected_kind
+
+ @pytest.mark.parametrize(
+ "page_rows, expected_kind",
+ [
+ pytest.param(20, ChangeKind.PIXEL, id="bar_across_a_small_component"),
+ pytest.param(3000, None, id="two_rows_on_a_tall_page"),
+ ],
+ )
+ def test_inserted_rows_count_their_own_area(self, page_rows: int, expected_kind: ChangeKind | None):
+ # The residual never sees rows that have no counterpart, so the cap
+ # alone would absorb two black rows across a twenty-row component.
+ # The band's own area has to count against the pixel threshold.
+ colors = [(200 + (i * 7) % 50, 200 + (i * 13) % 50, 220, 255) for i in range(page_rows)]
+ baseline = make_striped_png(colors, width=100)
+ current = insert_background_rows(baseline, y=page_rows // 2, rows=2, fill=(0, 0, 0, 255))
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert result.row_shift.shifted_rows == 2
+ assert result.row_shift.residual_percentage == 0
+
+ assert classify_compare_result(result) == expected_kind
+
+ def test_over_cap_shift_is_layout_even_when_its_band_covers_the_page(self):
+ # The band's area counts as changed pixels, and a big move on a short
+ # page covers more of it than the pixel threshold. The move is still
+ # the change, so it has to read as layout, not as a pixel diff.
+ baseline = _make_tall_settings_page(height=200)
+ current = _insert_rows(baseline, y=80, rows=40)
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert result.aligned_diff_percentage > PIXEL_DIFF_THRESHOLD_PERCENT
+
+ assert classify_compare_result(result) == ChangeKind.LAYOUT
+
+ @pytest.mark.parametrize("destination", [pytest.param(800, id="interior"), pytest.param(3000, id="bottom_edge")])
+ def test_relocated_thin_element_is_layout_not_a_small_shift(self, destination: int):
+ # A one-row line that moved from y=100 elsewhere aligns as one delete
+ # plus one insert with no residual. Counting rows alone calls that a
+ # one-row shift; the inserted row's pixels equal the deleted row's,
+ # which says the line moved. The bottom edge is the case that looks
+ # exactly like a page translation from the band positions alone.
+ colors = [(200 + (i * 7) % 50, 200 + (i * 13) % 50, 220, 255) for i in range(3000)]
+ line = (0, 0, 0, 255)
+ baseline = make_striped_png([*colors[:100], line, *colors[100:]], width=100)
+ current = make_striped_png([*colors[:destination], line, *colors[destination:]], width=100)
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert (result.row_shift.inserted_rows, result.row_shift.deleted_rows) == (1, 1)
+ assert result.row_shift.relocated_rows == 1
+
+ assert classify_compare_result(result) == ChangeKind.LAYOUT
+
+ def test_page_shift_that_exposes_matching_edge_padding_still_absorbs(self):
+ # A fixed-height page that moved down by a row exposes a padding row
+ # at the top and crops one at the bottom. Both are padding, so they
+ # match, and the top one differs from the content below it. That is
+ # not an element that moved: neither row stood out in the interior.
+ padding = (245, 245, 245, 255)
+ colors = [(200 + (i * 7) % 50, 200 + (i * 13) % 50, 220, 255) for i in range(300)]
+ baseline = make_striped_png([padding, *colors, padding], width=100)
+ current = make_striped_png([padding, padding, *colors], width=100)
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert (result.row_shift.inserted_rows, result.row_shift.deleted_rows) == (1, 1)
+ assert result.row_shift.relocated_rows == 0
+
+ assert classify_compare_result(result) is None
+
+ def test_shift_too_big_to_check_for_relocation_goes_to_review(self, mocker):
+ # The relocation check decodes the images again. Past the pixel bound
+ # it is skipped, and a shift with both inserts and deletes must then
+ # reach a reviewer rather than absorb on the strength of a guess.
+ mocker.patch("products.visual_review.backend.diff.RELOCATION_CHECK_MAX_PIXELS", 1)
+ baseline = _make_tall_settings_page()
+ grown = open_png(_grow_rows(baseline, y=1500, rows=1))
+ current = to_png(grown.crop((0, 0, grown.width, grown.height - 1)))
+
+ result = compare_images(baseline, current, with_thumbnail=False)
+ assert result.row_shift is not None
+ assert result.row_shift.relocated_rows == 1
+
+ assert classify_compare_result(result) == ChangeKind.LAYOUT
+
+ def test_shift_plus_real_change_is_not_absorbed(self):
+ baseline = _make_tall_settings_page()
+ shifted = open_png(_insert_rows(baseline, y=200, rows=1))
+ ImageDraw.Draw(shifted).rectangle([(20, 1000), (380, 1060)], fill=(255, 0, 0, 255))
+
+ result = compare_images(baseline, to_png(shifted), with_thumbnail=False)
+
+ assert result.row_shift is not None
+ assert result.row_shift.inserted_rows == 1
+ assert classify_compare_result(result) in (ChangeKind.PIXEL, ChangeKind.STRUCTURAL)
+
+ def test_partial_width_drift_is_not_absorbed(self):
+ # Only the right half of a block moves down a row. That is not a page
+ # shift, so it must not ride the absorb path out of review.
+ baseline = _make_tall_settings_page()
+ drifted = open_png(baseline)
+ width, _ = drifted.size
+ half = drifted.crop((width // 2, 500, width, 900))
+ drifted.paste((245, 245, 245, 255), (width // 2, 500, width, 900))
+ drifted.paste(half, (width // 2, 501))
+
+ assert _classify(baseline, to_png(drifted)) is not None
diff --git a/products/visual_review/frontend/components/SnapshotChangeBadge.tsx b/products/visual_review/frontend/components/SnapshotChangeBadge.tsx
index 88a3d39ea345..23acbe297788 100644
--- a/products/visual_review/frontend/components/SnapshotChangeBadge.tsx
+++ b/products/visual_review/frontend/components/SnapshotChangeBadge.tsx
@@ -2,7 +2,8 @@ import { IconWarning } from '@posthog/icons'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
-import type { ClusterSummaryApi } from '../generated/api.schemas'
+import type { ClusterSummaryApi, RowShiftApi } from '../generated/api.schemas'
+import { type ShiftDescription, describeShift } from '../lib/shiftCopy'
// IconPulse is intentionally NOT used here. The "pulse" icon reads as
// "average drift / activity over time" and only makes sense in the
@@ -42,6 +43,22 @@ type ChangeBadgeSnapshot = {
// alongside the kind chip; doesn't replace it (a snapshot can have a
// different viewport AND a real content change).
size_mismatch?: boolean | null
+ // The vertical shift the diff pipeline measured. Present on absorbed
+ // snapshots too, which is the only signal those carry.
+ row_shift?: RowShiftApi | null
+}
+
+/**
+ * The shift chip a snapshot gets, or null. `layout` is a change somebody has
+ * to look at; an empty kind with a shift is one the classifier absorbed.
+ * Every other kind describes itself through its own chip.
+ */
+function shiftDescription(snapshot: ChangeBadgeSnapshot): ShiftDescription | null {
+ const kind = snapshot.change_kind || ''
+ if (kind !== '' && kind !== 'layout') {
+ return null
+ }
+ return describeShift(snapshot.row_shift, kind === '')
}
/**
@@ -55,6 +72,9 @@ export function hasSnapshotChangeBadge(snapshot: ChangeBadgeSnapshot): boolean {
if (snapshot.size_mismatch) {
return true
}
+ if (shiftDescription(snapshot)) {
+ return true
+ }
const kind = snapshot.change_kind || ''
if (kind === 'structural') {
return true
@@ -81,12 +101,17 @@ type ChangeBadgeProps = {
* the label explains why it's flagged. Both tiers use the same metric
* (pixel diff %) so the overview can average across them.
*
+ * `layout` shows how many rows the page gained or lost. A snapshot with a
+ * row shift and no kind was absorbed as noise, and gets a neutral chip so
+ * the run still shows what moved.
+ *
* Returns null when there's nothing to show (no diff, no size mismatch,
- * or pre-migration legacy row with no kind and no percentage).
+ * no shift, or pre-migration legacy row with no kind and no percentage).
*/
export function SnapshotChangeBadge({ snapshot, size = 'default' }: ChangeBadgeProps): JSX.Element | null {
const kind = snapshot.change_kind || ''
const pct = snapshot.diff_percentage ?? null
+ const shift = shiftDescription(snapshot)
const isCompact = size === 'small'
// Smaller padding + non-pill corners on the filmstrip; the rounded-full
// pill plus icon pair was too visually heavy stacked next to a thumbnail.
@@ -111,6 +136,20 @@ export function SnapshotChangeBadge({ snapshot, size = 'default' }: ChangeBadgeP
</span>
</Tooltip>
)
+ } else if (shift) {
+ // Absorbed reads neutral: nothing there needs review, and the chip is
+ // only present so the run does not look like it saw nothing.
+ const toneClass =
+ shift.tone === 'warning' ? 'bg-warning-highlight/60 text-warning-dark' : 'bg-bg-3000 text-muted-alt'
+ kindChip = (
+ <Tooltip title={shift.tooltip}>
+ <span
+ className={`shrink-0 inline-flex items-center font-medium leading-none ${toneClass} ${radiusClass} ${sizeClass}`}
+ >
+ {isCompact ? shift.compactLabel : shift.label}
+ </span>
+ </Tooltip>
+ )
} else if ((kind === 'pixel' || kind === '') && pct != null && pct >= PCT_DISPLAY_FLOOR) {
// `pixel` (current pipeline) and legacy rows (no `change_kind`
// but a populated `diff_percentage`) both render as the
@@ -145,18 +184,23 @@ export function SnapshotChangeBadge({ snapshot, size = 'default' }: ChangeBadgeP
// so two side-by-side chips don't crowd the thumbnail.
const sizeChipTooltip =
'Baseline and current screenshots had different dimensions. Pixelhog padded to the larger size before computing the diff, so metrics are still meaningful — they just include the new content area as part of the change.'
- const sizeChip = snapshot.size_mismatch ? (
- <Tooltip title={sizeChipTooltip}>
- <span
- className={`shrink-0 inline-flex items-center bg-warning-highlight font-medium text-warning-dark leading-none ${radiusClass} ${
- isCompact ? 'p-0.5' : `gap-1 ${sizeClass}`
- }`}
- >
- <IconWarning className={iconClass} />
- {!isCompact && 'Size changed'}
- </span>
- </Tooltip>
- ) : null
+ // A shift already says the page changed height, and says it more
+ // precisely, so the size chip would only repeat it in warning colors.
+ // A shift also means the widths matched: pixelhog never aligns a pair
+ // whose widths differ, so a width change never comes with a shift.
+ const sizeChip =
+ snapshot.size_mismatch && !shift ? (
+ <Tooltip title={sizeChipTooltip}>
+ <span
+ className={`shrink-0 inline-flex items-center bg-warning-highlight font-medium text-warning-dark leading-none ${radiusClass} ${
+ isCompact ? 'p-0.5' : `gap-1 ${sizeClass}`
+ }`}
+ >
+ <IconWarning className={iconClass} />
+ {!isCompact && 'Size changed'}
+ </span>
+ </Tooltip>
+ ) : null
if (!kindChip && !sizeChip) {
return null
diff --git a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx
index e4b95cce84f2..e992bebb9bf9 100644
--- a/products/visual_review/frontend/components/SnapshotDiffViewer.tsx
+++ b/products/visual_review/frontend/components/SnapshotDiffViewer.tsx
@@ -14,6 +14,7 @@ import { visualReviewPreferencesLogic } from '../scenes/visualReviewPreferencesL
import { QuarantineAction } from './QuarantineAction'
import { SnapshotChangeBadge, hasSnapshotChangeBadge } from './SnapshotChangeBadge'
import { SnapshotClusterPanel } from './SnapshotClusterPanel'
+import { SnapshotShiftSummary } from './SnapshotShiftSummary'
import { SnapshotStatusIndicator } from './SnapshotStatusIndicator'
// A toleration the diff pipeline minted for sub-threshold jitter reads very
@@ -129,6 +130,7 @@ export function SnapshotDiffViewer({
})),
[visibleClusterSummary]
)
+ const rowShift = snapshot.row_shift ?? null
const diffPixelTotal =
snapshot.diff_artifact?.width && snapshot.diff_artifact?.height
? snapshot.diff_artifact.width * snapshot.diff_artifact.height
@@ -249,6 +251,7 @@ export function SnapshotDiffViewer({
onModeChange={setComparisonMode}
className="min-h-[200px]"
diffOverlayBoxes={overlayBoxes}
+ diffOverlayBands={rowShift?.bands}
diffOverlayWidth={snapshot.diff_artifact?.width ?? undefined}
diffOverlayHeight={snapshot.diff_artifact?.height ?? undefined}
highlightedOverlayIndex={highlightedClusterIndex}
@@ -266,6 +269,9 @@ export function SnapshotDiffViewer({
/>
)}
+ {/* === Row shift === */}
+ {rowShift && <SnapshotShiftSummary rowShift={rowShift} />}
+
{/* === Change clusters === */}
{visibleClusterSummary && visibleClusterSummary.items.length > 0 && (
<SnapshotClusterPanel
diff --git a/products/visual_review/frontend/components/SnapshotShiftSummary.tsx b/products/visual_review/frontend/components/SnapshotShiftSummary.tsx
new file mode 100644
index 000000000000..99d7186690fe
--- /dev/null
+++ b/products/visual_review/frontend/components/SnapshotShiftSummary.tsx
@@ -0,0 +1,29 @@
+import type { RowShiftApi } from '../generated/api.schemas'
+import { describeBand } from '../lib/shiftCopy'
+
+interface SnapshotShiftSummaryProps {
+ rowShift: RowShiftApi
+}
+
+/**
+ * Sidebar line naming where the page moved.
+ *
+ * Sits above the cluster panel because a shift explains the clusters below
+ * it, and it renders on its own for an absorbed shift, where the residual is
+ * too small to produce any cluster at all.
+ */
+export function SnapshotShiftSummary({ rowShift }: SnapshotShiftSummaryProps): JSX.Element | null {
+ if (rowShift.bands.length === 0) {
+ return null
+ }
+ return (
+ <div>
+ <h4 className="text-xs font-semibold text-muted mb-1">Row shift</h4>
+ <div className="flex flex-col gap-0.5 text-[11px] text-muted tabular-nums">
+ {rowShift.bands.map((band, i) => (
+ <span key={i}>{describeBand(band)}</span>
+ ))}
+ </div>
+ </div>
+ )
+}
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index 0facfd32d537..f9b0959f100f 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -361,8 +361,45 @@ export interface ArtifactApi {
download_url: string | null
}
+/**
+ * * `inserted` - inserted
+ * * `deleted` - deleted
+ */
+export type ShiftBandKindEnumApi = (typeof ShiftBandKindEnumApi)[keyof typeof ShiftBandKindEnumApi]
+
+export const ShiftBandKindEnumApi = {
+ Inserted: 'inserted',
+ Deleted: 'deleted',
+} as const
+
+export interface ShiftBandApi {
+ /** First row of the band, in current-image coordinates. */
+ y: number
+ /** How many rows the band covers. */
+ rows: number
+ /** 'inserted' when the current image gained these rows, 'deleted' when it lost them. A deleted band has no rows of its own in the current image, so its y is the seam the removed rows left behind.
+ *
+ * * `inserted` - inserted
+ * * `deleted` - deleted */
+ kind: ShiftBandKindEnumApi
+}
+
+export interface RowShiftApi {
+ /** Where the shift happened, in current-image coordinates. */
+ bands: ShiftBandApi[]
+ /** Rows the current image gained. */
+ inserted_rows: number
+ /** Rows the current image lost. */
+ deleted_rows: number
+ /** Percentage of pixels that differ inside the rows present in both images, 0 to 100. Excludes the shift itself. The stored diff_percentage adds the area of the rows the shift added or removed, and that combined number is what the pixel threshold judges. */
+ residual_percentage: number
+ /** Percentage of pixels that differ without alignment, which is what the shift would have cost. */
+ raw_diff_percentage: number
+}
+
export interface SnapshotHistoryEntryApi {
current_artifact?: ArtifactApi | null
+ row_shift?: RowShiftApi | null
run_id: string
snapshot_id: string
result: string
@@ -505,6 +542,7 @@ export interface SnapshotApi {
diff_artifact?: ArtifactApi | null
reviewed_by?: UserBasicInfoApi | null
cluster_summary?: ClusterSummaryApi | null
+ row_shift?: RowShiftApi | null
id: string
run_id: string
identifier: string
diff --git a/products/visual_review/frontend/lib/shiftCopy.ts b/products/visual_review/frontend/lib/shiftCopy.ts
new file mode 100644
index 000000000000..95ab3575235f
--- /dev/null
+++ b/products/visual_review/frontend/lib/shiftCopy.ts
@@ -0,0 +1,111 @@
+import { pluralize } from 'lib/utils/strings'
+
+import type { RowShiftApi, ShiftBandApi } from '../generated/api.schemas'
+
+/** How far the rows moved, the larger side when inserts and deletes cancel out. Zero when the pair aligned with no shift. */
+export function shiftedRows(rowShift: RowShiftApi | null | undefined): number {
+ return rowShift ? Math.max(rowShift.inserted_rows, rowShift.deleted_rows) : 0
+}
+
+/** Only name a position when there is one band, so it can't point at one of several. */
+function shiftPosition(rowShift: RowShiftApi): string {
+ return rowShift.bands.length === 1 ? ` at y=${rowShift.bands[0].y}` : ''
+}
+
+function formatResidual(value: number): string {
+ if (value === 0) {
+ return '0%'
+ }
+ return value < 0.01 ? `${value.toFixed(3)}%` : `${value.toFixed(2)}%`
+}
+
+/**
+ * The movement in pixels, the same number the classifier judged. Signed when
+ * the page only grew or only shrank; unsigned when rows moved both ways,
+ * because the net height change would understate how far they moved.
+ */
+function signedShiftPx(rowShift: RowShiftApi): string {
+ const px = `${shiftedRows(rowShift)}px`
+ if (rowShift.deleted_rows === 0) {
+ return `+${px}`
+ }
+ if (rowShift.inserted_rows === 0) {
+ return `-${px}`
+ }
+ return px
+}
+
+function absorbedTooltip(rowShift: RowShiftApi): string {
+ const where = shiftPosition(rowShift)
+ let opening: string
+ if (rowShift.deleted_rows === 0) {
+ opening = `The page grew by ${pluralize(rowShift.inserted_rows, 'row')}${where}.`
+ } else if (rowShift.inserted_rows === 0) {
+ opening = `The page shrank by ${pluralize(rowShift.deleted_rows, 'row')}${where}.`
+ } else {
+ opening = `The page shifted by ${pluralize(shiftedRows(rowShift), 'row')}${where}.`
+ }
+ return (
+ `${opening} Rows below it moved, and after aligning them only ${formatResidual(rowShift.residual_percentage)} ` +
+ `of pixels differ, so this run was absorbed as noise. Without alignment it would have read as ` +
+ `${rowShift.raw_diff_percentage.toFixed(2)}% pixel diff.`
+ )
+}
+
+function layoutTooltip(rowShift: RowShiftApi): string {
+ const parts: string[] = []
+ if (rowShift.inserted_rows > 0) {
+ parts.push(`${pluralize(rowShift.inserted_rows, 'row')} added`)
+ }
+ if (rowShift.deleted_rows > 0) {
+ parts.push(`${pluralize(rowShift.deleted_rows, 'row')} removed`)
+ }
+ return (
+ `${parts.join(' and ')}${shiftPosition(rowShift)}. Content in the matched rows changed by ` +
+ `${formatResidual(rowShift.residual_percentage)} (residual).`
+ )
+}
+
+export interface ShiftDescription {
+ /** `neutral` for an absorbed shift, which needs no review; `warning` for a layout change. */
+ tone: 'neutral' | 'warning'
+ label: string
+ compactLabel: string
+ tooltip: string
+}
+
+/**
+ * The one description both the badge and its predicate render from, so the
+ * two cannot disagree about whether a snapshot has a shift worth showing.
+ *
+ * Chips speak pixels because that is the size of the move a person sees;
+ * tooltips and the sidebar speak rows with positions, which is what somebody
+ * chasing the cause needs. Returns null when nothing moved.
+ */
+export function describeShift(rowShift: RowShiftApi | null | undefined, absorbed: boolean): ShiftDescription | null {
+ if (!rowShift || shiftedRows(rowShift) === 0) {
+ return null
+ }
+ const px = signedShiftPx(rowShift)
+ if (absorbed) {
+ const magnitude = `${shiftedRows(rowShift)}px shift`
+ return {
+ tone: 'neutral',
+ label: `Absorbed ${magnitude}`,
+ compactLabel: magnitude,
+ tooltip: absorbedTooltip(rowShift),
+ }
+ }
+ return {
+ tone: 'warning',
+ label: `${px} Layout shift`,
+ compactLabel: px,
+ tooltip: layoutTooltip(rowShift),
+ }
+}
+
+/** One band, as the sidebar names it. */
+export function describeBand(band: ShiftBandApi): string {
+ const verb = band.kind === 'deleted' ? 'deleted' : 'inserted'
+ return `${pluralize(band.rows, 'row')} ${verb} at y=${band.y}`
+}
diff --git a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx
index 09e0905d4fc7..4a12f47f9a25 100644
--- a/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewRunScene.stories.tsx
@@ -41,7 +41,7 @@ const run: RunApi = {
pr_number: 42,
approved: false,
approved_at: null,
- summary: { total: 7, changed: 1, new: 1, removed: 0, unchanged: 5 },
+ summary: { total: 7, changed: 2, new: 1, removed: 0, unchanged: 4 },
error_message: null,
created_at: '2026-06-10T00:00:00Z',
completed_at: '2026-06-10T00:01:00Z',
@@ -65,7 +65,7 @@ const snapshot = (overrides: Partial<SnapshotApi>): SnapshotApi => ({
})
const snapshots = {
- count: 2,
+ count: 4,
next: null,
previous: null,
quarantined_count: 0,
@@ -85,6 +85,48 @@ const snapshots = {
diff_pixel_count: null,
current_artifact: artifact('curr_new'),
}),
+ // A panel grew by a row, so the page below it moved. Absorbed as
+ // noise, and the chip is the only trace the run leaves.
+ snapshot({
+ id: 'snapshot-absorbed-shift',
+ identifier: 'Components/Card--with-footer',
+ result: 'unchanged',
+ classification_reason: 'below_threshold',
+ diff_percentage: 0.03,
+ diff_pixel_count: 42,
+ baseline_artifact: artifact('base_absorbed'),
+ current_artifact: artifact('curr_absorbed'),
+ row_shift: {
+ inserted_rows: 1,
+ deleted_rows: 0,
+ residual_percentage: 0.001,
+ raw_diff_percentage: 2.4,
+ bands: [{ y: 60, rows: 1, kind: 'inserted' }],
+ },
+ }),
+ // A block appeared, so the shift is past the absorb cap and stays in review.
+ snapshot({
+ id: 'snapshot-layout-shift',
+ identifier: 'Components/Navigation--expanded',
+ result: 'changed',
+ change_kind: 'layout',
+ diff_percentage: 1.4,
+ diff_pixel_count: 896,
+ baseline_artifact: artifact('base_layout'),
+ current_artifact: artifact('curr_layout'),
+ row_shift: {
+ inserted_rows: 40,
+ deleted_rows: 12,
+ residual_percentage: 0.0,
+ raw_diff_percentage: 31.6,
+ bands: [
+ { y: 80, rows: 40, kind: 'inserted' },
+ // A deletion at the bottom edge. Its seam sits at the image
+ // height, so the viewer must clamp it back into frame.
+ { y: 200, rows: 12, kind: 'deleted' },
+ ],
+ },
+ }),
],
}
diff --git a/pyproject.toml b/pyproject.toml
index 0076294fb4fb..30fdda92316e 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -199,7 +199,7 @@ dependencies = [
"defusedxml~=0.7.1",
"confluent-kafka~=2.13",
"blake3>=1.0.8,<2",
- "pixelhog~=1.2.0",
+ "pixelhog~=1.3.0",
"google-re2>=1.1.20251105,<2",
"scrubadub~=2.0.1",
"braintrust-core>=0.0.59,<1",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 961caa7a57b6..62fd6813a718 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -58338,8 +58338,46 @@ export namespace Schemas {
results: SignalSourceConfig[];
}
+ /**
+ * * `inserted` - inserted
+ * * `deleted` - deleted
+ */
+ export type ShiftBandKindEnum = typeof ShiftBandKindEnum[keyof typeof ShiftBandKindEnum];
+
+
+ export const ShiftBandKindEnum = {
+ Inserted: 'inserted',
+ Deleted: 'deleted',
+ } as const;
+
+ export interface ShiftBand {
+ /** First row of the band, in current-image coordinates. */
+ y: number;
+ /** How many rows the band covers. */
+ rows: number;
+ /** 'inserted' when the current image gained these rows, 'deleted' when it lost them. A deleted band has no rows of its own in the current image, so its y is the seam the removed rows left behind.
+ *
+ * * `inserted` - inserted
+ * * `deleted` - deleted */
+ kind: ShiftBandKindEnum;
+ }
+
+ export interface RowShift {
+ /** Where the shift happened, in current-image coordinates. */
+ bands: ShiftBand[];
+ /** Rows the current image gained. */
+ inserted_rows: number;
+ /** Rows the current image lost. */
+ deleted_rows: number;
+ /** Percentage of pixels that differ inside the rows present in both images, 0 to 100. Excludes the shift itself. The stored diff_percentage adds the area of the rows the shift added or removed, and that combined number is what the pixel threshold judges. */
+ residual_percentage: number;
+ /** Percentage of pixels that differ without alignment, which is what the shift would have cost. */
+ raw_diff_percentage: number;
+ }
+
export interface SnapshotHistoryEntry {
current_artifact?: Artifact | null;
+ row_shift?: RowShift | null;
run_id: string;
snapshot_id: string;
result: string;
@@ -58374,6 +58412,7 @@ export namespace Schemas {
diff_artifact?: Artifact | null;
reviewed_by?: UserBasicInfo | null;
cluster_summary?: ClusterSummary | null;
+ row_shift?: RowShift | null;
id: string;
run_id: string;
identifier: string;
diff --git a/uv.lock b/uv.lock
index 279ca058dc20..5ac2505ca3f2 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5426,17 +5426,17 @@ wheels = [
[[package]]
name = "pixelhog"
-version = "1.2.0"
+version = "1.3.0"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/1f/5e/23e3cf43002b8e68e55da4b650b108909e6e38569170fc9c2611ddaf5dcf/pixelhog-1.2.0.tar.gz", hash = "sha256:919b9c3f90e89307ae1de816d7860cd3fa27a59e5e2da020f02953f30ebb56fd", size = 31973, upload-time = "2026-05-05T09:18:06.785Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/2e/d9/27e623a5d417b2142f45c44f22a7cee254eaa326601a2298df084e309616/pixelhog-1.3.0.tar.gz", hash = "sha256:dda5a6b0ac57b21d5045ac79ce29a5e71905c89465f48674a8392629133c20ae", size = 46544, upload-time = "2026-09-08T06:42:47.176Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/a1/3b/860c2e4cfe1a26fdfd5c19afb4ba649710a83a9a5d0bfcdd4111068aba3b/pixelhog-1.2.0-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:82b33e6cddc730dd08314aea688d0f3ac50f1f52439c5655378838ce41bf3710", size = 660795, upload-time = "2026-05-05T09:17:59.02Z" },
- { url = "https://files.pythonhosted.org/packages/1a/e0/9822760802dd572b837fb381fcba8274509d76532b151f0a49ed2ca250e2/pixelhog-1.2.0-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:f0488d22181b166871a149458cefc84d5c6bac74766898a35053dcb7c163f802", size = 648839, upload-time = "2026-05-05T09:17:57.43Z" },
- { url = "https://files.pythonhosted.org/packages/da/07/d142e38d7dc60a467b97ef8f1a92d61cb1909bb8ffb0e9c27bec55e61bb0/pixelhog-1.2.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2a2d70c505f17295b85a77c60c7fec8cee97a3c95100232cca2f86a5a590a579", size = 683699, upload-time = "2026-05-05T09:18:00.378Z" },
- { url = "https://files.pythonhosted.org/packages/79/7e/a04a4914a17774929d8fd1e0be0da71c1c310db14a0a37fbc33437a301f4/pixelhog-1.2.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:365834d17326109c63cf2da5204cb92ce84518798f9a5d08502331fe83dacb4d", size = 724161, upload-time = "2026-05-05T09:18:04.434Z" },
- { url = "https://files.pythonhosted.org/packages/73/07/da9179b7f0c9b118b9ae81a9a6d1849a2acbbdc86b9f6450ad05f0bdd8d2/pixelhog-1.2.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:05239693d9e5f844af52a082d082a8e191608f379257ce35bf5c197b52231970", size = 859951, upload-time = "2026-05-05T09:18:03.094Z" },
- { url = "https://files.pythonhosted.org/packages/27/c0/a5b1d61a18fcd060afda879fd95abb9f510d131e585cf477816c1f178ce4/pixelhog-1.2.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7ac96f4f9ee6c2505eb89412f6532e8cc9719ac730d1c156e30b22be878285cf", size = 916439, upload-time = "2026-05-05T09:18:01.65Z" },
- { url = "https://files.pythonhosted.org/packages/09/d2/c057e7c1a708ec91abd9071a068332adf5d92d064b49537c0fdf9164cfed/pixelhog-1.2.0-cp312-abi3-win_amd64.whl", hash = "sha256:3de6ddcea4cad183052a20f3d07d38ca23ff587bc7b6ffafdff1f98f914ca06b", size = 610639, upload-time = "2026-05-05T09:18:05.632Z" },
+ { url = "https://files.pythonhosted.org/packages/00/87/8227f1aa5d4b25923410868ce3328fd69789e7a521fb0ac2398833d6a9f5/pixelhog-1.3.0-cp312-abi3-macosx_10_12_x86_64.whl", hash = "sha256:fb7bf5ec5dd836ee629a552c760edd077799cd5db5dcfc1b684915eaaa056ecd", size = 682556, upload-time = "2026-09-08T06:42:37.269Z" },
+ { url = "https://files.pythonhosted.org/packages/2e/6e/40e854d6fb86273077d047559e04befc6ca5d39fb67c65a8fd1755264618/pixelhog-1.3.0-cp312-abi3-macosx_11_0_arm64.whl", hash = "sha256:92c2991132f1400b98d588c9c87db4b789af6e77e5ec4e79ea295cadc5baea96", size = 670510, upload-time = "2026-09-08T06:42:38.933Z" },
+ { url = "https://files.pythonhosted.org/packages/30/c1/5267264269c7bea81396cab580a971095a65a2900e3f865a77ef6f587a37/pixelhog-1.3.0-cp312-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0b9c0a13ba74dd9c2bf997805b8b4f5363a388485e644314dc19ed867111d66d", size = 703665, upload-time = "2026-09-08T06:42:40.197Z" },
+ { url = "https://files.pythonhosted.org/packages/05/f8/8680f0abd297423b13b89facedb41cb47bef470657233af76919f3ff1820/pixelhog-1.3.0-cp312-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:295705dc7d229cb2e5e8357fa73a6b1274a2d7b79ea82932eb5b98d251b04491", size = 752576, upload-time = "2026-09-08T06:42:41.547Z" },
+ { url = "https://files.pythonhosted.org/packages/de/fe/5eb670983f8b2e7b81dc8163b54873ed4e46077bafc8ac653365a66725f6/pixelhog-1.3.0-cp312-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:2cb7dd216e3b6d859f199db1a4507eab45d94a8fc1c346998909a34511906f6b", size = 881421, upload-time = "2026-09-08T06:42:42.791Z" },
+ { url = "https://files.pythonhosted.org/packages/ce/48/63c1616c3c1648505499cbdfea1c93c5d14083b2a9653ff2b4377f9741c4/pixelhog-1.3.0-cp312-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:6b67fc52acce409c7600dd1958e796bef2efd37d8b044af40bb4127e18c60558", size = 946987, upload-time = "2026-09-08T06:42:44.508Z" },
+ { url = "https://files.pythonhosted.org/packages/04/d6/2665bc86c5850e2c8348f2566e7434e05d31149c2004849d0c5342f24815/pixelhog-1.3.0-cp312-abi3-win_amd64.whl", hash = "sha256:f76882d96890f6764f7f2d94e61403a595781be9839e41d009b03bacefe9764c", size = 637511, upload-time = "2026-09-08T06:42:45.951Z" },
]
[[package]]
@@ -5957,7 +5957,7 @@ requires-dist = [
{ name = "pandas", specifier = "~=2.2.2" },
{ name = "paramiko", specifier = "~=3.5.0" },
{ name = "pillow", specifier = "==12.3.0" },
- { name = "pixelhog", specifier = "~=1.2.0" },
+ { name = "pixelhog", specifier = "~=1.3.0" },
{ name = "playwright", specifier = "~=1.60.0" },
{ name = "polars", specifier = "==1.37.1" },
{ name = "posthog-hogland", specifier = "==0.4.1" },