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.

fix(visual-review): count digest pile-ups across baselines in a 30-day window (#104246)

Julian Bez318407d4b64a
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index c23a9a16dded..27a2fe7c51fa 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -55,7 +55,7 @@ The lead names the team and the week, and counts each condition that has items,
Under it, one thread reply per condition that has items: a line saying what to do about that condition, then one section per item with the single action that resolves it on a button beside it.
Theme variants of one story list as one entry when the reader would see the same facts for each.
A merged expiring quarantine links to the flakiness page searched to that story, and a merged unowned file keeps its file button.
-Pile-ups never merge, because a baseline resets one snapshot at a time.
+Pile-ups never merge, because each theme variant carries its own toleration count.
The last reply says when the next digest comes.
A team that owns nothing gets no message at all.
@@ -66,15 +66,14 @@ Two conditions, and nothing else:
The extra day is overlap: two weekly runs can fall slightly more than seven days apart, and a quarantine expiring in that gap would otherwise never be reported.
The flakiness page keeps the plain seven days.
It clears when somebody extends it past the window, lifts it, or lets it lapse.
-- **N accepted variants of the current baseline.**
- `VARIANT_PILEUP_MIN` or more active intentional tolerations recorded against the hash the baseline currently holds, with no quarantine already covering the identity.
- This is not the ninety-day tolerated count on the baselines page, which measures how often somebody accepted drift in a window.
- This count has no window, because an accepted variant keeps matching without a new record.
- It clears when the tolerations are removed, or when the baseline changes.
-
-A baseline change invalidates the tolerations recorded against the old baseline: they can never match again, so the count drops to zero.
-That is not evidence the story recovered.
-Reminders about retained exceptions repeat until they are removed or no longer apply.
+- **Tolerated N times in 30 days.**
+ `VARIANT_PILEUP_MIN` or more tolerations by a person or agent in the last `TOLERATION_PILEUP_WINDOW_DAYS`, with no quarantine already covering the identity.
+ It matches the manual half of the rule the Tolerate dialog uses to suggest a quarantine.
+ The count spans every baseline.
+ A flaky story's baseline often moves between tolerations, and a count scoped to the current baseline would drop to zero at each move while the tolerations go on.
+ Automatic tolerations do not count: they absorb renderings under the diff thresholds, which never block anybody.
+ It clears when the tolerations age out of the window.
+ Reminders about retained exceptions repeat until they are removed or no longer apply.
Attribution runs through the story index of the newest default-branch Storybook run, and then through `owners.yaml`.
`vr run upload --storybook-index <index.json> --storybook-root <dir>` turns the build's `index.json` into a story-to-file map, and each default-branch run records the map's SHA-256 in `metadata["story_index_hash"]`.
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index 2b5740635f5c..eb8124230c7b 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -521,6 +521,11 @@ BASELINE_DRIFT_RECENT_RUN_COUNT = 10
# "the baseline" means for that snapshot, and the same floor the frequently-tolerated stat uses.
VARIANT_PILEUP_MIN = 3
+# Rolling window for counting a snapshot's tolerations across baselines. The debt digest flags
+# `VARIANT_PILEUP_MIN` intentional tolerations in this window. The Tolerate dialog's quarantine
+# suggestion in the frontend (`lib/quarantineNudge.ts`) uses the same window and floor.
+TOLERATION_PILEUP_WINDOW_DAYS = 30
+
@dataclass(frozen=True)
class BaselineQuarantineSummary:
diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.py
index b3aa6804fba6..aeec2ebe1484 100644
--- a/products/visual_review/backend/logic/debt_digest.py
+++ b/products/visual_review/backend/logic/debt_digest.py
@@ -12,13 +12,15 @@ The two conditions:
a day of overlap so two weekly runs cannot skip one. Somebody has to extend it, lift it, or decide
to let it lapse.
- Variant pile-up. `VARIANT_PILEUP_MIN` or more accepted variants standing against the baseline's
- current hash, with no quarantine already covering the identity. The baseline has stopped
- describing one rendering.
+ Toleration pile-up. `VARIANT_PILEUP_MIN` or more tolerations by a person or agent in the last
+ `TOLERATION_PILEUP_WINDOW_DAYS`, with no quarantine already covering the identity. Each toleration
+ covers one exact rendering, so a snapshot that keeps needing them renders differently from run to
+ run, and the fix is in the story.
-A baseline change clears the second condition, and that is not the same as the story recovering: it
-invalidates the tolerations recorded against the old baseline, because they can never match again.
-Nothing here claims a snapshot got better.
+The pile-up counts across baselines. A flaky story's baseline often moves between tolerations, and
+a count scoped to the current baseline drops to zero at every move while the tolerations go on.
+Automatic tolerations do not count: they absorb renderings under the diff thresholds, which never
+block anybody.
Attribution runs through the Storybook build behind the current baseline. Its story index names the
file each story lives in, and the repository's own ownership files name the team that owns that file.
@@ -78,7 +80,7 @@ from posthog.utils import human_list, pluralize
from products.engineering_analytics.backend.facade.api import resolve_path_owners
from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
-from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, VARIANT_PILEUP_MIN
+from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, TOLERATION_PILEUP_WINDOW_DAYS, VARIANT_PILEUP_MIN
from ..facade.enums import RunType
from ..models import QuarantinedIdentifier, Repo, Run
from . import quarantine, run_queries, story_index, toleration
@@ -123,9 +125,9 @@ _QUARANTINE_HEADING = (
"A lapsed quarantine fails the gate again."
)
_PILEUP_HEADING = (
- "*Snapshots with piled-up variants*\n"
- f"{VARIANT_PILEUP_MIN} or more accepted renderings mean the baseline is wrong. "
- "Approve the current rendering as the baseline and the variants stop counting."
+ "*Snapshots that keep getting tolerated*\n"
+ "A toleration covers one exact rendering, so these snapshots render differently from run to run. "
+ "Fix the story, or quarantine it until someone can."
)
@@ -355,7 +357,7 @@ def _quarantine_facts(entry: QuarantinedIdentifier, authors: dict[int, str], now
def _pileup_facts(count: int) -> str:
- return f"*{count}* accepted variants of the current baseline"
+ return f"Tolerated *{count}* times in the last {TOLERATION_PILEUP_WINDOW_DAYS} days"
def _quarantine_line(repo: Repo, entry: QuarantinedIdentifier, authors: dict[int, str], now: datetime) -> str:
@@ -372,7 +374,7 @@ def _quarantine_line(repo: Repo, entry: QuarantinedIdentifier, authors: dict[int
def _pileup_line(repo: Repo, run_type: str, identifier: str, count: int) -> str:
body = (
- f"{count} accepted variants of the current baseline"
+ f"Tolerated {count} times in {TOLERATION_PILEUP_WINDOW_DAYS} days"
f" · {escape_slack_mrkdwn(clip_text(identifier, _MAX_IDENTIFIER_CHARS))} ({escape_slack_mrkdwn(run_type)})"
)
return _linked_line(repo, body, run_type, identifier)
@@ -422,11 +424,11 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:
quarantined_keys = quarantine.active_quarantine_keys(repo.id, now=now)
piled_up = {
key: count
- for key, count in toleration.count_active_variants_against_current_baseline(
- repo.id, now=now, newest_run_by_type=newest_run_by_type
+ for key, count in toleration.count_recent_intentional_tolerations(
+ repo.id, since=now - timedelta(days=TOLERATION_PILEUP_WINDOW_DAYS), newest_run_by_type=newest_run_by_type
).items()
# Any live quarantine, expiring or not, already says somebody knows the snapshot is
- # unreliable, so asking them about the variants underneath it is a second reminder about
+ # unreliable, so asking them about the tolerations underneath it is a second reminder about
# one problem.
if count >= VARIANT_PILEUP_MIN and key not in quarantined_keys
}
@@ -657,7 +659,9 @@ def _count_phrases(digest: TeamDigest, emphasis: str = "") -> list[str]:
)
pileups = len(digest.variant_pileups)
if pileups:
- phrases.append(f"{emphasis}{pluralize(pileups, 'snapshot')}{emphasis} with piled-up variants")
+ phrases.append(
+ f"{emphasis}{pluralize(pileups, 'snapshot')}{emphasis} keep{'s' if pileups == 1 else ''} getting tolerated"
+ )
return phrases
@@ -701,7 +705,7 @@ def thread_messages(repo: Repo, digest: TeamDigest, now: datetime) -> list[Slack
),
ReplyGroup(
heading=_heading_part(_PILEUP_HEADING),
- items=[_item_part(repo, item, "Reset baseline") for item in digest.variant_pileups],
+ items=[_item_part(repo, item, "Fix or quarantine") for item in digest.variant_pileups],
),
]
return _split_into_messages(groups, _footer_parts(now))
diff --git a/products/visual_review/backend/logic/toleration.py b/products/visual_review/backend/logic/toleration.py
index fafa25d36b36..56ba4f66a853 100644
--- a/products/visual_review/backend/logic/toleration.py
+++ b/products/visual_review/backend/logic/toleration.py
@@ -137,6 +137,47 @@ def count_active_variants_against_current_baseline(
return counts
+def count_recent_intentional_tolerations(
+ repo_id: UUID, *, since: datetime, newest_run_by_type: Mapping[str, Run] | None = None
+) -> dict[SnapshotKey, int]:
+ """How many tolerations a person or agent recorded for each snapshot identity since `since`,
+ across every baseline.
+
+ The count survives a baseline change, unlike `count_active_variants_against_current_baseline`.
+ A flaky story's baseline often moves between tolerations, so a per-baseline count keeps
+ dropping to zero while the tolerations go on.
+
+ Only identities on the newest default-branch runs are counted, so a deleted story drops out.
+ A toleration row has no run type of its own, so it takes the run type of the run it was
+ decided in. A row whose run the retention sweep already deleted counts for every run type
+ that has the identifier. Only non-zero counts are returned.
+ """
+ baseline_hash_by_key = _current_baseline_hashes(repo_id, newest_run_by_type)
+ if not baseline_hash_by_key:
+ return {}
+
+ keys_by_identifier: dict[str, list[SnapshotKey]] = {}
+ for key in baseline_hash_by_key:
+ keys_by_identifier.setdefault(key.identifier, []).append(key)
+
+ counts: dict[SnapshotKey, int] = {}
+ for identifier, run_type, count in (
+ ToleratedHash.objects.filter(
+ repo_id=repo_id,
+ identifier__in=list(keys_by_identifier),
+ reason__in=INTENTIONAL_TOLERATE_REASONS,
+ created_at__gte=since,
+ )
+ .values_list("identifier", "source_run__run_type")
+ .annotate(c=Count("id"))
+ .values_list("identifier", "source_run__run_type", "c")
+ ):
+ for key in keys_by_identifier[identifier]:
+ if run_type in (None, key.run_type):
+ counts[key] = counts.get(key, 0) + count
+ return counts
+
+
def _current_baseline_hashes(
repo_id: UUID, newest_run_by_type: Mapping[str, Run] | None = None
) -> dict[SnapshotKey, str]:
diff --git a/products/visual_review/backend/tests/logic/test_debt_digest.py b/products/visual_review/backend/tests/logic/test_debt_digest.py
index 2b1692bf7ee9..e25210027275 100644
--- a/products/visual_review/backend/tests/logic/test_debt_digest.py
+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py
@@ -22,12 +22,13 @@ from posthog.team_notifications.slack import (
from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
from products.visual_review.backend.facade.contracts import (
FLAKINESS_EXPIRY_SOON_DAYS,
+ TOLERATION_PILEUP_WINDOW_DAYS,
CreateRunInput,
SnapshotManifestItem,
)
from products.visual_review.backend.facade.enums import RunType
from products.visual_review.backend.logic import artifact_store, debt_digest, quarantine, repos, runs, story_index
-from products.visual_review.backend.models import ToleratedHash
+from products.visual_review.backend.models import Run, ToleratedHash
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
_PRODUCT_PATH = "products/visual_review/"
@@ -63,7 +64,7 @@ def _item(
attribution: debt_digest.Attribution,
identifier: str = _IDENTIFIER,
line: str = "a line",
- facts: str = "*3* accepted variants of the current baseline",
+ facts: str = "Tolerated *3* times in the last 30 days",
) -> debt_digest.DebtItem:
return debt_digest.DebtItem(
identifier=identifier, run_type="storybook", attribution=attribution, line=line, facts=facts
@@ -105,8 +106,8 @@ class TestLead:
"expiring,pileups,fields,mentions_lapse",
[
(1, 0, ["*1 quarantine* expires soon"], True),
- (0, 2, ["*2 snapshots* with piled-up variants"], False),
- (3, 1, ["*3 quarantines* expire soon", "*1 snapshot* with piled-up variants"], True),
+ (0, 2, ["*2 snapshots* keep getting tolerated"], False),
+ (3, 1, ["*3 quarantines* expire soon", "*1 snapshot* keeps getting tolerated"], True),
],
)
def test_the_lead_names_the_team_and_counts_only_the_conditions_it_has(
@@ -137,7 +138,7 @@ class TestLead:
assert message.text == (
"Visual review debt for team-devex in PostHog/posthog: 1 quarantine expires soon, "
- "2 snapshots with piled-up variants."
+ "2 snapshots keep getting tolerated."
)
@@ -146,8 +147,8 @@ class TestThreadReplies:
"expiring,pileups,headings",
[
(1, 0, ["*Quarantines expiring soon*"]),
- (0, 1, ["*Snapshots with piled-up variants*"]),
- (2, 2, ["*Quarantines expiring soon*", "*Snapshots with piled-up variants*"]),
+ (0, 1, ["*Snapshots that keep getting tolerated*"]),
+ (2, 2, ["*Quarantines expiring soon*", "*Snapshots that keep getting tolerated*"]),
],
)
def test_one_reply_per_condition_that_has_items(self, expiring: int, pileups: int, headings: list[str]) -> None:
@@ -159,7 +160,7 @@ class TestThreadReplies:
messages = debt_digest.thread_messages(_repo(), _team_digest(expiring=1, pileups=1), _MONDAY)
buttons = _all_buttons(messages)
- assert [button["text"]["text"] for button in buttons] == ["Extend or fix", "Reset baseline"]
+ assert [button["text"]["text"] for button in buttons] == ["Extend or fix", "Fix or quarantine"]
assert all(
button["url"] == f"{settings.SITE_URL}/project/7/visual_review/repos/abc/storybook/snapshots/{_IDENTIFIER}"
for button in buttons
@@ -366,7 +367,7 @@ class TestRendering:
def test_links_to_the_snapshot_page_with_encoded_segments(self) -> None:
line = debt_digest._pileup_line(_repo(), "storybook", "scenes/Button--dark", 4)
- assert line.startswith("4 accepted variants of the current baseline · scenes/Button--dark (storybook)")
+ assert line.startswith("Tolerated 4 times in 30 days · scenes/Button--dark (storybook)")
assert line.endswith("/project/7/visual_review/repos/abc/storybook/snapshots/scenes%2FButton--dark")
@pytest.mark.parametrize(
@@ -513,16 +514,58 @@ class TestCollectAndSend:
runs.finish_processing(run.id)
return run
- def _pile_up(self, repo, identifier=_IDENTIFIER, count=3):
- for index in range(count):
+ def _pile_up(
+ self,
+ repo,
+ identifier=_IDENTIFIER,
+ baseline_hashes=("old_hash",) * 3,
+ reason="human",
+ age=None,
+ source_run_type=None,
+ ):
+ source_run = (
+ Run.objects.create(
+ repo=repo, team_id=repo.team_id, run_type=source_run_type, commit_sha="def", branch="feature"
+ )
+ if source_run_type
+ else None
+ )
+ for index, baseline_hash in enumerate(baseline_hashes):
ToleratedHash.objects.create(
repo=repo,
team_id=repo.team_id,
identifier=identifier,
- baseline_hash="old_hash",
+ baseline_hash=baseline_hash,
alternate_hash=f"variant_{index}",
- reason="human",
+ reason=reason,
+ source_run=source_run,
)
+ if age is not None:
+ # created_at is auto_now_add, so backdating takes a second write.
+ ToleratedHash.objects.filter(repo=repo, identifier=identifier).update(created_at=timezone.now() - age)
+
+ @pytest.mark.parametrize(
+ "baseline_hashes,reason,age,source_run_type,expected",
+ [
+ (("older_hash", "old_hash", "old_hash"), "human", timedelta(days=1), None, [_IDENTIFIER]),
+ (("old_hash",) * 3, "agent", timedelta(days=1), None, [_IDENTIFIER]),
+ (("old_hash",) * 3, "human", timedelta(days=TOLERATION_PILEUP_WINDOW_DAYS + 1), None, []),
+ (("old_hash",) * 3, "auto_threshold", timedelta(days=1), None, []),
+ (("old_hash",) * 2, "human", timedelta(days=1), None, []),
+ (("old_hash",) * 3, "human", timedelta(days=1), RunType.STORYBOOK, [_IDENTIFIER]),
+ (("old_hash",) * 3, "human", timedelta(days=1), RunType.PLAYWRIGHT, []),
+ ],
+ )
+ def test_a_pile_up_counts_recent_intentional_tolerations_across_baselines(
+ self, repo, mocker, baseline_hashes, reason, age, source_run_type, expected
+ ):
+ self._completed_run(repo, mocker)
+ self._pile_up(repo, baseline_hashes=baseline_hashes, reason=reason, age=age, source_run_type=source_run_type)
+
+ with _with_index(_INDEX):
+ debt = debt_digest.collect_debt(repo, timezone.now())
+
+ assert [item.identifier for item in debt.variant_pileups] == expected
def test_collects_both_conditions_and_names_the_story_file(self, repo, team, user, mocker):
self._completed_run(repo, mocker)
@@ -546,7 +589,7 @@ class TestCollectAndSend:
assert [(item.identifier, item.attribution) for item in debt.expiring_quarantines] == [
(_ABSENT_IDENTIFIER, _STORY_ABSENT)
]
- assert "3 accepted variants of the current baseline" in debt.variant_pileups[0].line
+ assert "Tolerated 3 times in 30 days" in debt.variant_pileups[0].line
def test_an_unreadable_story_index_leaves_the_items_unattributed(self, repo, mocker):
self._completed_run(repo, mocker)
@@ -633,7 +676,7 @@ class TestCollectAndSend:
assert len(rendered) == 1
# Preview prints the plain text behind every message, so a by-hand run reads without Slack.
assert rendered[0].startswith("Visual review debt for team-devex in org/test-debt: ")
- assert "3 accepted variants of the current baseline" in rendered[0]
+ assert "Tolerated 3 times in 30 days" in rendered[0]
assert rendered[0].rstrip().split("\n")[-1].startswith("Next digest Monday, ")
def test_an_unreadable_owners_file_sends_nothing(self, repo, mocker):