: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(visual-review): send a daily debt digest to owning teams (#98982)
Julian Bez15a46a2c7e2d
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 8c073e78208c..3cc820910552 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -126,7 +126,7 @@ from products.tasks.backend.facade.tasks import (sweep_inactive_tasks_task,sweep_loop_task_retention_task,)-from products.visual_review.backend.facade.tasks import sweep_visual_review_retention+from products.visual_review.backend.facade.tasks import send_visual_review_debt_digests, sweep_visual_review_retentionfrom products.warehouse_sources.backend.facade.tasks import sweep_stopped_schema_syncsfrom products.web_analytics.backend.achievements.tasks import sweep_web_analytics_achievement_team_tracksfrom products.web_analytics.backend.tasks.heatmap_screenshot import (@@ -1082,6 +1082,14 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="sweep visual review retention",)+ add_periodic_task_with_expiry(+ sender,+ crontab(hour="7", minute="30"),+ send_visual_review_debt_digests.s(),+ name="send visual review debt digests",+ expires_seconds=60 * 60,+ )+sender.add_periodic_task(TEST_CENSUS_CRONTAB,emit_test_ownership_census.s(),diff --git a/posthog/team_notifications/slack.py b/posthog/team_notifications/slack.pyindex c1afa2013dfa..58aeaf571ce4 100644--- a/posthog/team_notifications/slack.py+++ b/posthog/team_notifications/slack.py@@ -1,8 +1,8 @@"""Find a team's Slack channel by name, and post an automated message into it.-The two pieces every product that posts a routed digest needs, and nothing else. Which channel a-team's message belongs in, what the message says, and what a failed post does to the product's own-records all stay with the product.+What every product that posts a routed digest needs: which channel a team's message belongs in, the+limits Slack puts on a message, and what a refused post says. What the message says, and what a+failure does to the product's own records, stay with the product."""from __future__ import annotations@@ -19,6 +19,23 @@ from posthog.models.integration import Integration, SlackIntegrationlogger = structlog.get_logger(__name__)+# Slack rejects a section block over 3000 characters. The margin covers the mrkdwn escaping, which+# can turn one character into five.+MAX_SECTION_CHARS = 2900+++def clip_text(text: str, limit: int) -> str:+ """Cut display text down to `limit` characters, marking that something was cut."""+ if len(text) <= limit:+ return text+ return text[: max(limit - 1, 0)] + "…"+++def section_block(text: str) -> list[dict]:+ """One mrkdwn section, in the block list a post takes."""+ return [{"type": "section", "text": {"type": "mrkdwn", "text": text}}]++# Slack channel flags that mark a channel as shared beyond this workspace. A caller that maps a team# name onto a Slack channel by name can land on a shared channel carrying that name, which sends an# internal message outside the workspace. is_ext_shared and is_pending_ext_shared cover live anddiff --git a/posthog/team_notifications/test/test_slack.py b/posthog/team_notifications/test/test_slack.pyindex 43ab980bda8c..496037134e3a 100644--- a/posthog/team_notifications/test/test_slack.py+++ b/posthog/team_notifications/test/test_slack.py@@ -2,7 +2,7 @@ from django.test import SimpleTestCasefrom parameterized import parameterized-from posthog.team_notifications.slack import SlackChannel, find_channel+from posthog.team_notifications.slack import SlackChannel, clip_text, find_channel_TEAM_CHANNEL = SlackChannel(channel_id="C1", shared=False)_SHARED_CHANNEL = SlackChannel(channel_id="C2", shared=True)@@ -25,3 +25,16 @@ class TestFindChannel(SimpleTestCase):match = find_channel(_CHANNELS, channel_name, allow_shared=allow_shared)self.assertEqual((match.channel, match.reason), (channel, reason))+++class TestClipText(SimpleTestCase):+ @parameterized.expand(+ [+ ("shorter_than_the_limit_is_untouched", "one line", 20, "one line"),+ ("exactly_the_limit_is_untouched", "one line", 8, "one line"),+ ("over_the_limit_is_cut_to_the_limit", "one line", 4, "one…"),+ ("a_limit_of_zero_keeps_no_text", "one line", 0, "…"),+ ]+ )+ def test_clip(self, _name: str, text: str, limit: int, expected: str) -> None:+ self.assertEqual(clip_text(text, limit), expected)diff --git a/products/engineering_analytics/backend/facade/api.py b/products/engineering_analytics/backend/facade/api.pyindex 7780392799e8..72320796f56c 100644--- a/products/engineering_analytics/backend/facade/api.py+++ b/products/engineering_analytics/backend/facade/api.py@@ -18,6 +18,7 @@ then delegates to the read layer — source selection and access control live innot in the query builders below it."""+from collections.abc import Sequencefrom typing import TYPE_CHECKINGfrom posthog.models.team import Team@@ -36,6 +37,7 @@ from products.engineering_analytics.backend.facade.contracts import (GitHubSource,MasterFailureGroup,MergedPullRequest,+ PathOwnership,PRCostSummary,PRLifecycle,PullRequestList,@@ -624,3 +626,13 @@ def list_job_aggregates(branch=branch,run_scope=run_scope,)+++def resolve_path_owners(repository: str, paths: Sequence[str]) -> PathOwnership:+ """Name the team that owns each repository path, from the repository's own ownership files.++ No team parameter: the answer comes from the repository as it stands on its default branch, not+ from anything this PostHog team stores. Callers outside this product reach it here so the fetch,+ the cache, and the failure contract stay in one place.+ """+ return logic.resolve_path_owners(repository, paths)diff --git a/products/engineering_analytics/backend/facade/contracts.py b/products/engineering_analytics/backend/facade/contracts.pyindex ef7b37d1795e..f9740df2b212 100644--- a/products/engineering_analytics/backend/facade/contracts.py+++ b/products/engineering_analytics/backend/facade/contracts.py@@ -21,10 +21,12 @@ read layer maps them into these types. Reviewers and file paths areintentionally absent until the warehouse data that backs them lands."""+from collections.abc import Mappingfrom dataclasses import fieldfrom datetime import date, datetimefrom enum import StrEnum+from posthog_owners.schema import TeamEntryfrom pydantic.dataclasses import dataclassfrom posthog.hogql.database.models import FieldOrTable@@ -1547,3 +1549,20 @@ class WorkflowJobAggregate:retry_job_count: intbillable_minutes: float | Noneestimated_cost_usd: float | None+++@dataclass(frozen=True)+class PathOwnership:+ """Which team owns each of a set of repository paths, plus the repo's Slack registry.++ The registry rides along because the caller that asks who owns a path usually has to reach+ that team next, and the root ``owners.yaml`` answers both questions in one read.++ ``resolved`` is false when the ownership files could not be read, which leaves every path+ ``UNOWNED_TEAM`` and the registry empty. A caller that says so beats one that reads the blind+ answer as "nobody owns this".+ """++ team_by_path: Mapping[str, str]+ registry: Mapping[str, TeamEntry]+ resolved: booldiff --git a/products/engineering_analytics/backend/logic/__init__.py b/products/engineering_analytics/backend/logic/__init__.pyindex 1e45470efca9..b4e5952e89d5 100644--- a/products/engineering_analytics/backend/logic/__init__.py+++ b/products/engineering_analytics/backend/logic/__init__.py@@ -22,6 +22,7 @@ from products.engineering_analytics.backend.logic.dora import (build_dora_overview as build_dora_overview,get_dora_environment_choices as get_dora_environment_choices,)+from products.engineering_analytics.backend.logic.ownership import resolve_path_owners as resolve_path_ownersfrom products.engineering_analytics.backend.logic.pull_requests import (build_author_workflow_costs as build_author_workflow_costs,build_ci_cards as build_ci_cards,diff --git a/products/engineering_analytics/backend/logic/ownership.py b/products/engineering_analytics/backend/logic/ownership.pyindex 2f7d4e7904ba..d470300c03b1 100644--- a/products/engineering_analytics/backend/logic/ownership.py+++ b/products/engineering_analytics/backend/logic/ownership.py@@ -6,7 +6,7 @@ files are fetched and cached."""import random-from collections.abc import Callable, Iterable+from collections.abc import Callable, Iterable, Sequencefrom concurrent.futures import ThreadPoolExecutorfrom http import HTTPStatusfrom time import monotonic@@ -18,13 +18,14 @@ import requestsimport structlogfrom posthog_owners import OwnershipSource, OwnersResolverfrom posthog_owners.matcher import normalize_path+from posthog_owners.resolver import teams_registryfrom requests.adapters import HTTPAdapterfrom posthog.dataclasses import frozenfrom posthog.egress.github.transport import github_requestfrom posthog.models.integration.github import _is_safe_github_repo_path-from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnershiplogger = structlog.get_logger(__name__)@@ -210,6 +211,35 @@ def resolve_test_ownership(return RepoOwnershipResult(tests=[UNPLACED] * len(tests), resolved=False)+def resolve_path_owners(repository: str, paths: Sequence[str], files: RepoFiles | None = None) -> PathOwnership:+ """Name the team that owns each repository path, and hand back the repo's Slack registry.++ The paths are resolved exactly as given. There is no candidate-path search: that exists because+ a test suite reports a path relative to its own root, and a caller who already holds a+ repo-relative path has nothing to guess at.+ """+ reader = files if files is not None else GitHubRepoFiles(repository)+ try:+ return _own_paths(repository, reader, list(dict.fromkeys(paths)))+ except OwnershipUnavailable:+ logger.exception("repo_path_ownership_unavailable", repository=repository)+ return PathOwnership(team_by_path=dict.fromkeys(paths, UNOWNED_TEAM), registry={}, resolved=False)+++def _own_paths(repository: str, files: RepoFiles, paths: list[str]) -> PathOwnership:+ root = files.read(_ROOT_OWNERS_FILE)+ if root is None:+ raise OwnershipUnavailable(f"{repository} has no root {_ROOT_OWNERS_FILE}")+ resolver = OwnersResolver(source=files)+ files.read_all(resolver.ownership_file_paths(paths))+ owners = resolver.map(paths)+ return PathOwnership(+ team_by_path={path: _team(owners[path].owners) for path in paths},+ registry=teams_registry(root),+ resolved=True,+ )++def _place(repository: str, files: RepoFiles, tests: list[QuarantinedTestFile]) -> list[PlacedTest]:if files.read(_ROOT_OWNERS_FILE) is None:# Every repo this runs against declares one, so its absence proves the reader is blinddiff --git a/products/engineering_analytics/backend/tests/test_ownership.py b/products/engineering_analytics/backend/tests/test_ownership.pyindex b3ea56f69323..a2aa62e2e371 100644--- a/products/engineering_analytics/backend/tests/test_ownership.py+++ b/products/engineering_analytics/backend/tests/test_ownership.py@@ -19,11 +19,19 @@ from products.engineering_analytics.backend.logic.ownership import (OwnershipUnavailable,PlacedTest,QuarantinedTestFile,+ resolve_path_owners,resolve_test_ownership,)+_ROOT_OWNERS = """version: 1+owners: [team-root]+teams:+ team-ingestion:+ notifications: '#alerts-ingestion'+"""+_OWNERS = {- "owners.yaml": "version: 1\nowners: [team-root]\n",+ "owners.yaml": _ROOT_OWNERS,"nodejs/src/owners.yaml": "version: 1\nowners: [team-ingestion]\n","frontend/src/scenes/owners.yaml": "version: 1\nowners: [team-product-analytics]\n","rust/owners.yaml": "version: 1\nowners: [team-rust]\n",@@ -115,6 +123,27 @@ class TestRepoOwnership(SimpleTestCase):assert resolve_test_ownership("PostHog/posthog", [], files=_FakeRepoFiles()).resolved+class TestPathOwnership(SimpleTestCase):+ def test_places_each_path_exactly_and_returns_the_registry(self) -> None:+ # Exact resolution, not the suite-root search: 'src/...' is a real repo-relative path here+ # and must not be repositioned under nodejs/ the way a reported test path is.+ owned = resolve_path_owners(+ "PostHog/posthog",+ ["nodejs/src/cdp/worker.ts", "src/cdp/worker.ts"],+ files=_FakeRepoFiles(),+ )+ assert owned.resolved+ assert owned.team_by_path == {"nodejs/src/cdp/worker.ts": "team-ingestion", "src/cdp/worker.ts": "team-root"}+ assert owned.registry["team-ingestion"].notifications == "#alerts-ingestion"++ def test_an_unreadable_repository_owns_nothing_and_says_so(self) -> None:+ no_root = _FakeRepoFiles(owners={k: v for k, v in _OWNERS.items() if k != "owners.yaml"})+ owned = resolve_path_owners("PostHog/posthog", ["nodejs/src/cdp/worker.ts"], files=no_root)+ assert not owned.resolved+ assert owned.team_by_path == {"nodejs/src/cdp/worker.ts": UNOWNED_TEAM}+ assert owned.registry == {}++class TestGitHubRepoFiles(SimpleTestCase):def setUp(self) -> None:cache.clear()diff --git a/products/visual_review/README.md b/products/visual_review/README.mdindex 7eb4d0bb80a1..f9b616ab4041 100644--- a/products/visual_review/README.md+++ b/products/visual_review/README.md@@ -41,6 +41,59 @@ The windows and the reasons behind them are constants in `backend/logic/retentioAn artifact row is what makes the CLI skip an upload, so a row without its object is the one state to avoid; a leaked object only costs storage.- Each invocation is capped by rows and by a time budget, so a backlog drains over days.+### Daily debt digest++A daily Celery task, `send visual review debt digests`, posts each team a Slack reminder about the visual review debt it still carries.+The digest is stateless: every morning both conditions below are evaluated from current data, and nothing is stored about what was sent.+An item repeats every day while it stands, and stops the day the condition no longer holds.++Two conditions, and nothing else:++- **Quarantine expiring.**+ An active quarantine that runs out inside `FLAKINESS_EXPIRY_SOON_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.++Attribution runs through the Storybook build behind the current baseline, and then through `owners.yaml`.+The build uploads its story index as a GitHub Actions artifact, so the digest reads the artifact of the workflow run recorded on that baseline run (`metadata["github_run_id"]`), and the index names the file each story lives in.+A snapshot identifier is a story id plus the theme, the browser when it is not chromium, and the viewport width for a story that snapshots several.+The full story id is looked up first and the width suffix is only stripped when that misses, because a story can be named after a width.+The parsed index is cached per repository and workflow run for two days, and the key rotates on its own whenever the baseline moves.+Nothing is guessed from the identifier: a story name is not a path.+Only Storybook runs are attributed today.++Three outcomes have no owning team, and the digest keeps them apart:++- **Nobody owns the file.** The story maps to a file, and no owners entry covers it. Add one for the path, which stays on the line.+- **The story is not in the index.** It moved, was renamed, was deleted, or it only exists on a branch.+- **Ownership could not be worked out.** The artifact was missing or expired, the download failed, the team has no GitHub integration, or the run type is not supported yet.++All three go to whoever owns `products/visual_review/`, in a triage part of that team's digest kept separate from the items those maintainers own.+Holding an item until a team takes it is not owning it, and the wording says so.+A missing artifact never turns the digest into "nobody owns this": the items still go out, and the lead says ownership is worked out again tomorrow.+When nobody owns `products/visual_review/` either, the items are logged and dropped rather than posted somewhere arbitrary.+The artifact is kept for one day, which is enough for a daily read of a moving baseline.+A baseline that has not moved for longer reads as ownership could not be worked out, and the digest says so instead of guessing.++Routing goes to the team's `notifications` channel in the repository's root `owners.yaml` registry, under the `visual_review` producer.+A team opts out with `notifications: {visual_review: false}` under its entry.+A shared Slack channel is refused, so a name match never carries an internal reminder out of the workspace.++There is nothing to configure.+The daily beat task runs the digest for every repository, and a repository that owes nothing posts nothing.++`./manage.py visual_review_debt_digest --repo owner/name [--mode preview]` runs one repository by hand.+`--mode preview`, the default, renders every team's message and logs it without posting.+`--mode live` posts.+## The flow### Single-command flow (`vr submit`)diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex ea4f90cf6859..85ce9c37cd6d 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -319,9 +319,9 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:run = snapshot.runartifact = snapshot.current_artifactthumbnail = artifact.thumbnail if artifact is not None else None- # `(run_type, identifier)` keys because the same identifier in- # different run types is a different baseline.- key = (run.run_type, identifier)+ # Keyed per identity because the same identifier in different run types+ # is a different baseline.+ key = run_queries.SnapshotKey(run_type=run.run_type, identifier=identifier)metadata = snapshot.metadata or {}active_quarantine = raw.active_quarantines_by_key.get(key)entries.append(@@ -334,6 +334,7 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:height=artifact.height if artifact is not None else None,tolerate_count_30d=raw.tolerate_30d_by_id.get(identifier, 0),tolerate_count_90d=raw.tolerate_90d_by_id.get(identifier, 0),+ active_variants_current_baseline=raw.active_variants_by_key.get(key, 0),is_quarantined=active_quarantine is not None,last_run_at=run.completed_at or run.created_at,baseline_change_count=raw.change_count_by_key.get(key, 0),@@ -351,6 +352,7 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:recently_tolerated=raw.totals_recent,frequently_tolerated=raw.totals_frequent,currently_quarantined=raw.totals_quarantined,+ variant_pileups=raw.totals_variant_pileups,by_run_type=raw.by_run_type,)diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex 3b499782c889..53f04708bcc0 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -511,6 +511,11 @@ BASELINE_OVERVIEW_MAX_ENTRIES = 5000# to wash out a single jittery render while staying responsive on real changes.BASELINE_DRIFT_RECENT_RUN_COUNT = 10+# Accepted variants against one current baseline at which the baseline stops describing one+# rendering and starts describing a set. Three is the point where a reader can no longer hold what+# "the baseline" means for that snapshot, and the same floor the frequently-tolerated stat uses.+VARIANT_PILEUP_MIN = 3+@dataclass(frozen=True)class BaselineQuarantineSummary:@@ -546,6 +551,11 @@ class BaselineEntry:height: int | Nonetolerate_count_30d: inttolerate_count_90d: int+ # Accepted variants still recorded against the hash this baseline currently holds. Distinct+ # from the two counts above, which measure how often somebody accepted drift in a rolling+ # window. A baseline change drops this to zero, because a toleration is recorded against the+ # baseline hash it was decided for and stops matching when that hash moves.+ active_variants_current_baseline: intis_quarantined: boollast_run_at: datetime# Lifetime count of YAML baseline flips on master/main for this identifier.@@ -576,6 +586,8 @@ class BaselineTotals:recently_tolerated: intfrequently_tolerated: intcurrently_quarantined: int+ # Baselines carrying at least `VARIANT_PILEUP_MIN` accepted variants of their current hash.+ variant_pileups: intby_run_type: dict[str, int]diff --git a/products/visual_review/backend/facade/tasks.py b/products/visual_review/backend/facade/tasks.pyindex 31b3cc4f25ef..ba87b8f53c95 100644--- a/products/visual_review/backend/facade/tasks.py+++ b/products/visual_review/backend/facade/tasks.py@@ -1,5 +1,5 @@"""Celery tasks core schedules for visual_review (see products/architecture.md, wiring couplings)."""-from products.visual_review.backend.tasks.tasks import sweep_visual_review_retention+from products.visual_review.backend.tasks.tasks import send_visual_review_debt_digests, sweep_visual_review_retention-__all__ = ["sweep_visual_review_retention"]+__all__ = ["send_visual_review_debt_digests", "sweep_visual_review_retention"]diff --git a/products/visual_review/backend/logic/baseline_overview.py b/products/visual_review/backend/logic/baseline_overview.pyindex bc61d758abbf..851c4e36b9b4 100644--- a/products/visual_review/backend/logic/baseline_overview.py+++ b/products/visual_review/backend/logic/baseline_overview.py@@ -13,7 +13,8 @@ from posthog.dataclasses import frozenfrom ..facade.enums import INTENTIONAL_TOLERATE_REASONS, RunStatus, SnapshotResultfrom ..models import QuarantinedIdentifier, Run, RunSnapshot, ToleratedHash-from . import run_queries+from . import run_queries, toleration+from .run_queries import SnapshotKeydef get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:@@ -28,6 +29,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:- 1 query for the universe runs (one row per run_type, indexed)- 1 query for the universe rows (with thumbnail + artifact prefetch)- 2 grouped queries for tolerate counts (30d + 90d)+ - 2 queries for the accepted variants standing against the current baseline- 1 grouped query for active quarantines- 1 grouped query for lifetime baseline-flip count- 2 queries for the recent-drift average (resolve last-N runs, aggregate)@@ -35,32 +37,19 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:"""from datetime import timedelta- from ..facade.contracts import BASELINE_DRIFT_RECENT_RUN_COUNT, BASELINE_OVERVIEW_MAX_ENTRIES+ from ..facade.contracts import BASELINE_DRIFT_RECENT_RUN_COUNT, BASELINE_OVERVIEW_MAX_ENTRIES, VARIANT_PILEUP_MINnow = timezone.now()- # 1. Find the latest *completed* run on the default branch per (repo,- # branch, run_type). Filtering on `superseded_by IS NULL` looks tempting- # but is wrong here: a freshly started PENDING/PROCESSING master run is- # un-superseded yet has zero (or sparse) RunSnapshots ingested, and would- # collapse the universe to whatever it has loaded so far. `status=completed`- # makes the universe fall through to the most recent fully-ingested run.- universe_runs = list(- Run.objects.filter(- repo_id=repo_id,- branch__in=run_queries._DEFAULT_BRANCHES,- status=RunStatus.COMPLETED,- )- .order_by("repo_id", "branch", "run_type", "-created_at")- .distinct("repo_id", "branch", "run_type")- .only("id", "run_type", "completed_at", "created_at")- )+ # 1. Find the latest *completed* run on the default branch per (repo, branch, run_type).+ universe_runs = run_queries.latest_default_branch_runs(repo_id)universe_run_ids = [r.id for r in universe_runs]if not universe_run_ids:return _BaselineOverviewRaw(entries=[],tolerate_30d_by_id={},tolerate_90d_by_id={},+ active_variants_by_key={},active_quarantines_by_key={},change_count_by_key={},recent_drift_by_key={},@@ -68,6 +57,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:totals_recent=0,totals_frequent=0,totals_quarantined=0,+ totals_variant_pileups=0,by_run_type={},truncated=False,generated_at=now,@@ -135,6 +125,12 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:):tolerate_90d_by_id[identifier] = count+ # 3a-bis. Accepted variants still standing against each baseline's current hash. Scoped to the+ # whole universe rather than the truncated slice, because the totals below read it too.+ active_variants_by_key = toleration.count_active_variants_against_current_baseline(+ repo_id, now=now, newest_run_by_type=run_queries.newest_run_by_run_type(universe_runs)+ )+# 3b. Active quarantines for this repo, scoped to the universe identifiers# AND the run_types they live on (quarantine is per (repo, run_type, id)).# We hydrate the full row (not just identity) so the overview can render@@ -143,7 +139,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:# `BASELINE_OVERVIEW_MAX_ENTRIES`. `Run.metadata` (JSONField) and# `Run.error_message` (TextField) can be large and aren't needed by the# summary — defer them to keep the response light.- active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier] = {}+ active_quarantines_by_key: dict[SnapshotKey, QuarantinedIdentifier] = {}if universe_identifiers:for q in (QuarantinedIdentifier.objects.filter(@@ -155,7 +151,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:.defer("source_run__metadata", "source_run__error_message").order_by("-created_at")):- key = (q.run_type, q.identifier)+ key = SnapshotKey(run_type=q.run_type, identifier=q.identifier)# Multiple active rows for the same key shouldn't happen — create# auto-supersedes prior — but if it does, keep the latest (sorted# above) and ignore the rest.@@ -185,8 +181,8 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:# resolve the run IDs first (sub-ms) and aggregate via PK-indexed# run_id__in, otherwise the planner inlines a CTE that produces a# ROW_NUMBER plan over the full RunSnapshot table.- change_count_by_key: dict[tuple[str, str], int] = {}- recent_drift_by_key: dict[tuple[str, str], float] = {}+ change_count_by_key: dict[SnapshotKey, int] = {}+ recent_drift_by_key: dict[SnapshotKey, float] = {}if universe_identifiers:for identifier, run_type, c in (RunSnapshot.objects.filter(@@ -199,7 +195,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:.annotate(c=Count("id")).values_list("identifier", "run__run_type", "c")):- change_count_by_key[(run_type, identifier)] = c+ change_count_by_key[SnapshotKey(run_type=run_type, identifier=identifier)] = c# Top-N per run_type via window function. There's no pure-ORM# equivalent: Postgres doesn't allow filtering on a window result,@@ -237,7 +233,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:.values_list("identifier", "run__run_type", "drift_avg")):if drift_avg is not None:- recent_drift_by_key[(run_type, identifier)] = drift_avg+ recent_drift_by_key[SnapshotKey(run_type=run_type, identifier=identifier)] = drift_avg# 4. Totals computed across the *full* universe (not the truncated slice)# so the stat row stays correct when the entries are clipped.@@ -295,7 +291,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:.count())else:- quarantined_id_count = len({identifier for _, identifier in active_quarantines_by_key})+ quarantined_id_count = len({key.identifier for key in active_quarantines_by_key})# by_run_type counts every entry in the universe. Aggregate query under# truncation so it doesn't undercount; in-memory Counter when not truncated@@ -314,6 +310,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:entries=universe,tolerate_30d_by_id=tolerate_30d_by_id,tolerate_90d_by_id=tolerate_90d_by_id,+ active_variants_by_key=active_variants_by_key,active_quarantines_by_key=active_quarantines_by_key,change_count_by_key=change_count_by_key,recent_drift_by_key=recent_drift_by_key,@@ -321,6 +318,7 @@ def get_baselines_overview(repo_id: UUID) -> _BaselineOverviewRaw:totals_recent=len(recent_ids),totals_frequent=len(frequent_ids),totals_quarantined=quarantined_id_count,+ totals_variant_pileups=sum(1 for count in active_variants_by_key.values() if count >= VARIANT_PILEUP_MIN),by_run_type=by_run_type,truncated=truncated,generated_at=now,@@ -337,20 +335,24 @@ class _BaselineOverviewRaw:entries: list[RunSnapshot]tolerate_30d_by_id: dict[str, int]tolerate_90d_by_id: dict[str, int]+ # Accepted variants standing against each baseline's current hash. Only non-zero counts+ # are present.+ active_variants_by_key: dict[SnapshotKey, int]# Latest active QuarantinedIdentifier (with `source_run` preloaded) for each# `(run_type, identifier)` in the universe — lets the facade build the rich# quarantine summary embedded on each BaselineEntry. Membership doubles as# the "is_quarantined" signal — no separate set needed.- active_quarantines_by_key: dict[tuple[str, str], QuarantinedIdentifier]- # Stability signals keyed by `(run_type, identifier)` because the same- # identifier in different run types is a different baseline; merging would- # bleed storybook stability into playwright stability.- change_count_by_key: dict[tuple[str, str], int]- recent_drift_by_key: dict[tuple[str, str], float]+ active_quarantines_by_key: dict[SnapshotKey, QuarantinedIdentifier]+ # Stability signals keyed per identity because the same identifier in+ # different run types is a different baseline; merging would bleed storybook+ # stability into playwright stability.+ change_count_by_key: dict[SnapshotKey, int]+ recent_drift_by_key: dict[SnapshotKey, float]totals_all: inttotals_recent: inttotals_frequent: inttotals_quarantined: int+ totals_variant_pileups: intby_run_type: dict[str, int]truncated: boolgenerated_at: datetimediff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.pynew file mode 100644index 000000000000..f33806b86d27--- /dev/null+++ b/products/visual_review/backend/logic/debt_digest.py@@ -0,0 +1,586 @@+"""The daily reminder about visual review debt a team is still carrying.++Stateless by design. Every morning the two conditions below are evaluated from current data,+attributed to the team that owns the file the snapshot's story lives in today, and posted. Nothing+is stored about what was sent, so an item repeats every day until the condition stops holding and+disappears the moment it does. A team whose post fails is logged and the run moves on; tomorrow+recomputes everything from scratch.++The two conditions:++ Quarantine expiring. An active quarantine that runs out inside `FLAKINESS_EXPIRY_SOON_DAYS`.+ 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.++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.++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.+Three things stop that: no owners entry covers the file, the index has no such story, or there is no+index to read. All three go to the visual review maintainers as triage, kept apart from the items+those maintainers own, because holding an item until a team takes it is not owning it.+"""++from __future__ import annotations++from collections.abc import Mapping+from dataclasses import field+from datetime import datetime+from enum import StrEnum+from urllib.parse import quote++from django.conf import settings+from django.utils import timezone++import structlog+from posthog_owners.resolver import Purpose, team_channel+from posthog_owners.schema import Producer, TeamEntry++from posthog.comment.formatting import escape_slack_mrkdwn+from posthog.dataclasses import frozen+from posthog.models.integration import Integration, SlackIntegration+from posthog.models.user import User+from posthog.team_notifications.slack import (+ MAX_SECTION_CHARS,+ SlackChannel,+ SlackPostRefused,+ clip_text,+ fetch_channel_map,+ find_channel,+ post_message,+ post_with_join,+ section_block,+)++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 VARIANT_PILEUP_MIN+from ..facade.enums import RunType+from ..models import QuarantinedIdentifier, Repo, Run+from . import quarantine, run_queries, story_index, toleration++logger = structlog.get_logger(__name__)++# The digest is automation, so it asks the registry where automation posts rather than where the+# team's people are. That falls back to the people channel when a team never separates the two.+_CHANNEL_PURPOSE: Purpose = "notifications"+# Named so a team can keep this digest out of its channel while other bots keep posting there.+_PRODUCER: Producer = "visual_review"++# Whose digest carries the items no team owns. The people who built the product can read a story+# name and find who to ask; nobody else can. Routed like any other team, so there is no second+# delivery path to keep working.+_PRODUCT_PATH = "products/visual_review/"++# Said of a run type whose items have no default-branch run to attribute against.+_NO_BASELINE_RUN_DETAIL = "there is no default branch run to read"++_MAX_LINE_CHARS = MAX_SECTION_CHARS // 2+# The full identifier still goes into the URL, so a cut display costs the reader nothing.+_MAX_IDENTIFIER_CHARS = 160+_MAX_REASON_CHARS = 200++MODE_PREVIEW = "preview"+MODE_LIVE = "live"+MODES = (MODE_PREVIEW, MODE_LIVE)++_FOOTER = (+ "This repeats daily while the items stay unresolved. "+ "To opt out, set notifications: {visual_review: false} under your team in owners.yaml."+)+++class AttributionKind(StrEnum):+ """What the story index can say about the file behind one snapshot."""++ PLACED = "placed" # the story maps to a file in the repository+ STORY_ABSENT = "story_absent" # the index was read, and it holds no such story+ UNAVAILABLE = "unavailable" # there is no index to ask for this run type today+++# Each outcome asks the reader for a different fix. A placed path in triage is one no owners entry covers.+_TRIAGE_HEADERS: dict[AttributionKind, str] = {+ AttributionKind.PLACED: "*Nobody owns the file yet.* Add an owners entry for the path at the end of each line.",+ AttributionKind.STORY_ABSENT: (+ "*The story is not in the Storybook index.* Check whether it moved, was renamed, or was deleted."+ ),+ AttributionKind.UNAVAILABLE: (+ "*Ownership could not be worked out today.* Nothing to do, the digest tries again tomorrow."+ ),+}+++@frozen+class Attribution:+ """The file behind one debt item, or the reason there is none.++ Never guessed from the identifier: a story name is not a path, and a wrong guess sends a team a+ reminder about somebody else's snapshot.+ """++ kind: AttributionKind+ # Repo-relative path of the story's file. Set only when the kind is PLACED.+ source_path: str = ""+ # Short phrase naming what stopped the lookup. Set only when the kind is UNAVAILABLE.+ detail: str = ""+++@frozen+class DebtItem:+ """One thing somebody still has to decide about, and what is known about where it lives."""++ identifier: str+ run_type: str+ attribution: Attribution+ line: str+++@frozen+class RepoDebt:+ """Everything one repo owes today, before it is split by owning team."""++ expiring_quarantines: list[DebtItem]+ variant_pileups: list[DebtItem]++ @property+ def items(self) -> list[DebtItem]:+ return [*self.expiring_quarantines, *self.variant_pileups]+++@frozen+class TriageGroup:+ """The items that share one attribution outcome, and so one reason for having no owning team."""++ kind: AttributionKind+ items: list[DebtItem]+++@frozen+class TeamDigest:+ """One team's share of a repo's debt, ready to post."""++ team_slug: str+ expiring_quarantines: list[DebtItem]+ variant_pileups: list[DebtItem]+ # Items nobody owns yet. Only the maintainers' digest carries them, and they hold them until a+ # team takes them.+ triage: list[TriageGroup] = field(default_factory=list)+++@frozen+class Delivery:+ """Where one team's digest goes."""++ channel_id: str+ channel_name: str+++def _snapshot_url(repo: Repo, run_type: str, identifier: str) -> str:+ return (+ f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/repos/{repo.id}"+ f"/{quote(run_type, safe='')}/snapshots/{quote(identifier, safe='')}"+ )+++def _repo_snapshots_url(repo: Repo) -> str:+ """The repo's snapshot list. It names no snapshot, so its length does not follow the identifier."""+ return f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/repos/{repo.id}/snapshots"+++def _linked_line(repo: Repo, body: str, run_type: str, identifier: str) -> str:+ """One item's line with its link, kept under the per-line cap.++ A non-ASCII identifier percent-encodes to nine characters each, so the snapshot URL alone can+ outgrow a Slack block however short the displayed text is cut. Point at the repo's snapshot+ list instead: the reader still gets a link, and one long item no longer costs the team the+ rest of its thread.+ """+ line = f"{body} · {_snapshot_url(repo, run_type, identifier)}"+ if len(line) <= _MAX_LINE_CHARS:+ return line+ listed = f" · listed under the repo's snapshots: {_repo_snapshots_url(repo)}"+ return f"{clip_text(body, _MAX_LINE_CHARS - len(listed))}{listed}"+++def _quarantine_line(repo: Repo, entry: QuarantinedIdentifier, authors: dict[int, str], now: datetime) -> str:+ days = max((entry.expires_at - now).days, 0) if entry.expires_at is not None else 0+ who = authors.get(entry.created_by_id or 0, "someone")+ body = (+ f"Quarantine expires in {days} days"+ f" · {escape_slack_mrkdwn(clip_text(entry.identifier, _MAX_IDENTIFIER_CHARS))}"+ f" ({escape_slack_mrkdwn(entry.run_type)})"+ f' · opened by {escape_slack_mrkdwn(who)} for "{escape_slack_mrkdwn(clip_text(entry.reason, _MAX_REASON_CHARS))}"'+ )+ return _linked_line(repo, body, entry.run_type, entry.identifier)+++def _pileup_line(repo: Repo, run_type: str, identifier: str, count: int) -> str:+ body = (+ f"{count} accepted variants of the current baseline"+ f" · {escape_slack_mrkdwn(clip_text(identifier, _MAX_IDENTIFIER_CHARS))} ({escape_slack_mrkdwn(run_type)})"+ )+ return _linked_line(repo, body, run_type, identifier)+++def _display_names(user_ids: set[int]) -> dict[int, str]:+ if not user_ids:+ return {}+ return {+ user.id: user.first_name or user.email+ for user in User.objects.filter(id__in=user_ids).only("id", "first_name", "email")+ }+++def _workflow_run_id(run: Run) -> str | None:+ """The GitHub workflow run that produced one run, or None when the run records none.++ Read on a query of its own because the shared default-branch universe defers `metadata`. Every+ other reader of that universe needs the run ids alone, so it stays lean for the pages that use+ it.+ """+ metadata = Run.objects.filter(id=run.id).values_list("metadata", flat=True).first()+ github_run_id = (metadata or {}).get("github_run_id")+ return github_run_id if isinstance(github_run_id, str) and github_run_id else None+++def _attribution_sources(+ repo: Repo, run_types: set[str], newest_run_by_type: Mapping[str, Run]+) -> dict[str, story_index.StoryIndex | str]:+ """What each run type in play can be attributed against: a story index, or why there is none.++ One artifact read per run type, not per item. A run type nothing owes today is never read, so a+ repo with no Storybook debt costs no download at all.+ """+ sources: dict[str, story_index.StoryIndex | str] = {}+ for run_type in run_types:+ if run_type != RunType.STORYBOOK:+ sources[run_type] = f"{run_type} runs are not supported yet"+ continue+ run = newest_run_by_type.get(run_type)+ if run is None:+ sources[run_type] = _NO_BASELINE_RUN_DETAIL+ continue+ github_run_id = _workflow_run_id(run)+ if github_run_id is None:+ sources[run_type] = "the run behind the baseline records no workflow run"+ continue+ index = story_index.fetch_story_index(repo, github_run_id)+ sources[run_type] = (+ index if index is not None else f"the Storybook build artifact for run {github_run_id} was not read"+ )+ return sources+++def _attribution(sources: Mapping[str, story_index.StoryIndex | str], run_type: str, identifier: str) -> Attribution:+ """Where one snapshot's story lives, or why the index cannot say."""+ source = sources.get(run_type)+ if source is None:+ return Attribution(kind=AttributionKind.UNAVAILABLE, detail=_NO_BASELINE_RUN_DETAIL)+ if isinstance(source, str):+ return Attribution(kind=AttributionKind.UNAVAILABLE, detail=source)+ path = story_index.story_path(source, identifier)+ if path is None:+ return Attribution(kind=AttributionKind.STORY_ABSENT)+ return Attribution(kind=AttributionKind.PLACED, source_path=path)+++def collect_debt(repo: Repo, now: datetime) -> RepoDebt:+ """Evaluate both conditions against current data, attribute each item, and render its line."""+ newest_run_by_type = run_queries.newest_run_by_run_type(run_queries.latest_default_branch_runs(repo.id))+ expiring = quarantine.list_expiring_quarantines(repo.id, now=now)+ 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+ ).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+ # one problem.+ if count >= VARIANT_PILEUP_MIN and key not in quarantined_keys+ }++ run_types = {entry.run_type for entry in expiring} | {key.run_type for key in piled_up}+ sources = _attribution_sources(repo, run_types, newest_run_by_type)+ authors = _display_names({entry.created_by_id for entry in expiring if entry.created_by_id})++ return RepoDebt(+ expiring_quarantines=[+ DebtItem(+ identifier=entry.identifier,+ run_type=entry.run_type,+ attribution=_attribution(sources, entry.run_type, entry.identifier),+ line=_quarantine_line(repo, entry, authors, now),+ )+ for entry in expiring+ ],+ variant_pileups=[+ DebtItem(+ identifier=key.identifier,+ run_type=key.run_type,+ attribution=_attribution(sources, key.run_type, key.identifier),+ line=_pileup_line(repo, key.run_type, key.identifier, count),+ )+ # Biggest pile first, then by identity so a tie reads the same way every morning.+ for key, count in sorted(+ piled_up.items(), key=lambda item: (-item[1], item[0].run_type, item[0].identifier)+ )+ ],+ )+++def paths_to_resolve(debt: RepoDebt) -> list[str]:+ """Every path the run needs an owner for, including the product's own directory."""+ placed = {item.attribution.source_path for item in debt.items if item.attribution.kind == AttributionKind.PLACED}+ return [_PRODUCT_PATH, *sorted(placed)]+++def _owning_team(item: DebtItem, ownership: PathOwnership) -> str:+ """The team that owns the item's story file, or `UNOWNED_TEAM` when there is nobody to name."""+ if item.attribution.kind != AttributionKind.PLACED:+ return UNOWNED_TEAM+ return ownership.team_by_path.get(item.attribution.source_path, UNOWNED_TEAM)+++def split_by_team(debt: RepoDebt, ownership: PathOwnership) -> list[TeamDigest]:+ """Group a repo's debt by the team that owns each item's story file.++ Everything else is triage rather than debt of the maintainers' own: it goes into the digest of+ the team that owns the product directory, grouped by why it has no owner. When that team is+ unowned too, the item is dropped with a log line rather than posted somewhere arbitrary.+ """+ fallback = ownership.team_by_path.get(_PRODUCT_PATH, UNOWNED_TEAM)+ expiring_by_team: dict[str, list[DebtItem]] = {}+ pileups_by_team: dict[str, list[DebtItem]] = {}+ triage_by_kind: dict[AttributionKind, list[DebtItem]] = {}+ for items, bucket in ((debt.expiring_quarantines, expiring_by_team), (debt.variant_pileups, pileups_by_team)):+ for item in items:+ team = _owning_team(item, ownership)+ if team != UNOWNED_TEAM:+ bucket.setdefault(team, []).append(item)+ continue+ if fallback == UNOWNED_TEAM:+ logger.info(+ "visual_review.debt_digest_item_unowned",+ identifier=item.identifier,+ attribution=str(item.attribution.kind),+ source_path=item.attribution.source_path,+ )+ continue+ triage_by_kind.setdefault(item.attribution.kind, []).append(item)++ # Declaration order, so the three groups always read in the same order.+ triage = [TriageGroup(kind=kind, items=triage_by_kind[kind]) for kind in AttributionKind if kind in triage_by_kind]+ teams = expiring_by_team.keys() | pileups_by_team.keys()+ if triage:+ teams = teams | {fallback}+ return [+ TeamDigest(+ team_slug=team,+ expiring_quarantines=expiring_by_team.get(team, []),+ variant_pileups=pileups_by_team.get(team, []),+ triage=triage if team == fallback else [],+ )+ for team in sorted(teams)+ ]+++def _unavailable_details(digest: TeamDigest) -> list[str]:+ """Every distinct reason ownership could not be worked out for this digest's triage items."""+ return sorted(+ {item.attribution.detail for group in digest.triage for item in group.items if item.attribution.detail}+ )+++def lead_text(digest: TeamDigest, repo: Repo) -> str:+ expiring = len(digest.expiring_quarantines)+ pileups = len(digest.variant_pileups)+ # A digest that carries triage only still names the team and the repo, so the maintainers can+ # see whose channel it landed in without opening the thread.+ owed = (+ f"{expiring} quarantine{'' if expiring == 1 else 's'} expire{'s' if expiring == 1 else ''} soon, "+ f"{pileups} snapshot{'' if pileups == 1 else 's'} with piled-up variants."+ if expiring or pileups+ else "nothing this team owns today."+ )+ sentences = [f"Visual review debt for {digest.team_slug} in {repo.repo_full_name}: {owed}"]+ triage_count = sum(len(group.items) for group in digest.triage)+ if triage_count:+ sentences.append(+ f"Plus {triage_count} in triage that nobody owns yet: visual review maintainers hold them "+ "until a team takes them."+ )+ details = _unavailable_details(digest)+ if details:+ sentences.append(+ "Ownership could not be worked out for some of them today, because "+ f"{escape_slack_mrkdwn('; '.join(details))}. The digest tries again tomorrow."+ )+ # The lead is one Slack section like every thread line, so it takes the same cap.+ return clip_text(" ".join(sentences), MAX_SECTION_CHARS)+++def _triage_line(item: DebtItem) -> str:+ """One triage item's line, carrying what its group's header asks the reader to act on."""+ if item.attribution.kind == AttributionKind.PLACED:+ return f"{item.line} · {escape_slack_mrkdwn(item.attribution.source_path)}"+ if item.attribution.kind == AttributionKind.UNAVAILABLE:+ return f"{item.line} · {escape_slack_mrkdwn(item.attribution.detail)}"+ return item.line+++def thread_texts(digest: TeamDigest) -> list[str]:+ """The item lines, grouped by condition and then by triage reason, split to fit Slack's section cap."""+ lines = [+ *(item.line for item in digest.expiring_quarantines),+ *(item.line for item in digest.variant_pileups),+ ]+ for group in digest.triage:+ lines.append(_TRIAGE_HEADERS[group.kind])+ lines.extend(_triage_line(item) for item in group.items)+ lines.append(_FOOTER)+ # A cut line costs one reader one path; a line Slack refuses costs the team the rest of the thread.+ lines = [clip_text(line, MAX_SECTION_CHARS) for line in lines]+ messages: list[str] = []+ current: list[str] = []+ for line in lines:+ if current and len("\n".join([*current, line])) > MAX_SECTION_CHARS:+ messages.append("\n".join(current))+ current = []+ current.append(line)+ if current:+ messages.append("\n".join(current))+ return messages+++def resolve_channel(+ digest: TeamDigest, registry: Mapping[str, TeamEntry], channels_by_name: Mapping[str, SlackChannel]+) -> Delivery | None:+ """The team's own notifications channel, or None when it opted out or the name does not resolve."""+ answer = team_channel(digest.team_slug, registry, _CHANNEL_PURPOSE, _PRODUCER)+ if answer.channel is None:+ logger.info("visual_review.debt_digest_team_opted_out", team_slug=digest.team_slug)+ return None+ name = answer.channel.removeprefix("#")+ match = find_channel(channels_by_name, name, allow_shared=False)+ if match.channel is None:+ logger.info(+ "visual_review.debt_digest_channel_unusable",+ team_slug=digest.team_slug,+ channel_name=name,+ reason=match.reason,+ )+ return None+ return Delivery(channel_id=match.channel.channel_id, channel_name=name)+++def send_debt_digest(repo: Repo, mode: str) -> list[str]:+ """Evaluate, attribute, and post one repo's digest. One team's failure does not stop the rest.++ Returns each team's rendered message, so an operator running this by hand can read what the+ run would send without reaching into the logs.+ """+ # Anything that is not preview posts, so an undefined mode must stop here rather than go live.+ if mode not in MODES:+ logger.warning("visual_review.debt_digest_mode_unknown", mode=mode)+ return []++ debt = collect_debt(repo, timezone.now())+ if not debt.items:+ logger.info("visual_review.debt_digest_nothing_owed", repo_id=str(repo.id), team_id=repo.team_id)+ return []++ ownership = resolve_path_owners(repo.repo_full_name, paths_to_resolve(debt))+ if not ownership.resolved:+ # A blind answer names no team and carries no registry, so every item would read as+ # unowned and be dropped. Say so instead, and send the same items tomorrow.+ logger.warning("visual_review.debt_digest_ownership_unavailable", repo_id=str(repo.id), team_id=repo.team_id)+ return []+ digests = split_by_team(debt, ownership)++ if mode == MODE_PREVIEW:+ return [_preview_one(repo, digest, ownership.registry) for digest in digests]++ integration = Integration.objects.filter(team_id=repo.team_id, kind="slack").first()+ if integration is None:+ logger.info("visual_review.debt_digest_no_slack_integration", team_id=repo.team_id)+ return []+ channels_by_name = fetch_channel_map(integration)++ rendered: list[str] = []+ for digest in digests:+ try:+ rendered.append(_send_one(repo, digest, ownership.registry, channels_by_name, integration))+ except Exception as e:+ # One team's Slack failure must not cost the rest of the repo its reminder, and there is+ # nothing to retry against: tomorrow's run sends the same items again.+ logger.warning(+ "visual_review.debt_digest_team_failed",+ repo_id=str(repo.id),+ team_slug=digest.team_slug,+ error=str(e),+ )+ return rendered+++def _preview_one(repo: Repo, digest: TeamDigest, registry: Mapping[str, TeamEntry]) -> str:+ """Render one team's digest and log it, without reading Slack at all."""+ rendered = "\n".join([lead_text(digest, repo), *thread_texts(digest)])+ # Preview holds no channel map, because fetching one needs the integration it deliberately does+ # not touch. So the routing here only ever reports the team's own opt-out.+ resolved = resolve_channel(digest, registry, {})+ logger.info(+ "visual_review.debt_digest_preview",+ repo_id=str(repo.id),+ team_slug=digest.team_slug,+ channel_name=resolved.channel_name if resolved is not None else None,+ item_count=len(digest.expiring_quarantines) + len(digest.variant_pileups),+ triage_count=sum(len(group.items) for group in digest.triage),+ rendered=rendered,+ )+ return rendered+++def _send_one(+ repo: Repo,+ digest: TeamDigest,+ registry: Mapping[str, TeamEntry],+ channels_by_name: Mapping[str, SlackChannel],+ integration: Integration,+) -> str:+ lead = lead_text(digest, repo)+ thread = thread_texts(digest)+ delivery = resolve_channel(digest, registry, channels_by_name)+ if delivery is None:+ return ""++ slack = SlackIntegration(integration)+ try:+ thread_ts = post_with_join(+ slack, delivery.channel_id, section_block(lead), lead, channel_name=delivery.channel_name+ )+ except SlackPostRefused as e:+ logger.warning("visual_review.debt_digest_post_refused", team_slug=digest.team_slug, error=str(e))+ return ""+ # Without a parent to hang them on, the item lines land in the channel as separate top-level+ # posts, which is the noise the thread exists to remove.+ if thread_ts is not None:+ for text in thread:+ post_message(slack, delivery.channel_id, section_block(text), text, thread_ts=thread_ts)+ return "\n".join([lead, *thread])+++def repos_in_scope() -> list[Repo]:+ """Every repo, oldest first.++ No allowlist: the per-repo task stops as soon as a repo owes nothing, so a repo that never+ carries debt costs one cheap read a day. The fan-out only routes, so the rows stay unhydrated.+ """+ # nosemgrep: idor-lookup-without-team — cross-team beat sweep, no user input+ return list(Repo.objects.unscoped().only("id", "team_id").order_by("created_at"))diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.pyindex c2da8bd5b774..1395457d0d16 100644--- a/products/visual_review/backend/logic/flakiness.py+++ b/products/visual_review/backend/logic/flakiness.py@@ -20,7 +20,6 @@ from posthog.dataclasses import frozenfrom ..facade.contracts import (FLAKINESS_BROKEN_RATE,- FLAKINESS_EXPIRY_SOON_DAYS,FLAKINESS_MAX_ENTRIES,FLAKINESS_MIN_HEADROOM,FLAKINESS_MIN_WINDOW_RUNS,@@ -31,6 +30,8 @@ from ..facade.contracts import (from ..facade.enums import ClassificationReason, FlakinessState, ReviewState, RunStatus, SnapshotResult, ToleratedReasonfrom ..models import QuarantinedIdentifier, Run, RunSnapshot, ToleratedHashfrom . import run_queries+from .quarantine import expiry_soon_cutoff, is_expiring_soon+from .run_queries import SnapshotKey# Rows a run recorded as a difference from the baseline, split by what that# difference cost. `_HARD` failed the gate and blocked whoever was merging.@@ -73,14 +74,6 @@ _SOFT = Q(result=SnapshotResult.UNCHANGED) & ()-@frozen-class _SnapshotKey:- """One snapshot identity. The same identifier under two run types is two."""-- run_type: str- identifier: str--@frozenclass _VariantKey:"""One snapshot's variants, scoped to the baseline they were recorded against.@@ -174,7 +167,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:# Hydrated so each row can render reason, expiry, who and the source run# without a per-row fetch. `Run.metadata` and `Run.error_message` can be# large and are not needed for the summary.- active_quarantines_by_key: dict[_SnapshotKey, QuarantinedIdentifier] = {}+ active_quarantines_by_key: dict[SnapshotKey, QuarantinedIdentifier] = {}for active_quarantine in (QuarantinedIdentifier.objects.filter(repo_id=repo_id).filter(live)@@ -182,26 +175,13 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:.defer("source_run__metadata", "source_run__error_message").order_by("-created_at")):- quarantine_key = _SnapshotKey(run_type=active_quarantine.run_type, identifier=active_quarantine.identifier)+ quarantine_key = SnapshotKey(run_type=active_quarantine.run_type, identifier=active_quarantine.identifier)# Creating a quarantine supersedes the prior active row, so duplicates# should not exist. Keep the newest if one ever does.if quarantine_key not in active_quarantines_by_key:active_quarantines_by_key[quarantine_key] = active_quarantine- # `status=completed` rather than `superseded_by IS NULL`: a freshly started- # run on the default branch is un-superseded but has few or no RunSnapshots- # ingested yet, which would collapse the universe to whatever it has loaded- # so far. Same reasoning as `baseline_overview.get_baselines_overview`.- universe_runs = list(- Run.objects.filter(- repo_id=repo_id,- branch__in=run_queries._DEFAULT_BRANCHES,- status=RunStatus.COMPLETED,- )- .order_by("repo_id", "branch", "run_type", "-created_at")- .distinct("repo_id", "branch", "run_type")- .only("id", "run_type", "created_at")- )+ universe_runs = run_queries.latest_default_branch_runs(repo_id)if not universe_runs:return _quarantine_only_raw(active_quarantines_by_key,@@ -210,27 +190,19 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:max_entries=FLAKINESS_MAX_ENTRIES,)- # `universe_runs` holds one run per branch and run type, so a repo with runs- # on both master and main has two per run type. The row identity carries no- # branch, so keep only the newest run per run type. Otherwise whichever- # branch happened to be read last decided the baseline, and two identical- # requests could disagree.- newest_run_by_type: dict[str, Run] = {}- for run in sorted(universe_runs, key=lambda r: r.created_at, reverse=True):- newest_run_by_type.setdefault(run.run_type, run)-+ newest_run_by_type = run_queries.newest_run_by_run_type(universe_runs)run_type_by_run_id = {run.id: run_type for run_type, run in newest_run_by_type.items()}universe_run_ids = list(run_type_by_run_id)# The baseline hash each identifier would be compared against right now.# values_list rather than model hydration: the universe can run to# thousands of rows and only the listed ones need thumbnails later.- baseline_hash_by_key: dict[_SnapshotKey, str] = {}+ baseline_hash_by_key: dict[SnapshotKey, str] = {}for run_id, identifier, baseline_hash in RunSnapshot.objects.filter(run_id__in=universe_run_ids).values_list("run_id", "identifier", "baseline_hash"):if baseline_hash:- baseline_hash_by_key[_SnapshotKey(run_type=run_type_by_run_id[run_id], identifier=identifier)] = (+ baseline_hash_by_key[SnapshotKey(run_type=run_type_by_run_id[run_id], identifier=identifier)] = (baseline_hash)@@ -347,7 +319,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:# neighbour does. The history it reads reaches back only as far as retention# keeps default-branch runs, which is# `retention.DEFAULT_BRANCH_RUN_RETENTION_DAYS`.- baseline_moved_at_by_key: dict[_SnapshotKey, datetime] = {}+ baseline_moved_at_by_key: dict[SnapshotKey, datetime] = {}for identifier, run_type, moved_at in (RunSnapshot.objects.filter(run__repo_id=repo_id,@@ -361,9 +333,9 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:.values_list("identifier", "run__run_type", "moved_at")):if moved_at is not None:- baseline_moved_at_by_key[_SnapshotKey(run_type=run_type, identifier=identifier)] = moved_at+ baseline_moved_at_by_key[SnapshotKey(run_type=run_type, identifier=identifier)] = moved_at- expiry_soon_cutoff = now + timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS)+ expiry_cutoff = expiry_soon_cutoff(now)# An identity can carry something to report and still have no current# baseline: a quarantine opened before the first run, or a snapshot that@@ -371,7 +343,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:# default-branch run. Those keys are absent from `baseline_hash_by_key`, so# walk them too rather than silently drop what they recorded.baseline_less_keys = (active_quarantines_by_key.keys() | hard_activity.keys()) - baseline_hash_by_key.keys()- scored_keys: list[tuple[_SnapshotKey, str]] = [+ scored_keys: list[tuple[SnapshotKey, str]] = [*baseline_hash_by_key.items(),*((key, "") for key in baseline_less_keys),]@@ -438,7 +410,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:needs_decision=_needs_decision(quarantine=quarantine,hard_count=hard_count,- expiry_soon_cutoff=expiry_soon_cutoff,+ expiry_cutoff=expiry_cutoff,),))@@ -468,7 +440,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:snapshots_by_key = _hydrate_snapshots(universe_run_ids=universe_run_ids,run_type_by_run_id=run_type_by_run_id,- keys={_SnapshotKey(run_type=row.run_type, identifier=row.identifier) for row in listed},+ keys={SnapshotKey(run_type=row.run_type, identifier=row.identifier) for row in listed},)return _FlakinessRaw(@@ -489,7 +461,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:def _quarantine_only_raw(- active_quarantines_by_key: dict[_SnapshotKey, QuarantinedIdentifier],+ active_quarantines_by_key: dict[SnapshotKey, QuarantinedIdentifier],*,generated_at: datetime,strip_days: int,@@ -550,7 +522,7 @@ def _read_activity(in_window: Q,match: Q,identifiers: list[str] | None = None,-) -> dict[_SnapshotKey, _Activity]:+) -> dict[SnapshotKey, _Activity]:"""Window activity per snapshot identity, for the rows `match` selects.Grouped by day so one query serves both the rate and the activity strip:@@ -560,10 +532,10 @@ def _read_activity(if identifiers is not None:queryset = queryset.filter(identifier__in=identifiers)- daily: dict[_SnapshotKey, dict[date, int]] = defaultdict(dict)- totals: Counter[_SnapshotKey] = Counter()- last_at: dict[_SnapshotKey, datetime] = {}- worst: dict[_SnapshotKey, float] = {}+ daily: dict[SnapshotKey, dict[date, int]] = defaultdict(dict)+ totals: Counter[SnapshotKey] = Counter()+ last_at: dict[SnapshotKey, datetime] = {}+ worst: dict[SnapshotKey, float] = {}for run_type, identifier, day, day_count, latest, worst_diff in (queryset.annotate(day=TruncDate("run__created_at")).values("run__run_type", "identifier", "day")@@ -574,7 +546,7 @@ def _read_activity().values_list("run__run_type", "identifier", "day", "day_count", "latest", "worst_diff")):- key = _SnapshotKey(run_type=run_type, identifier=identifier)+ key = SnapshotKey(run_type=run_type, identifier=identifier)daily[key][day] = day_counttotals[key] += day_countseen_last = last_at.get(key)@@ -661,16 +633,16 @@ def _latest(*moments: datetime | None) -> datetime | None:return max(known) if known else None-def snapshot_key(row: _FlakinessRow) -> _SnapshotKey:+def snapshot_key(row: _FlakinessRow) -> SnapshotKey:"""Key for `_FlakinessRaw.snapshots_by_key`, for the facade to look a row up."""- return _SnapshotKey(run_type=row.run_type, identifier=row.identifier)+ return SnapshotKey(run_type=row.run_type, identifier=row.identifier)def _needs_decision(*,quarantine: QuarantinedIdentifier | None,hard_count: int,- expiry_soon_cutoff: datetime,+ expiry_cutoff: datetime,) -> bool:"""Whether an active quarantine has stopped matching what it was opened for.@@ -696,7 +668,7 @@ def _needs_decision(return Falseif hard_count == 0:return True- return quarantine.expires_at is not None and quarantine.expires_at <= expiry_soon_cutoff+ return is_expiring_soon(quarantine, expiry_cutoff)def _daily_series(counts_by_day: dict[date, int], *, strip_start: date, length: int) -> list[int]:@@ -708,13 +680,13 @@ def _hydrate_snapshots(*,universe_run_ids: list[UUID],run_type_by_run_id: dict[UUID, str],- keys: set[_SnapshotKey],-) -> dict[_SnapshotKey, RunSnapshot]:+ keys: set[SnapshotKey],+) -> dict[SnapshotKey, RunSnapshot]:"""Thumbnail and dimension data for the listed rows only."""if not keys:return {}identifiers = list({key.identifier for key in keys})- hydrated: dict[_SnapshotKey, RunSnapshot] = {}+ hydrated: dict[SnapshotKey, RunSnapshot] = {}for snapshot in (RunSnapshot.objects.filter(run_id__in=universe_run_ids, identifier__in=identifiers).select_related("current_artifact__thumbnail")@@ -727,7 +699,7 @@ def _hydrate_snapshots("current_artifact__thumbnail__content_hash",)):- key = _SnapshotKey(run_type=run_type_by_run_id[snapshot.run_id], identifier=snapshot.identifier)+ key = SnapshotKey(run_type=run_type_by_run_id[snapshot.run_id], identifier=snapshot.identifier)if key in keys:hydrated[key] = snapshotreturn hydrated@@ -787,7 +759,7 @@ class _FlakinessRaw:"""rows: list[_FlakinessRow]- snapshots_by_key: dict[_SnapshotKey, RunSnapshot]+ snapshots_by_key: dict[SnapshotKey, RunSnapshot]tracked_total: inttotals_broken: inttotals_unstable: intdiff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.pyindex 05cf7a5bc313..5d75a19cc1ce 100644--- a/products/visual_review/backend/logic/github_api.py+++ b/products/visual_review/backend/logic/github_api.py@@ -159,6 +159,7 @@ def _github_api_request(repo: Repo,path: str,*,+ params: dict[str, str | int] | None = None,json: Mapping[str, object] | None = None,timeout: int = 10,) -> requests.Response:@@ -174,7 +175,9 @@ def _github_api_request(github = get_github_integration_for_repo(repo)- response = github.api_request(method, f"/repos/{repo.repo_full_name}/{safe_path}", json_body=json, timeout=timeout)+ response = github.api_request(+ method, f"/repos/{repo.repo_full_name}/{safe_path}", params=params, json_body=json, timeout=timeout+ )if response.status_code == 404 and repo.repo_external_id:new_full_name = _resolve_repo_by_id(github, repo.repo_external_id)@@ -189,7 +192,7 @@ def _github_api_request(repo.save(update_fields=["repo_full_name"])response = github.api_request(- method, f"/repos/{new_full_name}/{safe_path}", json_body=json, timeout=timeout+ method, f"/repos/{new_full_name}/{safe_path}", params=params, json_body=json, timeout=timeout)return responsediff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.pyindex e044083016ae..3b8e5ba90250 100644--- a/products/visual_review/backend/logic/quarantine.py+++ b/products/visual_review/backend/logic/quarantine.py@@ -2,17 +2,19 @@from __future__ import annotations-from datetime import datetime+from datetime import datetime, timedeltafrom uuid import UUIDfrom django.db import transactionfrom django.db.models import Qfrom django.utils import timezone-from ..db import WRITER_DB+from ..db import READER_DB, WRITER_DB+from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYSfrom ..facade.enums import ActorTypefrom ..models import QuarantinedIdentifier, Runfrom . import errors, repos+from .run_queries import SnapshotKeydef list_quarantined_identifiers(@@ -38,6 +40,48 @@ def list_quarantined_identifiers(return list(qs.order_by("-created_at"))+def expiry_soon_cutoff(now: datetime) -> datetime:+ """The moment past which an expiry is close enough that somebody has to decide about it."""+ return now + timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS)+++def is_expiring_soon(entry: QuarantinedIdentifier, cutoff: datetime) -> bool:+ """Whether an active quarantine runs out inside the window.++ An entry with no expiry never does. It is a standing exception, and nothing about it changes+ on its own, so there is no date for a reminder to hang off.+ """+ return entry.expires_at is not None and entry.expires_at <= cutoff+++def list_expiring_quarantines(repo_id: UUID, *, now: datetime) -> list[QuarantinedIdentifier]:+ """Active quarantines that run out inside the window, soonest first.++ An entry leaves this list when somebody extends it past the window, lifts it, or lets it lapse.+ """+ return list(+ QuarantinedIdentifier.objects.using(READER_DB)+ .filter(repo_id=repo_id, expires_at__gt=now, expires_at__lte=expiry_soon_cutoff(now))+ # Preload `source_run` so the caller can render the "what was wrong" link without an extra+ # fetch per row. `Run.metadata` (JSONField) and `Run.error_message` (TextField) can be+ # large and aren't needed for the summary.+ .select_related("source_run")+ .defer("source_run__metadata", "source_run__error_message")+ .order_by("expires_at")+ )+++def active_quarantine_keys(repo_id: UUID, *, now: datetime) -> set[SnapshotKey]:+ """Every identity under a quarantine that has not run out, whatever its expiry."""+ return {+ SnapshotKey(run_type=run_type, identifier=identifier)+ for run_type, identifier in QuarantinedIdentifier.objects.using(READER_DB)+ .filter(repo_id=repo_id)+ .filter(Q(expires_at__isnull=True) | Q(expires_at__gt=now))+ .values_list("run_type", "identifier")+ }++@transaction.atomic(using=WRITER_DB)def quarantine_identifier(repo_id: UUID,diff --git a/products/visual_review/backend/logic/run_queries.py b/products/visual_review/backend/logic/run_queries.pyindex 5e20d7af54cf..f0c7a32899ff 100644--- a/products/visual_review/backend/logic/run_queries.py+++ b/products/visual_review/backend/logic/run_queries.py@@ -7,6 +7,7 @@ from uuid import UUIDfrom django.db import models as db_modelsfrom django.db.models import Count, Q+from posthog.dataclasses import frozenfrom posthog.helpers.trigram_search import (TrigramSearchField,apply_trigram_search,@@ -20,6 +21,14 @@ from ..models import Run, RunSnapshotfrom . import errors+@frozen+class SnapshotKey:+ """One snapshot identity. The same identifier under two run types is two."""++ run_type: str+ identifier: str++def is_run_stale(run: Run) -> bool:return run.superseded_by_id is not None@@ -152,3 +161,41 @@ def get_run_snapshots(run_id: UUID, team_id: int | None = None) -> list[RunSnaps# include both candidates and assume nobody has both — whichever has rows wins.# When `trunk`/`develop`-style defaults show up, this becomes a `Repo` field._DEFAULT_BRANCHES = ("master", "main")+++def latest_default_branch_runs(repo_id: UUID) -> list[Run]:+ """The newest completed run per `(branch, run_type)` on the default branches.++ The universe every "current baseline" read is anchored on: one row per+ `(run_type, identifier)` in these runs is the closest thing to what a new+ capture would be compared against right now.++ `status=completed` rather than `superseded_by IS NULL`: a freshly started+ run on the default branch is un-superseded but has few or no RunSnapshots+ ingested yet, which would collapse the universe to whatever it has loaded+ so far.+ """+ return list(+ Run.objects.filter(+ repo_id=repo_id,+ branch__in=_DEFAULT_BRANCHES,+ status=RunStatus.COMPLETED,+ )+ .order_by("repo_id", "branch", "run_type", "-created_at")+ .distinct("repo_id", "branch", "run_type")+ .only("id", "run_type", "completed_at", "created_at")+ )+++def newest_run_by_run_type(runs: list[Run]) -> dict[str, Run]:+ """One run per run type, newest first.++ `latest_default_branch_runs` holds one run per branch and run type, so a repo with runs on+ both master and main has two per run type. A `(run_type, identifier)` identity carries no+ branch, so without this reduction whichever branch was read last decides the baseline and two+ identical requests can disagree.+ """+ newest: dict[str, Run] = {}+ for run in sorted(runs, key=lambda r: r.created_at, reverse=True):+ newest.setdefault(run.run_type, run)+ return newestdiff --git a/products/visual_review/backend/logic/story_index.py b/products/visual_review/backend/logic/story_index.pynew file mode 100644index 000000000000..0cab9088c625--- /dev/null+++ b/products/visual_review/backend/logic/story_index.py@@ -0,0 +1,203 @@+"""Which repository file each Storybook snapshot renders, read from the run's build artifact.++A snapshot identifier is built from a story id, and only the Storybook build knows which file a+story came from. The build uploads its story index as a GitHub Actions artifact, so the index of the+run behind the current baseline is the map from a snapshot back to a file somebody owns.++Nothing is stored. The artifact of one workflow run never changes, so a parsed index is cached under+that run id and the key rotates on its own when the baseline moves.+"""++from __future__ import annotations++import io+import json+import zipfile+import posixpath+from collections.abc import Mapping++from django.core.cache import cache++import requests+import structlog++from posthog.dataclasses import frozen+from posthog.egress.github.transport import GitHubRateLimitError+from posthog.models.github_integration_base import GitHubIntegrationError++from ..models import Repo+from . import errors, github_api++logger = structlog.get_logger(__name__)++# These mirror the snapshot naming in common/storybook/.storybook/test-runner.ts. An identifier is+# "<story id>--<theme>", with "--<browser>" appended for a browser other than chromium, and the+# story id carries "--<width>" for a story that snapshots several viewport widths.+_THEMES = ("light", "dark")+_SUFFIXED_BROWSERS = ("webkit",)+_VIEWPORT_WIDTHS = ("narrow", "medium", "wide", "superwide")++# Where the PostHog repository builds Storybook, and the artifact its workflow uploads the build as.+STORYBOOK_ARTIFACT_NAME = "storybook-build"+STORYBOOK_PACKAGE_DIR = "common/storybook"++_INDEX_MEMBER = "index.json"+# The zip is tens of megabytes, so it needs far longer than an API read.+_ZIP_TIMEOUT_SECONDS = 60+# Both are read into memory whole, so an artifact far past the size of a real build is refused+# rather than made the worker's problem.+_MAX_ARTIFACT_BYTES = 512 * 1024 * 1024+_MAX_INDEX_BYTES = 32 * 1024 * 1024+_CACHE_TTL_SECONDS = 2 * 24 * 60 * 60+++@frozen+class StoryIndex:+ """The story-to-file map of one Storybook build."""++ path_by_story_id: Mapping[str, str]+++def _strip_theme_and_browser(identifier: str) -> str | None:+ """The story id an identifier was built from, before any width suffix is considered.++ None when the identifier carries no theme, which means the test runner did not write it.+ """+ rest = identifier+ for browser in _SUFFIXED_BROWSERS:+ if rest.endswith(f"--{browser}"):+ rest = rest.removesuffix(f"--{browser}")+ break+ for theme in _THEMES:+ if rest.endswith(f"--{theme}"):+ return rest.removesuffix(f"--{theme}")+ return None+++def story_path(index: StoryIndex, identifier: str) -> str | None:+ """The repository path behind one snapshot identifier, or None when the index has no such story.++ The full story id is looked up first, because a story can be named after a viewport width+ ("lemon-ui-lemon-banner--narrow" is a story of its own). Stripping the width first would place+ that snapshot in the file of a different story.+ """+ story_id = _strip_theme_and_browser(identifier)+ if story_id is None:+ return None+ path = index.path_by_story_id.get(story_id)+ if path is not None:+ return path+ for width in _VIEWPORT_WIDTHS:+ if story_id.endswith(f"--{width}"):+ return index.path_by_story_id.get(story_id.removesuffix(f"--{width}"))+ return None+++def _parse_story_index(raw: bytes, package_dir: str) -> dict[str, str]:+ """Story id to repository path, for the story entries of a Storybook index.++ Raises ValueError when the payload is not a story index. `json.JSONDecodeError` is a ValueError,+ so a truncated download lands in the same branch.+ """+ document = json.loads(raw)+ entries = document.get("entries") if isinstance(document, dict) else None+ if not isinstance(entries, dict):+ raise ValueError("storybook index has no entries")++ paths: dict[str, str] = {}+ for story_id, entry in entries.items():+ # Docs pages carry an importPath too, and no snapshot is taken of one.+ if not isinstance(entry, dict) or entry.get("type") != "story":+ continue+ import_path = entry.get("importPath")+ if not isinstance(import_path, str) or not import_path:+ continue+ path = posixpath.normpath(posixpath.join(package_dir, import_path))+ # A story imported from outside the checkout has no repository path, so no team can own it.+ # An absolute import path drops the package directory on the join, so it lands here too.+ if path.startswith("..") or posixpath.isabs(path):+ continue+ paths[story_id] = path+ return paths+++def _log_unavailable(repo: Repo, github_run_id: str, reason: str) -> None:+ logger.info(+ "visual_review.story_index_unavailable",+ repo_id=str(repo.id),+ github_run_id=github_run_id,+ reason=reason,+ )+++def _fetch_index_member(repo: Repo, github_run_id: str) -> bytes | None:+ """The raw index.json of a run's Storybook artifact. None when it cannot be read."""+ listing = github_api._github_api_request(+ "GET", repo, f"actions/runs/{github_run_id}/artifacts", params={"per_page": 100}+ )+ if listing.status_code != 200:+ _log_unavailable(repo, github_run_id, "artifact_missing")+ return None++ artifact = next(+ (item for item in listing.json().get("artifacts") or [] if item.get("name") == STORYBOOK_ARTIFACT_NAME),+ None,+ )+ if artifact is None:+ _log_unavailable(repo, github_run_id, "artifact_missing")+ return None+ if artifact.get("expired"):+ _log_unavailable(repo, github_run_id, "artifact_expired")+ return None+ if (artifact.get("size_in_bytes") or 0) > _MAX_ARTIFACT_BYTES:+ _log_unavailable(repo, github_run_id, "artifact_too_large")+ return None++ # GitHub answers this with a 302 to a signed blob URL. Requests follows it and drops the+ # Authorization header on the host change, so the GitHub token never reaches the blob host.+ download = github_api._github_api_request(+ "GET", repo, f"actions/artifacts/{artifact['id']}/zip", timeout=_ZIP_TIMEOUT_SECONDS+ )+ if download.status_code != 200:+ _log_unavailable(repo, github_run_id, "download_failed")+ return None++ with zipfile.ZipFile(io.BytesIO(download.content)) as archive:+ if _INDEX_MEMBER not in archive.namelist():+ _log_unavailable(repo, github_run_id, "index_missing")+ return None+ if archive.getinfo(_INDEX_MEMBER).file_size > _MAX_INDEX_BYTES:+ _log_unavailable(repo, github_run_id, "artifact_too_large")+ return None+ return archive.read(_INDEX_MEMBER)+++def fetch_story_index(repo: Repo, github_run_id: str) -> StoryIndex | None:+ """The story index of one workflow run's Storybook build. None means attribution is unavailable.++ Only a success is cached, so a run whose artifact was gone this morning is read again tomorrow.+ Every failure is answered with None: the digest reports what it could not attribute, and never+ fails over a missing artifact.+ """+ cache_key = f"visual_review_story_index:{repo.id}:{github_run_id}"+ cached = cache.get(cache_key)+ if isinstance(cached, dict):+ return StoryIndex(path_by_story_id=cached)++ try:+ raw = _fetch_index_member(repo, github_run_id)+ if raw is None:+ return None+ paths = _parse_story_index(raw, STORYBOOK_PACKAGE_DIR)+ except errors.GitHubIntegrationNotFoundError:+ _log_unavailable(repo, github_run_id, "no_github_integration")+ return None+ except (GitHubIntegrationError, GitHubRateLimitError, requests.RequestException, zipfile.BadZipFile):+ _log_unavailable(repo, github_run_id, "download_failed")+ return None+ except ValueError:+ _log_unavailable(repo, github_run_id, "index_invalid")+ return None++ cache.set(cache_key, paths, timeout=_CACHE_TTL_SECONDS)+ return StoryIndex(path_by_story_id=paths)diff --git a/products/visual_review/backend/logic/toleration.py b/products/visual_review/backend/logic/toleration.pyindex ae16a9eeae76..fafa25d36b36 100644--- a/products/visual_review/backend/logic/toleration.py+++ b/products/visual_review/backend/logic/toleration.py@@ -2,15 +2,19 @@from __future__ import annotations+from collections.abc import Mapping+from datetime import datetimefrom uuid import UUIDfrom django.db import transaction+from django.db.models import Count, Qfrom django.utils import timezonefrom ..db import WRITER_DBfrom ..facade.enums import INTENTIONAL_TOLERATE_REASONS, ActorType, ReviewState, SnapshotResult, ToleratedReasonfrom ..models import Run, RunSnapshot, ToleratedHashfrom . import errors, run_queries+from .run_queries import SnapshotKey@transaction.atomic(using=WRITER_DB)@@ -86,6 +90,77 @@ def mark_snapshot_as_tolerated(return snapshot+def count_active_variants_against_current_baseline(+ repo_id: UUID, *, now: datetime, newest_run_by_type: Mapping[str, Run] | None = None+) -> dict[SnapshotKey, int]:+ """How many accepted variants each snapshot identity still carries against the baseline it+ would be compared against right now.++ A toleration is recorded under the baseline hash it was decided for, so a baseline change+ invalidates the whole pile at once and this count drops back to zero. That is what makes the+ number worth acting on: every row it counts is still in use.++ Counted with no recency cutoff, unlike the 30-day and 90-day counts on the baselines overview.+ Those measure how often somebody accepted drift; this measures how many accepted renderings the+ baseline is standing in for, and an accepted variant keeps matching without a new record.++ Keys carry the run type because the same identifier under two run types is two baselines.+ Only non-zero counts are returned.++ A caller that already holds the default-branch run universe passes it as `newest_run_by_type`,+ so the same page or digest run does not read it twice.+ """+ baseline_hash_by_key = _current_baseline_hashes(repo_id, newest_run_by_type)+ if not baseline_hash_by_key:+ return {}++ live = Q(expires_at__isnull=True) | Q(expires_at__gt=now)+ # The exact pair is still matched below, because two identifiers can share a baseline hash.+ counts_by_pair = {+ (identifier, baseline_hash): count+ for identifier, baseline_hash, count in ToleratedHash.objects.filter(+ repo_id=repo_id,+ identifier__in=list({key.identifier for key in baseline_hash_by_key}),+ baseline_hash__in=list(set(baseline_hash_by_key.values())),+ reason__in=INTENTIONAL_TOLERATE_REASONS,+ )+ .filter(live)+ .values_list("identifier", "baseline_hash")+ .annotate(c=Count("id"))+ .values_list("identifier", "baseline_hash", "c")+ }+ counts: dict[SnapshotKey, int] = {}+ for key, baseline_hash in baseline_hash_by_key.items():+ count = counts_by_pair.get((key.identifier, baseline_hash), 0)+ if count:+ counts[key] = count+ return counts+++def _current_baseline_hashes(+ repo_id: UUID, newest_run_by_type: Mapping[str, Run] | None = None+) -> dict[SnapshotKey, str]:+ """The baseline hash each snapshot identity would be compared against right now.++ values_list rather than model hydration: the universe runs to thousands of rows and nothing+ here needs anything else off them.+ """+ if newest_run_by_type is None:+ newest_run_by_type = run_queries.newest_run_by_run_type(run_queries.latest_default_branch_runs(repo_id))+ run_type_by_run_id = {run.id: run_type for run_type, run in newest_run_by_type.items()}+ if not run_type_by_run_id:+ return {}+ return {+ SnapshotKey(run_type=run_type_by_run_id[run_id], identifier=identifier): baseline_hash+ for run_id, identifier, baseline_hash in RunSnapshot.objects.filter(+ run_id__in=list(run_type_by_run_id)+ ).values_list("run_id", "identifier", "baseline_hash")+ # A snapshot with no baseline yet has nothing for a toleration to be recorded against, and+ # an empty hash would otherwise match every other baseline-less identity's rows.+ if baseline_hash+ }++def get_tolerated_hashes_for_identifier(repo_id: UUID, identifier: str) -> list[ToleratedHash]:"""List all tolerated hashes for a snapshot identifier, most recent first."""return list(ToleratedHash.objects.filter(repo_id=repo_id, identifier=identifier).order_by("-created_at"))diff --git a/products/visual_review/backend/management/commands/visual_review_debt_digest.py b/products/visual_review/backend/management/commands/visual_review_debt_digest.pynew file mode 100644index 000000000000..9d6629d9020c--- /dev/null+++ b/products/visual_review/backend/management/commands/visual_review_debt_digest.py@@ -0,0 +1,50 @@+"""Run one repo's visual review debt digest synchronously, in the mode you name."""++from typing import Any++from django.core.management.base import BaseCommand, CommandError++from posthog.models.scoping import team_scope++from products.visual_review.backend.logic import debt_digest+from products.visual_review.backend.models import Repo+++def find_repo(repo_full_name: str, team_id: int | None) -> Repo:+ """The one repo that goes by this name, or a CommandError saying why there is no single answer.++ A name is unique inside a team, not across them, so two teams can register the same repository+ and each carries its own debt.+ """+ # nosemgrep: idor-lookup-without-team — operator-run command, repo named on the command line+ matches = Repo.objects.unscoped().filter(repo_full_name=repo_full_name)+ if team_id is not None:+ matches = matches.filter(team_id=team_id)+ found = list(matches.order_by("created_at"))+ if not found:+ raise CommandError(f"No visual review repo named {repo_full_name}")+ if len(found) > 1:+ teams = ", ".join(str(repo.team_id) for repo in found)+ raise CommandError(f"{repo_full_name} is registered by more than one team ({teams}). Pick one with --team-id.")+ return found[0]+++class Command(BaseCommand):+ help = "Evaluate and render (or post) the visual review debt digest for one repo"++ def add_arguments(self, parser: Any) -> None:+ parser.add_argument("--repo", type=str, required=True, help="Repository as owner/name.")+ parser.add_argument("--team-id", type=int, help="Team that registered the repository.")+ parser.add_argument(+ "--mode",+ type=str,+ default=debt_digest.MODE_PREVIEW,+ choices=list(debt_digest.MODES),+ help="preview renders and prints, live posts to each team's channel.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ repo = find_repo(options["repo"], options.get("team_id"))+ with team_scope(repo.team_id):+ rendered = debt_digest.send_debt_digest(repo, mode=options["mode"])+ self.stdout.write("\n\n".join(rendered) or "Nothing owed.")diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex 9c3fba6e9e05..4f700b8d99c9 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -350,6 +350,13 @@ class BaselineEntrySerializer(DataclassSerializer):required=False,help_text="Active quarantine details when `is_quarantined` is true. Null otherwise.",)+ active_variants_current_baseline = serializers.IntegerField(+ help_text=(+ "Accepted variants still recorded against this baseline's current hash. Unlike the "+ "30-day and 90-day counts, this has no time window: an accepted variant keeps matching "+ "without a new record. A baseline change resets it to zero."+ )+ )class Meta:dataclass = BaselineEntry@@ -357,6 +364,9 @@ class BaselineEntrySerializer(DataclassSerializer):class BaselineTotalsSerializer(DataclassSerializer):by_run_type = serializers.DictField(child=serializers.IntegerField())+ variant_pileups = serializers.IntegerField(+ help_text="Baselines carrying three or more accepted variants of their current hash."+ )class Meta:dataclass = BaselineTotalsdiff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.pyindex 3a706da12519..1da746e2a559 100644--- a/products/visual_review/backend/tasks/tasks.py+++ b/products/visual_review/backend/tasks/tasks.py@@ -12,6 +12,8 @@ import timefrom datetime import datefrom uuid import UUID+from django.core.cache import cache+import structlogfrom celery import shared_taskfrom opentelemetry import trace@@ -28,6 +30,15 @@ from ..models import Repologger = structlog.get_logger(__name__)TRACER = trace.get_tracer(__name__)+# Long enough that a slow repo's Slack round trips finish inside it, short enough that a worker+# killed mid-run does not hold the next scheduled run out. A held lock costs one day of reminders,+# which the next run resends.+_DEBT_DIGEST_LOCK_SECONDS = 900++# A child task worth running is a child task worth running today. A worker draining a backlog past+# this drops it, and the next morning's run recomputes what is still owed.+_DEBT_DIGEST_EXPIRY_SECONDS = 60 * 60+@shared_task(name="products.visual_review.backend.tasks.emit_run_processing_metrics",@@ -210,3 +221,47 @@ def sweep_visual_review_retention() -> None:objects_leaked=result.objects_leaked,duration_seconds=round(time.monotonic() - started, 1),)+++@shared_task(+ name="products.visual_review.backend.tasks.send_visual_review_debt_digests",+ ignore_result=True,+)+@skip_team_scope_audit # cross-team beat sweep; the per-repo task below scopes every query+def send_visual_review_debt_digests() -> None:+ """Fan out to every repo, one task each.++ One repo's failure must not stop the rest, and nothing is stored about what was sent, so the+ next morning's run recomputes and resends whatever is still owed.+ """+ from ..logic import debt_digest # noqa: PLC0415 — avoids the logic/tasks circular import++ for repo in debt_digest.repos_in_scope():+ send_visual_review_debt_digest.apply_async(+ args=(repo.team_id, str(repo.id)), expires=_DEBT_DIGEST_EXPIRY_SECONDS+ )+++@shared_task(+ name="products.visual_review.backend.tasks.send_visual_review_debt_digest",+ ignore_result=True,+)+@with_team_scope()+def send_visual_review_debt_digest(team_id: int, repo_id: str) -> None:+ """Post one repo's digest.++ The lock is what stops a retried or double-scheduled run from posting the same reminders twice.+ Nothing records what was sent, so an overlapping run has no other way to tell.+ """+ from ..logic import debt_digest # noqa: PLC0415 — avoids the logic/tasks circular import++ lock_key = f"visual_review_debt_digest:{repo_id}"+ if not cache.add(lock_key, "locked", timeout=_DEBT_DIGEST_LOCK_SECONDS):+ logger.info("visual_review.debt_digest_already_running", repo_id=repo_id, team_id=team_id)+ return++ repo = Repo.objects.filter(id=UUID(repo_id), team_id=team_id).first()+ if repo is None:+ logger.warning("visual_review.debt_digest_repo_missing", repo_id=repo_id, team_id=team_id)+ return+ debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_LIVE)diff --git a/products/visual_review/backend/tests/logic/test_debt_digest.py b/products/visual_review/backend/tests/logic/test_debt_digest.pynew file mode 100644index 000000000000..e4d8c4c9c489--- /dev/null+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py@@ -0,0 +1,420 @@+"""Unit tests for logic/debt_digest.py — the daily visual review debt reminder."""++from datetime import timedelta++import pytest+from unittest.mock import MagicMock, patch++from django.conf import settings+from django.utils import timezone++from posthog_owners.schema import TeamEntry++from posthog.models.team.team import Team+from posthog.team_notifications.slack import MAX_SECTION_CHARS, SlackChannel, SlackPostRefused++from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership+from products.visual_review.backend.facade.contracts import (+ FLAKINESS_EXPIRY_SOON_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.tests.conftest import PRODUCT_DATABASES++_PRODUCT_PATH = "products/visual_review/"+_SOURCE_PATH = "frontend/src/scenes/Button.stories.tsx"+_STORY_ID = "scenes-app-button--primary"+_IDENTIFIER = f"{_STORY_ID}--light"+_ABSENT_IDENTIFIER = "scenes-app-gone--primary--light"+_GITHUB_RUN_ID = "98765"+_INDEX = story_index.StoryIndex(path_by_story_id={_STORY_ID: _SOURCE_PATH})++_PLACED = debt_digest.Attribution(kind=debt_digest.AttributionKind.PLACED, source_path=_SOURCE_PATH)+_STORY_ABSENT = debt_digest.Attribution(kind=debt_digest.AttributionKind.STORY_ABSENT)+_UNAVAILABLE = debt_digest.Attribution(+ kind=debt_digest.AttributionKind.UNAVAILABLE,+ detail=f"the Storybook build artifact for run {_GITHUB_RUN_ID} was not read",+)+++def _ownership(team_by_path: dict[str, str], registry: dict[str, TeamEntry] | None = None) -> PathOwnership:+ return PathOwnership(team_by_path=team_by_path, registry=registry or {}, resolved=True)+++def _item(+ attribution: debt_digest.Attribution, identifier: str = _IDENTIFIER, line: str = "a line"+) -> debt_digest.DebtItem:+ return debt_digest.DebtItem(identifier=identifier, run_type="storybook", attribution=attribution, line=line)+++def _with_index(index: story_index.StoryIndex | None):+ return patch("products.visual_review.backend.logic.story_index.fetch_story_index", return_value=index)+++def _digest(team_slug: str = "team-devex") -> debt_digest.TeamDigest:+ return debt_digest.TeamDigest(team_slug=team_slug, expiring_quarantines=[_item(_PLACED)], variant_pileups=[])+++def _triage_digest() -> debt_digest.TeamDigest:+ return debt_digest.TeamDigest(+ team_slug="team-devex",+ expiring_quarantines=[],+ variant_pileups=[],+ triage=[+ debt_digest.TriageGroup(kind=debt_digest.AttributionKind.PLACED, items=[_item(_PLACED)]),+ debt_digest.TriageGroup(kind=debt_digest.AttributionKind.UNAVAILABLE, items=[_item(_UNAVAILABLE)]),+ ],+ )+++class TestRendering:+ @pytest.mark.parametrize("run_type", ["storybook", "<!channel>"])+ def test_escapes_slack_control_characters_in_user_text(self, run_type: str) -> None:+ # A reason, an identifier and a run type are all contributor input; any of them could+ # otherwise smuggle a <!channel> mention into every owning team's channel.+ entry = MagicMock(+ identifier="Button<!channel>",+ run_type=run_type,+ reason="flaky & <!here>",+ expires_at=timezone.now() + timedelta(days=3),+ created_by_id=None,+ )+ repo = MagicMock(id="00000000-0000-0000-0000-000000000001", team_id=7, repo_full_name="PostHog/posthog")++ line = debt_digest._quarantine_line(repo, entry, {}, timezone.now())+ pileup = debt_digest._pileup_line(repo, run_type, "Button", 4)++ assert "<!channel>" not in line+ assert "<!channel>" not in pileup+ assert "<!here>" not in line+ assert "<!channel>" in line+ assert "flaky & <!here>" in line++ def test_links_to_the_snapshot_page_with_encoded_segments(self) -> None:+ repo = MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")++ 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.endswith("/project/7/visual_review/repos/abc/storybook/snapshots/scenes%2FButton--dark")++ @pytest.mark.parametrize(+ "identifier,reason,links_to_the_snapshot",+ [+ ("b" * 512, "non-deterministic", True),+ # Each of these percent-encodes to nine characters, so the URL alone outgrows a block.+ ("界" * 400, "non-deterministic", False),+ ("Button--light", "because " * 100, True),+ ],+ )+ def test_one_oversized_item_still_fits_a_slack_block(+ self, identifier: str, reason: str, links_to_the_snapshot: bool+ ) -> None:+ repo = MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")+ entry = MagicMock(+ identifier=identifier,+ run_type="storybook",+ reason=reason,+ expires_at=timezone.now() + timedelta(days=3),+ created_by_id=None,+ )++ line = debt_digest._quarantine_line(repo, entry, {}, timezone.now())+ texts = debt_digest.thread_texts(+ debt_digest.TeamDigest(+ team_slug="team-devex",+ expiring_quarantines=[_item(_PLACED, identifier=identifier, line=line)] * 2,+ variant_pileups=[],+ )+ )++ assert len(line) <= debt_digest._MAX_LINE_CHARS+ assert settings.SITE_URL in line+ assert ("/snapshots/" in line) == links_to_the_snapshot+ assert all(len(text) <= MAX_SECTION_CHARS for text in texts)++ def test_splits_the_thread_when_one_group_runs_long(self) -> None:+ long_item = _item(_PLACED, line="x" * 2000)+ digest = debt_digest.TeamDigest(+ team_slug="team-devex", expiring_quarantines=[long_item, long_item], variant_pileups=[]+ )++ texts = debt_digest.thread_texts(digest)++ assert len(texts) > 1+ assert all(len(text) <= MAX_SECTION_CHARS for text in texts)+ assert texts[-1].endswith(debt_digest._FOOTER)++ def test_the_lead_holds_triage_apart_from_what_the_team_owns(self) -> None:+ repo = MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")++ lead = debt_digest.lead_text(_triage_digest(), repo)++ assert "nothing this team owns today" in lead+ assert "2 in triage that nobody owns yet" in lead+ # An artifact that could not be read must never read as "nobody owns this".+ assert f"the Storybook build artifact for run {_GITHUB_RUN_ID} was not read" in lead+ assert "tries again tomorrow" in lead++ def test_the_thread_groups_triage_under_one_header_per_reason(self) -> None:+ thread = "\n".join(debt_digest.thread_texts(_triage_digest()))++ assert debt_digest._TRIAGE_HEADERS[debt_digest.AttributionKind.PLACED] in thread+ assert debt_digest._TRIAGE_HEADERS[debt_digest.AttributionKind.UNAVAILABLE] in thread+ # The path stays on the line, because it is what an owners entry is written for.+ assert f"a line · {_SOURCE_PATH}" in thread+ assert f"a line · the Storybook build artifact for run {_GITHUB_RUN_ID} was not read" in thread+++class TestSplitByTeam:+ def test_routes_a_placed_item_to_the_team_that_owns_its_file(self) -> None:+ placed = _item(_PLACED, line="placed")+ absent = _item(_STORY_ABSENT, identifier=_ABSENT_IDENTIFIER, line="absent")+ debt = debt_digest.RepoDebt(expiring_quarantines=[placed], variant_pileups=[absent])++ digests = debt_digest.split_by_team(+ debt, _ownership({_SOURCE_PATH: "team-product-analytics", _PRODUCT_PATH: "team-devex"})+ )++ by_slug = {d.team_slug: d for d in digests}+ assert set(by_slug) == {"team-product-analytics", "team-devex"}+ assert by_slug["team-product-analytics"].expiring_quarantines == [placed]+ # The maintainers hold the other item without it counting as debt of their own.+ assert by_slug["team-devex"].variant_pileups == []+ assert by_slug["team-devex"].triage == [+ debt_digest.TriageGroup(kind=debt_digest.AttributionKind.STORY_ABSENT, items=[absent])+ ]++ @pytest.mark.parametrize("attribution", [_PLACED, _STORY_ABSENT, _UNAVAILABLE])+ def test_keeps_the_three_unowned_outcomes_apart(self, attribution: debt_digest.Attribution) -> None:+ item = _item(attribution)+ debt = debt_digest.RepoDebt(expiring_quarantines=[item], variant_pileups=[])++ digests = debt_digest.split_by_team(debt, _ownership({_PRODUCT_PATH: "team-devex"}))++ assert [d.team_slug for d in digests] == ["team-devex"]+ assert digests[0].expiring_quarantines == []+ assert digests[0].triage == [debt_digest.TriageGroup(kind=attribution.kind, items=[item])]++ def test_drops_an_item_nobody_owns(self) -> None:+ debt = debt_digest.RepoDebt(expiring_quarantines=[_item(_STORY_ABSENT)], variant_pileups=[])++ assert debt_digest.split_by_team(debt, _ownership({})) == []+++class TestRouting:+ _CHANNELS = {+ "team-devex": SlackChannel(channel_id="C1", shared=False),+ "team-shared": SlackChannel(channel_id="C2", shared=True),+ }++ def test_a_team_that_opted_out_is_skipped(self) -> None:+ registry = {"team-devex": TeamEntry(notifications={"visual_review": False})}++ assert debt_digest.resolve_channel(_digest(), registry, self._CHANNELS) is None++ def test_a_shared_channel_is_refused(self) -> None:+ # A name match onto a shared channel would send an internal reminder out of the workspace.+ assert debt_digest.resolve_channel(_digest("team-shared"), {}, self._CHANNELS) is None++ @pytest.mark.parametrize("mode", ["preveiw", "shadow", ""])+ def test_an_unknown_mode_evaluates_nothing_and_posts_nothing(self, mode: str) -> None:+ with (+ patch("products.visual_review.backend.logic.debt_digest.collect_debt") as collect,+ patch("products.visual_review.backend.logic.debt_digest.post_with_join") as post,+ ):+ assert debt_digest.send_debt_digest(MagicMock(), mode=mode) == []++ assert collect.call_count == 0+ assert post.call_count == 0++[email protected]_db(databases=PRODUCT_DATABASES)+class TestReposInScope:+ def test_every_repo_is_in_scope_whatever_team_owns_it(self, team) -> None:+ mine = repos.create_repo(team_id=team.id, repo_external_id=77781, repo_full_name="org/mine")+ other_team = Team.objects.create(organization=team.organization, name="other")+ theirs = repos.create_repo(team_id=other_team.id, repo_external_id=77782, repo_full_name="org/theirs")++ assert {(repo.team_id, repo.id) for repo in debt_digest.repos_in_scope()} == {+ (mine.team_id, mine.id),+ (theirs.team_id, theirs.id),+ }++[email protected]_db(databases=PRODUCT_DATABASES)+class TestCollectAndSend:+ @pytest.fixture+ def repo(self, team):+ return repos.create_repo(team_id=team.id, repo_external_id=77771, repo_full_name="org/test-debt")++ def _completed_run(self, repo, mocker, identifiers=(_IDENTIFIER,)):+ artifact_store.get_or_create_artifact(repo_id=repo.id, content_hash="new_hash", storage_path="p/new_hash")+ baselines = dict.fromkeys(identifiers, "old_hash")+ run, _ = runs.create_run(+ CreateRunInput(+ repo_id=repo.id,+ run_type=RunType.STORYBOOK,+ commit_sha="abc",+ branch="main",+ pr_number=None,+ metadata={"github_run_id": _GITHUB_RUN_ID},+ snapshots=[+ SnapshotManifestItem(identifier=identifier, content_hash="new_hash") for identifier in identifiers+ ],+ baseline_hashes=baselines,+ ),+ team_id=repo.team_id,+ )+ mocker.patch(+ "products.visual_review.backend.logic.baselines._resolve_baselines_with_merge_base",+ return_value=(baselines, 0),+ )+ mocker.patch("products.visual_review.backend.tasks.tasks.process_run_diffs.delay")+ runs.complete_run(run.id)+ runs.finish_processing(run.id)+ return run++ def _pile_up(self, repo, identifier=_IDENTIFIER, count=3):+ for index in range(count):+ ToleratedHash.objects.create(+ repo=repo,+ team_id=repo.team_id,+ identifier=identifier,+ baseline_hash="old_hash",+ alternate_hash=f"variant_{index}",+ reason="human",+ )++ def test_collects_both_conditions_and_names_the_story_file(self, repo, team, user, mocker):+ self._completed_run(repo, mocker)+ self._pile_up(repo)+ now = timezone.now()+ quarantine.quarantine_identifier(+ repo_id=repo.id,+ identifier=_ABSENT_IDENTIFIER,+ run_type=RunType.STORYBOOK,+ reason="non-deterministic",+ user_id=user.id,+ team_id=team.id,+ expires_at=now + timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS - 1),+ )++ with _with_index(_INDEX):+ debt = debt_digest.collect_debt(repo, now)++ assert [(item.identifier, item.attribution) for item in debt.variant_pileups] == [(_IDENTIFIER, _PLACED)]+ # A story the index does not hold is absent, which is not the same as nobody owning it.+ 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++ def test_an_unreadable_artifact_leaves_the_items_unattributed(self, repo, mocker):+ self._completed_run(repo, mocker)+ self._pile_up(repo)++ with _with_index(None):+ debt = debt_digest.collect_debt(repo, timezone.now())++ assert [item.attribution for item in debt.variant_pileups] == [_UNAVAILABLE]++ @pytest.mark.parametrize(+ "expires_in,expected_expiring",+ [+ (timedelta(days=1), [_IDENTIFIER]),+ (timedelta(days=60), []),+ (None, []),+ ],+ )+ def test_a_quarantined_identity_is_not_also_reported_for_its_variants(+ self, repo, team, user, mocker, expires_in, expected_expiring+ ):+ self._completed_run(repo, mocker)+ self._pile_up(repo)+ now = timezone.now()+ quarantine.quarantine_identifier(+ repo_id=repo.id,+ identifier=_IDENTIFIER,+ run_type=RunType.STORYBOOK,+ reason="non-deterministic",+ user_id=user.id,+ team_id=team.id,+ expires_at=now + expires_in if expires_in is not None else None,+ )++ with _with_index(_INDEX):+ debt = debt_digest.collect_debt(repo, now)++ assert [item.identifier for item in debt.expiring_quarantines] == expected_expiring+ assert debt.variant_pileups == []++ def test_preview_renders_every_team_and_posts_nothing(self, repo, mocker):+ self._completed_run(repo, mocker)+ self._pile_up(repo)+ with (+ _with_index(_INDEX),+ patch(+ "products.visual_review.backend.logic.debt_digest.resolve_path_owners",+ return_value=_ownership({_SOURCE_PATH: "team-devex", _PRODUCT_PATH: "team-devex"}),+ ),+ patch("products.visual_review.backend.logic.debt_digest.fetch_channel_map") as channel_map,+ patch("products.visual_review.backend.logic.debt_digest.post_with_join") as post,+ ):+ rendered = debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_PREVIEW)++ assert post.call_count == 0+ assert channel_map.call_count == 0+ assert len(rendered) == 1+ assert rendered[0].startswith("Visual review debt for team-devex in org/test-debt: ")++ def test_an_unreadable_owners_file_sends_nothing(self, repo, mocker):+ self._completed_run(repo, mocker)+ self._pile_up(repo)+ # Every path reads as unowned when the owners files could not be read, which would+ # otherwise drop the whole repo's debt as nobody's.+ blind = PathOwnership(+ team_by_path={_SOURCE_PATH: UNOWNED_TEAM, _PRODUCT_PATH: UNOWNED_TEAM}, registry={}, resolved=False+ )+ with (+ _with_index(_INDEX),+ patch("products.visual_review.backend.logic.debt_digest.resolve_path_owners", return_value=blind),+ patch("products.visual_review.backend.logic.debt_digest.post_with_join") as post,+ ):+ assert debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_LIVE) == []++ assert post.call_count == 0++ def test_one_team_failing_does_not_stop_the_next(self, repo, mocker):+ self._completed_run(repo, mocker, (_IDENTIFIER, _ABSENT_IDENTIFIER))+ self._pile_up(repo)+ self._pile_up(repo, identifier=_ABSENT_IDENTIFIER)+ with (+ _with_index(_INDEX),+ patch(+ "products.visual_review.backend.logic.debt_digest.resolve_path_owners",+ return_value=_ownership({_SOURCE_PATH: "team-one", _PRODUCT_PATH: "team-two"}),+ ),+ patch("products.visual_review.backend.logic.debt_digest.Integration") as integration,+ patch("products.visual_review.backend.logic.debt_digest.SlackIntegration"),+ patch(+ "products.visual_review.backend.logic.debt_digest.fetch_channel_map",+ return_value={+ "team-one": SlackChannel(channel_id="C1", shared=False),+ "team-two": SlackChannel(channel_id="C2", shared=False),+ },+ ),+ patch(+ "products.visual_review.backend.logic.debt_digest.post_with_join",+ side_effect=[SlackPostRefused("no"), "1700000000.1"],+ ) as post,+ patch("products.visual_review.backend.logic.debt_digest.post_message") as thread_post,+ ):+ integration.objects.filter.return_value.first.return_value = MagicMock()+ debt_digest.send_debt_digest(repo, mode=debt_digest.MODE_LIVE)++ assert post.call_count == 2+ assert thread_post.call_count == 1diff --git a/products/visual_review/backend/tests/logic/test_quarantine.py b/products/visual_review/backend/tests/logic/test_quarantine.pyindex 9eaf7e1bb15d..8ed5f0225568 100644--- a/products/visual_review/backend/tests/logic/test_quarantine.py+++ b/products/visual_review/backend/tests/logic/test_quarantine.py@@ -1,9 +1,12 @@"""Unit tests for logic/quarantine.py — Quarantined identifiers."""+from datetime import timedelta+import pytestfrom django.utils import timezone+from products.visual_review.backend.facade.contracts import FLAKINESS_EXPIRY_SOON_DAYSfrom products.visual_review.backend.facade.enums import RunStatus, RunTypefrom products.visual_review.backend.logic import quarantine, reposfrom products.visual_review.backend.models import Repo, Run@@ -89,3 +92,35 @@ class TestQuarantineIdentifier:team_id=team.id,)assert entry.source_run_id is None++[email protected]_db(databases=PRODUCT_DATABASES)+class TestExpiringQuarantines:+ @pytest.fixture+ def repo(self, team):+ return repos.create_repo(team_id=team.id, repo_external_id=88889, repo_full_name="org/test-expiring")++ @pytest.mark.parametrize(+ "expiry_days,listed",+ [+ (FLAKINESS_EXPIRY_SOON_DAYS - 1, True),+ (FLAKINESS_EXPIRY_SOON_DAYS + 1, False),+ (-1, False),+ (None, False),+ ],+ )+ def test_lists_only_quarantines_running_out_inside_the_window(self, repo, team, user, expiry_days, listed):+ now = timezone.now()+ quarantine.quarantine_identifier(+ repo_id=repo.id,+ identifier="flake",+ run_type=RunType.STORYBOOK,+ reason="non-deterministic",+ user_id=user.id,+ team_id=team.id,+ expires_at=None if expiry_days is None else now + timedelta(days=expiry_days),+ )++ entries = quarantine.list_expiring_quarantines(repo.id, now=now)++ assert [entry.identifier for entry in entries] == (["flake"] if listed else [])diff --git a/products/visual_review/backend/tests/logic/test_story_index.py b/products/visual_review/backend/tests/logic/test_story_index.pynew file mode 100644index 000000000000..b5f334a2f3c0--- /dev/null+++ b/products/visual_review/backend/tests/logic/test_story_index.py@@ -0,0 +1,182 @@+"""Unit tests for logic/story_index.py — the snapshot-to-file map from the Storybook artifact."""++import io+import json+import zipfile+from uuid import uuid4++import pytest+from unittest.mock import MagicMock, patch++import requests++from products.visual_review.backend.logic import errors, story_index++_ARTIFACT_NAME = story_index.STORYBOOK_ARTIFACT_NAME++_INDEX = story_index.StoryIndex(+ path_by_story_id={+ "scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx",+ # A story of its own whose name happens to be a viewport width name.+ "lemon-ui-lemon-banner--narrow": "frontend/src/lib/lemon-ui/LemonBannerNarrow.stories.tsx",+ "lemon-ui-lemon-banner--info": "frontend/src/lib/lemon-ui/LemonBanner.stories.tsx",+ },+)+++def _repo() -> MagicMock:+ return MagicMock(id=uuid4())+++def _zip_bytes(members: dict[str, bytes]) -> bytes:+ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w") as archive:+ for name, body in members.items():+ archive.writestr(name, body)+ return buffer.getvalue()+++def _response(status_code: int = 200, payload: object = None, content: bytes = b"") -> MagicMock:+ return MagicMock(status_code=status_code, content=content, json=MagicMock(return_value=payload))+++def _listing(*artifacts: dict) -> MagicMock:+ return _response(payload={"artifacts": list(artifacts)})+++def _index_document(entries: dict[str, dict]) -> bytes:+ return json.dumps({"v": 5, "entries": entries}).encode()+++class TestStoryPath:+ @pytest.mark.parametrize(+ "identifier,expected",+ [+ ("scenes-app-button--primary--light", "frontend/src/scenes/Button.stories.tsx"),+ ("scenes-app-button--primary--dark", "frontend/src/scenes/Button.stories.tsx"),+ ("scenes-app-button--primary--dark--webkit", "frontend/src/scenes/Button.stories.tsx"),+ # The width is only stripped once the full story id misses.+ ("lemon-ui-lemon-banner--info--superwide--light", "frontend/src/lib/lemon-ui/LemonBanner.stories.tsx"),+ # A story named after a width matches exactly, so it keeps its own file.+ ("lemon-ui-lemon-banner--narrow--light", "frontend/src/lib/lemon-ui/LemonBannerNarrow.stories.tsx"),+ ("scenes-app-gone--primary--light", None),+ # Nothing the test runner wrote looks like this, so there is no story to guess at.+ ("scenes-app-button--primary", None),+ ],+ )+ def test_resolves_an_identifier_to_its_story_file(self, identifier: str, expected: str | None) -> None:+ assert story_index.story_path(_INDEX, identifier) == expected+++class TestFetchStoryIndex:+ def test_keeps_story_entries_and_turns_import_paths_into_repo_paths(self) -> None:+ entries = {+ "scenes-app-button--primary": {+ "type": "story",+ "importPath": "../../frontend/src/scenes/Button.stories.tsx",+ },+ "scenes-app-button--docs": {"type": "docs", "importPath": "../../frontend/src/scenes/Button.mdx"},+ # A story imported from outside the checkout has no repository path to own.+ "vendor-thing--default": {"type": "story", "importPath": "../../../vendor/Thing.stories.tsx"},+ # An absolute path leaves the checkout too, and it drops the package directory on join.+ "root-thing--default": {"type": "story", "importPath": "/etc/Thing.stories.tsx"},+ }+ zip_bytes = _zip_bytes({"index.json": _index_document(entries)})+ with patch(+ "products.visual_review.backend.logic.github_api._github_api_request",+ side_effect=[_listing({"name": _ARTIFACT_NAME, "id": 42}), _response(content=zip_bytes)],+ ):+ index = story_index.fetch_story_index(_repo(), "98765")++ assert index is not None+ assert dict(index.path_by_story_id) == {"scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx"}++ # Nothing here needs the database, but the product's autouse package fixture builds it, and it+ # can only do that once a test in the module asks for it.+ @pytest.mark.django_db+ def test_reads_the_artifact_once_per_workflow_run(self) -> None:+ repo = _repo()+ zip_bytes = _zip_bytes(+ {"index.json": _index_document({"a--b": {"type": "story", "importPath": "../../frontend/src/A.tsx"}})}+ )+ with patch(+ "products.visual_review.backend.logic.github_api._github_api_request",+ side_effect=[_listing({"name": _ARTIFACT_NAME, "id": 42}), _response(content=zip_bytes)],+ ) as request:+ first = story_index.fetch_story_index(repo, "98765")+ second = story_index.fetch_story_index(repo, "98765")++ assert request.call_count == 2+ assert first is not None and second is not None+ assert dict(second.path_by_story_id) == {"a--b": "frontend/src/A.tsx"}++ @pytest.mark.parametrize(+ "responses",+ [+ pytest.param([_listing()], id="artifact_missing"),+ pytest.param([_listing({"name": "other-build", "id": 7})], id="artifact_named_differently"),+ pytest.param([_listing({"name": _ARTIFACT_NAME, "id": 42, "expired": True})], id="artifact_expired"),+ pytest.param([_response(status_code=404, payload={})], id="run_gone"),+ pytest.param(+ [_listing({"name": _ARTIFACT_NAME, "id": 42}), _response(status_code=410)],+ id="download_failed",+ ),+ pytest.param(+ [+ _listing({"name": _ARTIFACT_NAME, "id": 42}),+ _response(content=_zip_bytes({"iframe.html": b"<html></html>"})),+ ],+ id="index_missing",+ ),+ pytest.param(+ [_listing({"name": _ARTIFACT_NAME, "id": 42}), _response(content=_zip_bytes({"index.json": b"{"}))],+ id="index_invalid",+ ),+ ],+ )+ def test_an_unreadable_artifact_is_answered_with_none_and_not_cached(self, responses: list[MagicMock]) -> None:+ repo = _repo()+ with patch(+ "products.visual_review.backend.logic.github_api._github_api_request",+ side_effect=responses * 2,+ ) as request:+ assert story_index.fetch_story_index(repo, "98765") is None+ assert story_index.fetch_story_index(repo, "98765") is None++ # Nothing was cached, so tomorrow's run asks GitHub again instead of repeating today's miss.+ assert request.call_count == len(responses) * 2++ @pytest.mark.parametrize(+ "artifact_size,max_index_bytes",+ [+ (story_index._MAX_ARTIFACT_BYTES + 1, story_index._MAX_INDEX_BYTES),+ (1000, 5),+ ],+ )+ def test_an_oversized_artifact_is_not_read(self, artifact_size: int, max_index_bytes: int) -> None:+ responses = [+ _listing({"name": _ARTIFACT_NAME, "id": 42, "size_in_bytes": artifact_size}),+ _response(content=_zip_bytes({"index.json": _index_document({})})),+ ]+ with (+ patch.object(story_index, "_MAX_INDEX_BYTES", max_index_bytes),+ patch(+ "products.visual_review.backend.logic.github_api._github_api_request",+ side_effect=responses,+ ),+ ):+ assert story_index.fetch_story_index(_repo(), "98765") is None++ @pytest.mark.parametrize(+ "error",+ [+ errors.GitHubIntegrationNotFoundError("no integration"),+ requests.ConnectionError("boom"),+ ],+ )+ def test_a_failing_github_call_does_not_raise(self, error: Exception) -> None:+ with patch(+ "products.visual_review.backend.logic.github_api._github_api_request",+ side_effect=error,+ ):+ assert story_index.fetch_story_index(_repo(), "98765") is Nonediff --git a/products/visual_review/backend/tests/logic/test_toleration.py b/products/visual_review/backend/tests/logic/test_toleration.pyindex ec6cf851fdcd..7e89574a1b9b 100644--- a/products/visual_review/backend/tests/logic/test_toleration.py+++ b/products/visual_review/backend/tests/logic/test_toleration.py@@ -9,6 +9,7 @@ from django.utils import timezonefrom products.visual_review.backend.facade.contracts import CreateRunInput, SnapshotManifestItemfrom products.visual_review.backend.facade.enums import ActorType, RunType, SnapshotResultfrom products.visual_review.backend.logic import artifact_store, repos, runs, toleration+from products.visual_review.backend.logic.run_queries import SnapshotKeyfrom products.visual_review.backend.models import ToleratedHashfrom products.visual_review.backend.tests.conftest import PRODUCT_DATABASES@@ -158,6 +159,38 @@ class TestToleratedHashes:assert snapshot.classification_reason == ""assert snapshot.tolerated_hash_match is None+ @pytest.mark.parametrize(+ "rows,expected",+ [+ ([("old_hash", "human", None), ("old_hash", "agent", None)], 2),+ ([("old_hash", "human", None), ("old_hash", "agent", None), ("old_hash", "human", None)], 3),+ # Recorded against a baseline that has since moved. The classifier can never match+ # these again, so counting them would report a pile-up nobody can act on.+ ([("old_hash", "human", None), ("superseded", "human", None)], 1),+ ([("old_hash", "human", None), ("old_hash", "human", -1)], 1),+ # Sub-threshold jitter the diff pipeline minted, not a decision anybody made.+ ([("old_hash", "human", None), ("old_hash", "auto_threshold", None)], 1),+ ([("old_hash", "auto_threshold", None)], 0),+ ],+ )+ def test_counts_accepted_variants_of_the_current_baseline(self, repo, mocker, rows, expected):+ self._create_completed_run(repo, mocker)+ now = timezone.now()+ for index, (baseline_hash, reason, expiry_days) in enumerate(rows):+ ToleratedHash.objects.create(+ repo=repo,+ team_id=repo.team_id,+ identifier="Button",+ baseline_hash=baseline_hash,+ alternate_hash=f"variant_{index}",+ reason=reason,+ expires_at=None if expiry_days is None else now + timedelta(days=expiry_days),+ )++ counts = toleration.count_active_variants_against_current_baseline(repo.id, now=now)++ assert counts.get(SnapshotKey(run_type=RunType.STORYBOOK, identifier="Button"), 0) == expected+def test_get_tolerated_hashes_for_identifier(self, repo):from products.visual_review.backend.models import ToleratedHashdiff --git a/products/visual_review/backend/tests/test_baselines.py b/products/visual_review/backend/tests/test_baselines.pyindex d43f21c7d38e..f21f816a1ca0 100644--- a/products/visual_review/backend/tests/test_baselines.py+++ b/products/visual_review/backend/tests/test_baselines.py@@ -75,6 +75,7 @@ def _mk_snapshot(identifier: str,result: str = SnapshotResult.UNCHANGED,artifact: Artifact | None = None,+ baseline_hash: str = "",is_quarantined: bool = False,tolerated_match: ToleratedHash | None = None,metadata: dict | None = None,@@ -87,6 +88,7 @@ def _mk_snapshot(identifier=identifier,current_hash=artifact.content_hash if artifact else "",current_artifact=artifact,+ baseline_hash=baseline_hash,result=result,is_quarantined=is_quarantined,tolerated_hash_match=tolerated_match,@@ -226,7 +228,7 @@ class TestBaselinesOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):def test_tolerate_counts_respect_30d_and_90d_windows(self):run = _mk_run(self.repo)- _mk_snapshot(run, identifier="flake")+ _mk_snapshot(run, identifier="flake", baseline_hash="b")# 1 tolerate within 30d, 4 within 90d (so 3 are 30-90d old).for offset_days in (5, 40, 60, 80):@@ -256,6 +258,10 @@ class TestBaselinesOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):assert entry.tolerate_count_90d == 4assert result.totals.recently_tolerated == 1 # ≥1 in last 30dassert result.totals.frequently_tolerated == 1 # ≥3 in last 90d+ # No window on the variants: every live row recorded against the hash the baseline holds+ # now still matches, however old it is.+ assert entry.active_variants_current_baseline == 4+ assert result.totals.variant_pileups == 1def test_tolerate_counts_exclude_auto_threshold(self):"""AUTO_THRESHOLD rows are auto-minted by the diff pipeline fordiff --git a/products/visual_review/backend/tests/test_debt_digest_command.py b/products/visual_review/backend/tests/test_debt_digest_command.pynew file mode 100644index 000000000000..16463e7a32d4--- /dev/null+++ b/products/visual_review/backend/tests/test_debt_digest_command.py@@ -0,0 +1,41 @@+"""Tests for the visual_review_debt_digest management command."""++import pytest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError++from posthog.models.team.team import Team++from products.visual_review.backend.logic import repos+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES++_REPO = "org/shared-by-two"++[email protected]_db(databases=PRODUCT_DATABASES)+class TestDebtDigestCommand:+ @pytest.fixture+ def two_teams(self, team):+ other_team = Team.objects.create(organization=team.organization, name="other")+ mine = repos.create_repo(team_id=team.id, repo_external_id=66661, repo_full_name=_REPO)+ theirs = repos.create_repo(team_id=other_team.id, repo_external_id=66662, repo_full_name=_REPO)+ return mine, theirs++ def test_a_name_two_teams_registered_asks_which_one(self, two_teams) -> None:+ with pytest.raises(CommandError, match="more than one team"):+ call_command("visual_review_debt_digest", "--repo", _REPO)++ @pytest.mark.parametrize("which", [0, 1])+ def test_team_id_picks_the_row_that_team_owns(self, two_teams, which: int) -> None:+ wanted = two_teams[which]++ with patch("products.visual_review.backend.logic.debt_digest.send_debt_digest", return_value=[]) as send:+ call_command("visual_review_debt_digest", "--repo", _REPO, "--team-id", str(wanted.team_id))++ assert send.call_args.args[0].id == wanted.id++ def test_an_unknown_repo_is_named_in_the_error(self) -> None:+ with pytest.raises(CommandError, match="No visual review repo named org/nope"):+ call_command("visual_review_debt_digest", "--repo", "org/nope")diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.pyindex d7096cc7c02d..664e76e86b9d 100644--- a/products/visual_review/backend/tests/test_tasks.py+++ b/products/visual_review/backend/tests/test_tasks.py@@ -7,6 +7,8 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from django.core.cache import cache+from parameterized import parameterizedfrom PIL import Image@@ -21,9 +23,15 @@ from products.visual_review.backend.facade.enums import (RunType,SnapshotResult,)-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.logic import artifact_store, debt_digest, runs+from products.visual_review.backend.models import Repo, RunSnapshot, ToleratedHash+from products.visual_review.backend.tasks import tasks+from products.visual_review.backend.tasks.tasks import (+ post_approval_comment,+ process_run_diffs,+ send_visual_review_debt_digest,+ send_visual_review_debt_digests,+)from products.visual_review.backend.tests.conftest import (PRODUCT_DATABASES,VisualReviewTeamScopedTestMixin,@@ -543,3 +551,39 @@ class TestPostApprovalCommentTask:retry_mock.assert_called_once()assert retry_mock.call_args.kwargs["countdown"] == 42+++class TestDebtDigestTask(VisualReviewTeamScopedTestMixin, BaseTest):+ databases = PRODUCT_DATABASES++ def test_a_held_lock_skips_the_run(self) -> None:+ repo = Repo.objects.create(team_id=self.team.id, repo_external_id=55511, repo_full_name="org/locked")+ cache.set(f"visual_review_debt_digest:{repo.id}", "locked", timeout=60)+ try:+ with patch("products.visual_review.backend.logic.debt_digest.send_debt_digest") as send:+ send_visual_review_debt_digest(self.team.id, str(repo.id))+ finally:+ cache.delete(f"visual_review_debt_digest:{repo.id}")++ # Nothing records what was sent, so an overlapping run would post every reminder twice.+ assert send.call_count == 0++ def test_the_fan_out_gives_each_child_a_deadline(self) -> None:+ repo = Repo.objects.create(team_id=self.team.id, repo_external_id=55513, repo_full_name="org/fanned-out")++ with patch("products.visual_review.backend.tasks.tasks.send_visual_review_debt_digest.apply_async") as enqueue:+ send_visual_review_debt_digests()++ # A child without a deadline lets a drained backlog post yesterday's digest next to today's.+ enqueued = {(call.kwargs["args"], call.kwargs["expires"]) for call in enqueue.call_args_list}+ assert ((repo.team_id, str(repo.id)), tasks._DEBT_DIGEST_EXPIRY_SECONDS) in enqueued++ def test_the_scheduled_run_posts_rather_than_previews(self) -> None:+ repo = Repo.objects.create(team_id=self.team.id, repo_external_id=55512, repo_full_name="org/scheduled")+ try:+ with patch("products.visual_review.backend.logic.debt_digest.send_debt_digest") as send:+ send_visual_review_debt_digest(self.team.id, str(repo.id))+ finally:+ cache.delete(f"visual_review_debt_digest:{repo.id}")++ assert send.call_args.kwargs["mode"] == debt_digest.MODE_LIVEdiff --git a/products/visual_review/frontend/components/SnapshotCard.tsx b/products/visual_review/frontend/components/SnapshotCard.tsxindex 13fb893d9f87..719a149a6a27 100644--- a/products/visual_review/frontend/components/SnapshotCard.tsx+++ b/products/visual_review/frontend/components/SnapshotCard.tsx@@ -1,6 +1,6 @@import { useMemo } from 'react'-import { IconFlag, IconPulse, IconWarning } from '@posthog/icons'+import { IconCopy, IconFlag, IconPulse, IconWarning } from '@posthog/icons'import { LemonTag, Link } from '@posthog/lemon-ui'import { dayjs } from 'lib/dayjs'@@ -96,6 +96,7 @@ export function SnapshotCard({const { theme } = parseTheme(entry.identifier)const area = parseArea(entry.identifier)const tolerateCount = entry.tolerate_count_30d+ const variantCount = entry.active_variants_current_baselineconst driftPct = entry.recent_drift_avg ?? 0const driftVisible = driftPct >= DRIFT_DISPLAY_FLOOR_PCTconst driftLoud = driftPct >= DRIFT_WARNING_THRESHOLD_PCT@@ -106,7 +107,7 @@ export function SnapshotCard({? `${thumbnailBasePath}/${encodeURIComponent(entry.identifier)}/`: nullconst href = urls.visualReviewSnapshotHistory(repoId, entry.run_type, entry.identifier)- const hasMeta = driftVisible || tolerateCount > 0 || entry.baseline_change_count > 0+ const hasMeta = driftVisible || tolerateCount > 0 || variantCount > 0 || entry.baseline_change_count > 0const quarantine = entry.quarantine ?? null// Yellow ring (not a 1px border) so the card pulls the eye in a grid@@ -187,7 +188,7 @@ export function SnapshotCard({{area}</LemonTag>{hasMeta && (- <div className="flex items-center gap-2 shrink-0 tabular-nums leading-none">+ <div className="flex flex-wrap items-center justify-end gap-2 tabular-nums leading-none">{driftVisible && (<Tooltiptitle={`Average pixel drift over the last ${RECENT_DRIFT_WINDOW} default-branch runs: ${driftPct.toFixed(@@ -216,6 +217,18 @@ export function SnapshotCard({</span></Tooltip>)}+ {variantCount > 0 && (+ <Tooltip+ title={`${variantCount} accepted variant${+ variantCount === 1 ? '' : 's'+ } of the current baseline`}+ >+ <span className="inline-flex items-center gap-0.5">+ <IconCopy className="w-3 h-3" />+ {variantCount}+ </span>+ </Tooltip>+ )}{entry.baseline_change_count > 0 && (<Tooltiptitle={`Baseline updated ${entry.baseline_change_count} time${diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex f9b0959f100f..dcf8b4cc2ea0 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -75,6 +75,8 @@ export interface BaselineQuarantineSummaryApi {export interface BaselineEntryApi {/** Active quarantine details when `is_quarantined` is true. Null otherwise. */quarantine?: BaselineQuarantineSummaryApi | null+ /** Accepted variants still recorded against this baseline's current hash. Unlike the 30-day and 90-day counts, this has no time window: an accepted variant keeps matching without a new record. A baseline change resets it to zero. */+ active_variants_current_baseline: numberidentifier: stringrun_type: string/** @nullable */@@ -98,6 +100,8 @@ export type BaselineTotalsApiByRunType = { [key: string]: number }export interface BaselineTotalsApi {by_run_type: BaselineTotalsApiByRunType+ /** Baselines carrying three or more accepted variants of their current hash. */+ variant_pileups: numberall_snapshots: numberrecently_tolerated: numberfrequently_tolerated: numberdiff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex fcbcaafe772f..f50c39be4c98 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -12032,6 +12032,8 @@ export namespace Schemas {export interface BaselineEntry {/** Active quarantine details when `is_quarantined` is true. Null otherwise. */quarantine?: BaselineQuarantineSummary | null;+ /** Accepted variants still recorded against this baseline's current hash. Unlike the 30-day and 90-day counts, this has no time window: an accepted variant keeps matching without a new record. A baseline change resets it to zero. */+ active_variants_current_baseline: number;identifier: string;run_type: string;/** @nullable */@@ -12055,6 +12057,8 @@ export namespace Schemas {export interface BaselineTotals {by_run_type: BaselineTotalsByRunType;+ /** Baselines carrying three or more accepted variants of their current hash. */+ variant_pileups: number;all_snapshots: number;recently_tolerated: number;frequently_tolerated: number;diff --git a/tach.toml b/tach.tomlindex 3577b33684b4..40b6c75cfb75 100644--- a/tach.toml+++ b/tach.toml@@ -1001,6 +1001,7 @@ layer = "modules"path = "products.visual_review"depends_on = ["posthog",+ "products.engineering_analytics",]layer = "modules"