: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): add a toleration pile-ups endpoint and MCP tool (#104440)
Julian Bezf23384aba7f8
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.pyindex 9ab8855d5f50..d410eb42abf9 100644--- a/products/visual_review/backend/facade/api.py+++ b/products/visual_review/backend/facade/api.py@@ -20,6 +20,7 @@ from datetime import datetimefrom uuid import UUIDfrom django.contrib.auth import get_user_model+from django.utils import timezonefrom posthog.dataclasses import frozenfrom posthog.egress.github.transport import GitHubRateLimitError@@ -367,6 +368,59 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:)+def get_toleration_pileups(+ repo_id: UUID,+ *,+ window_days: int = contracts.TOLERATION_PILEUP_WINDOW_DAYS,+ min_tolerations: int = contracts.VARIANT_PILEUP_MIN,+ min_automatic_tolerations: int | None = None,+ include_quarantined: bool = True,+ run_type: str | None = None,+ limit: int = 100,+) -> contracts.TolerationPileups:+ """Snapshot identities that keep getting tolerated, biggest manual pile first.++ Backs the pile-ups endpoint, which agents read. The defaults are the debt digest's rule, except+ that quarantined identities stay in the list and are marked, so a reader sees open and muted+ piles alike.+ """+ now = timezone.now()+ quarantined_keys = quarantine.active_quarantine_keys(repo_id, now=now)+ pileups = toleration.list_toleration_pileups(+ repo_id,+ now=now,+ window_days=window_days,+ min_intentional=min_tolerations,+ min_automatic=min_automatic_tolerations,+ )+ matching = sorted(+ (+ (key, counts)+ for key, counts in pileups.items()+ if (include_quarantined or key not in quarantined_keys) and (run_type is None or key.run_type == run_type)+ ),+ key=lambda item: (-item[1].intentional, -item[1].automatic, item[0].run_type, item[0].identifier),+ )+ return contracts.TolerationPileups(+ entries=[+ contracts.TolerationPileupEntry(+ identifier=key.identifier,+ run_type=key.run_type,+ intentional_count=counts.intentional,+ automatic_count=counts.automatic,+ is_quarantined=key in quarantined_keys,+ )+ for key, counts in matching[:limit]+ ],+ window_days=window_days,+ min_tolerations=min_tolerations,+ min_automatic_tolerations=min_automatic_tolerations,+ total=len(matching),+ truncated=len(matching) > limit,+ generated_at=now,+ )++def get_flakiness_overview(repo_id: UUID, team_id: int) -> contracts.FlakinessOverview:"""Snapshot identities carrying rendering instability or an open quarantine.diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.pyindex 2dc92773c2c7..b1e0709a23b2 100644--- a/products/visual_review/backend/facade/contracts.py+++ b/products/visual_review/backend/facade/contracts.py@@ -758,3 +758,27 @@ class FlakinessOverview:totals: FlakinessTotalstruncated: boolgenerated_at: datetime+++@dataclass(frozen=True)+class TolerationPileupEntry:+ """One snapshot identity that keeps getting tolerated."""++ identifier: str+ run_type: str+ intentional_count: int+ automatic_count: int+ is_quarantined: bool+++@dataclass(frozen=True)+class TolerationPileups:+ """Result of the toleration pile-ups endpoint, with the rule it applied."""++ entries: list[TolerationPileupEntry]+ window_days: int+ min_tolerations: int+ min_automatic_tolerations: int | None+ total: int+ truncated: bool+ generated_at: datetimediff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.pyindex aeec2ebe1484..c1ccedf0c8ff 100644--- a/products/visual_review/backend/logic/debt_digest.py+++ b/products/visual_review/backend/logic/debt_digest.py@@ -80,7 +80,7 @@ from posthog.utils import human_list, pluralizefrom products.engineering_analytics.backend.facade.api import resolve_path_ownersfrom products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership-from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, TOLERATION_PILEUP_WINDOW_DAYS, VARIANT_PILEUP_MIN+from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, TOLERATION_PILEUP_WINDOW_DAYSfrom ..facade.enums import RunTypefrom ..models import QuarantinedIdentifier, Repo, Runfrom . import quarantine, run_queries, story_index, toleration@@ -423,14 +423,14 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:expiring = quarantine.list_expiring_quarantines(repo.id, now=now, within_days=_DIGEST_EXPIRY_WINDOW_DAYS)quarantined_keys = quarantine.active_quarantine_keys(repo.id, now=now)piled_up = {- key: count- for key, count in toleration.count_recent_intentional_tolerations(- repo.id, since=now - timedelta(days=TOLERATION_PILEUP_WINDOW_DAYS), newest_run_by_type=newest_run_by_type+ key: counts.intentional+ for key, counts in toleration.list_toleration_pileups(+ 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 tolerations underneath it is a second reminder about# one problem.- if count >= VARIANT_PILEUP_MIN and key not in quarantined_keys+ if key not in quarantined_keys}run_types = {entry.run_type for entry in expiring} | {key.run_type for key in piled_up}diff --git a/products/visual_review/backend/logic/toleration.py b/products/visual_review/backend/logic/toleration.pyindex 56ba4f66a853..bcd5db5f4c37 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 import Counterfrom collections.abc import Mapping-from datetime import datetime+from datetime import datetime, timedeltafrom uuid import UUIDfrom django.db import transactionfrom django.db.models import Count, Qfrom django.utils import timezone+from posthog.dataclasses import frozen+from ..db import WRITER_DB+from ..facade.contracts import TOLERATION_PILEUP_WINDOW_DAYS, VARIANT_PILEUP_MINfrom ..facade.enums import INTENTIONAL_TOLERATE_REASONS, ActorType, ReviewState, SnapshotResult, ToleratedReasonfrom ..models import Run, RunSnapshot, ToleratedHashfrom . import errors, run_queries@@ -137,11 +141,18 @@ def count_active_variants_against_current_baseline(return counts-def count_recent_intentional_tolerations(+@frozen+class TolerationCounts:+ """Tolerations recorded for one snapshot identity in a window, split by who decided them."""++ intentional: int = 0 # a person or agent accepted the rendering+ automatic: int = 0 # the rendering came in under both diff thresholds+++def count_recent_tolerations(repo_id: UUID, *, since: datetime, newest_run_by_type: Mapping[str, Run] | None = None-) -> dict[SnapshotKey, int]:- """How many tolerations a person or agent recorded for each snapshot identity since `since`,- across every baseline.+) -> dict[SnapshotKey, TolerationCounts]:+ """How many tolerations each snapshot identity collected since `since`, across every baseline.The count survives a baseline change, unlike `count_active_variants_against_current_baseline`.A flaky story's baseline often moves between tolerations, so a per-baseline count keeps@@ -150,7 +161,7 @@ def count_recent_intentional_tolerations(Only identities on the newest default-branch runs are counted, so a deleted story drops out.A toleration row has no run type of its own, so it takes the run type of the run it wasdecided in. A row whose run the retention sweep already deleted counts for every run type- that has the identifier. Only non-zero counts are returned.+ that has the identifier. Only identities with at least one toleration are returned."""baseline_hash_by_key = _current_baseline_hashes(repo_id, newest_run_by_type)if not baseline_hash_by_key:@@ -160,22 +171,49 @@ def count_recent_intentional_tolerations(for key in baseline_hash_by_key:keys_by_identifier.setdefault(key.identifier, []).append(key)- counts: dict[SnapshotKey, int] = {}- for identifier, run_type, count in (- ToleratedHash.objects.filter(- repo_id=repo_id,- identifier__in=list(keys_by_identifier),- reason__in=INTENTIONAL_TOLERATE_REASONS,- created_at__gte=since,- )- .values_list("identifier", "source_run__run_type")+ intentional: Counter[SnapshotKey] = Counter()+ automatic: Counter[SnapshotKey] = Counter()+ # No identifier filter in SQL: the repo and window already bound the scan, and a list of+ # every identifier in the universe would only bloat the query.+ for identifier, run_type, reason, count in (+ ToleratedHash.objects.filter(repo_id=repo_id, created_at__gte=since)+ .values_list("identifier", "source_run__run_type", "reason").annotate(c=Count("id"))- .values_list("identifier", "source_run__run_type", "c")+ .values_list("identifier", "source_run__run_type", "reason", "c")):- for key in keys_by_identifier[identifier]:+ bucket = intentional if reason in INTENTIONAL_TOLERATE_REASONS else automatic+ for key in keys_by_identifier.get(identifier, []):if run_type in (None, key.run_type):- counts[key] = counts.get(key, 0) + count- return counts+ bucket[key] += count+ return {+ key: TolerationCounts(intentional=intentional[key], automatic=automatic[key])+ for key in intentional.keys() | automatic.keys()+ }+++def list_toleration_pileups(+ repo_id: UUID,+ *,+ now: datetime,+ window_days: int = TOLERATION_PILEUP_WINDOW_DAYS,+ min_intentional: int = VARIANT_PILEUP_MIN,+ min_automatic: int | None = None,+ newest_run_by_type: Mapping[str, Run] | None = None,+) -> dict[SnapshotKey, TolerationCounts]:+ """Snapshot identities that keep getting tolerated, whether quarantined or not.++ An identity qualifies with `min_intentional` or more tolerations by a person or agent in the+ window, or, when `min_automatic` is set, with that many automatic ones. The defaults are the+ debt digest's rule, and the digest and the pile-ups endpoint share this function so the+ reminder and what an agent reads cannot drift apart.+ """+ return {+ key: counts+ for key, counts in count_recent_tolerations(+ repo_id, since=now - timedelta(days=window_days), newest_run_by_type=newest_run_by_type+ ).items()+ if counts.intentional >= min_intentional or (min_automatic is not None and counts.automatic >= min_automatic)+ }def _current_baseline_hashes(diff --git a/products/visual_review/backend/migrations/0017_toleratedhash_tolerated_repo_created.py b/products/visual_review/backend/migrations/0017_toleratedhash_tolerated_repo_created.pynew file mode 100644index 000000000000..9b5bebb73e37--- /dev/null+++ b/products/visual_review/backend/migrations/0017_toleratedhash_tolerated_repo_created.py@@ -0,0 +1,18 @@+from django.db import migrations, models++from posthog.migration_helpers import SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("visual_review", "0016_quarantinedidentifier_lifted_at_sha"),+ ]++ operations = [+ SafeAddIndexConcurrently(+ model_name="toleratedhash",+ index=models.Index(fields=["repo", "created_at"], name="tolerated_repo_created"),+ ),+ ]diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txtindex 046f442325c1..a156375b72ae 100644--- a/products/visual_review/backend/migrations/max_migration.txt+++ b/products/visual_review/backend/migrations/max_migration.txt@@ -1 +1 @@-0016_quarantinedidentifier_lifted_at_sha+0017_toleratedhash_tolerated_repo_createddiff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.pyindex cf726b2d3f71..3eeb52d927c3 100644--- a/products/visual_review/backend/models.py+++ b/products/visual_review/backend/models.py@@ -345,6 +345,9 @@ class ToleratedHash(ProductTeamModel):]indexes = [models.Index(fields=["repo", "identifier", "baseline_hash"], name="tolerated_lookup"),+ # Recency reads (pile-ups, digest, the baselines page's windowed counts) scan only the+ # window instead of every toleration the repo ever recorded.+ models.Index(fields=["repo", "created_at"], name="tolerated_repo_created"),]def __str__(self) -> str:diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.pyindex 06f5f198ef5d..9a4178e8777f 100644--- a/products/visual_review/backend/presentation/serializers.py+++ b/products/visual_review/backend/presentation/serializers.py@@ -11,6 +11,8 @@ from ..facade.contracts import (FLAKINESS_RATE_DAYS,FLAKINESS_WINDOW_DAYS,PIXEL_DIFF_THRESHOLD_PERCENT,+ TOLERATION_PILEUP_WINDOW_DAYS,+ VARIANT_PILEUP_MIN,AddSnapshotsInput,AddSnapshotsResult,ApproveRunRequestInput,@@ -43,6 +45,8 @@ from ..facade.contracts import (SnapshotHistoryEntry,SnapshotManifestItem,ToleratedHashEntry,+ TolerationPileupEntry,+ TolerationPileups,UpdateRepoRequestInput,UploadTarget,UserBasicInfo,@@ -585,3 +589,87 @@ class FlakinessOverviewSerializer(DataclassSerializer):class Meta:dataclass = FlakinessOverview+++class TolerationPileupsQuerySerializer(serializers.Serializer):+ min_tolerations = serializers.IntegerField(+ default=VARIANT_PILEUP_MIN,+ min_value=1,+ max_value=100,+ help_text=(+ "List a snapshot when a person or agent tolerated it at least this many times in the window. "+ f"The default, {VARIANT_PILEUP_MIN}, is the weekly debt digest's rule. Lower it to see snapshots that "+ "are starting to pile up, raise it to see only the worst ones."+ ),+ )+ min_automatic_tolerations = serializers.IntegerField(+ required=False,+ min_value=1,+ max_value=10000,+ help_text=(+ "Also list a snapshot when it collected at least this many automatic tolerations in the window. "+ "An automatic toleration is a rendering under both diff thresholds, so it never blocked anybody; "+ "many of them still mean the story is unstable. Omit to ignore automatic tolerations when "+ "deciding what to list. With 10, the list matches the Tolerate dialog's quarantine suggestion."+ ),+ )+ window_days = serializers.IntegerField(+ default=TOLERATION_PILEUP_WINDOW_DAYS,+ min_value=1,+ max_value=90,+ help_text=f"How many days back to count tolerations. Defaults to {TOLERATION_PILEUP_WINDOW_DAYS}.",+ )+ include_quarantined = serializers.BooleanField(+ default=True,+ help_text=(+ "Keep snapshots that an active quarantine already covers. They are marked with `is_quarantined`. "+ "Set to false to see only piles nobody has acted on yet."+ ),+ )+ run_type = serializers.CharField(+ required=False,+ max_length=64,+ help_text="Only list snapshots of this run type, for example `storybook` or `playwright`.",+ )+ limit = serializers.IntegerField(+ default=100,+ min_value=1,+ max_value=500,+ help_text="Maximum number of snapshots to return. `total` and `truncated` say whether more matched.",+ )+++class TolerationPileupEntrySerializer(DataclassSerializer):+ identifier = serializers.CharField(help_text="Snapshot identifier, for example a Storybook story id plus theme.")+ run_type = serializers.CharField(help_text="Run type the snapshot belongs to, for example `storybook`.")+ intentional_count = serializers.IntegerField(+ help_text=(+ "Tolerations a person or agent recorded for this snapshot in the window, across every baseline. "+ "Each one accepted a different exact rendering, so a high count means the snapshot renders "+ "differently from run to run."+ )+ )+ automatic_count = serializers.IntegerField(+ help_text="Automatic tolerations in the window: renderings that came in under both diff thresholds."+ )+ is_quarantined = serializers.BooleanField(+ help_text="Whether an active quarantine already covers this snapshot, so it no longer blocks pull requests."+ )++ class Meta:+ dataclass = TolerationPileupEntry+++class TolerationPileupsSerializer(DataclassSerializer):+ entries = TolerationPileupEntrySerializer(many=True, help_text="Matching snapshots, most manual tolerations first.")+ window_days = serializers.IntegerField(help_text="Length of the counting window in days that was applied.")+ min_tolerations = serializers.IntegerField(help_text="Manual toleration threshold that was applied.")+ min_automatic_tolerations = serializers.IntegerField(+ allow_null=True, help_text="Automatic toleration threshold that was applied, or null when none was."+ )+ total = serializers.IntegerField(help_text="How many snapshots matched before `limit` was applied.")+ truncated = serializers.BooleanField(help_text="True when `limit` cut the list short.")+ generated_at = serializers.DateTimeField(help_text="When the list was computed.")++ class Meta:+ dataclass = TolerationPileupsdiff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.pyindex 50968731833b..4ab227d7489b 100644--- a/products/visual_review/backend/presentation/views.py+++ b/products/visual_review/backend/presentation/views.py@@ -64,6 +64,8 @@ from .serializers import (SnapshotHistoryEntrySerializer,SnapshotSerializer,ToleratedHashEntrySerializer,+ TolerationPileupsQuerySerializer,+ TolerationPileupsSerializer,UnquarantineQuerySerializer,UpdateRepoInputSerializer,)@@ -163,6 +165,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"thumbnail","baselines","flakiness",+ "toleration_pileups",]@extend_schema(responses={200: RepoSerializer(many=True)})@@ -389,6 +392,42 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):result = api.get_flakiness_overview(repo_id, self.team_id)return Response(FlakinessOverviewSerializer(instance=result).data)+ @extend_schema(+ parameters=[OpenApiParameter("id", OpenApiTypes.STR, OpenApiParameter.PATH)],+ description=(+ "Snapshots that keep getting tolerated, counted across baselines, most manual tolerations "+ "first. A toleration accepts one exact rendering, so a snapshot that keeps needing them "+ "renders differently from run to run, and the fix belongs in the story. With no parameters "+ f"this is the weekly debt digest's rule ({contracts.VARIANT_PILEUP_MIN} or more tolerations by a "+ f"person or agent in {contracts.TOLERATION_PILEUP_WINDOW_DAYS} days), except that quarantined "+ "snapshots are kept and marked with `is_quarantined`. The list is small and returns fast; "+ "start here to find flaky stories worth fixing, then read one snapshot's history with the "+ "per-snapshot tools."+ ),+ )+ @validated_request(+ query_serializer=TolerationPileupsQuerySerializer,+ responses={200: OpenApiResponse(response=TolerationPileupsSerializer)},+ )+ @action(detail=True, methods=["get"], url_path="toleration-pileups", pagination_class=None)+ def toleration_pileups(self, request: TypedRequest, pk: str, **kwargs) -> Response:+ repo_id = _parse_uuid(pk)+ try:+ api.get_repo(repo_id, team_id=self.team_id)+ except api.RepoNotFoundError:+ return Response({"detail": "Repo not found"}, status=status.HTTP_404_NOT_FOUND)+ query = request.validated_query_data+ result = api.get_toleration_pileups(+ repo_id,+ window_days=query["window_days"],+ min_tolerations=query["min_tolerations"],+ min_automatic_tolerations=query.get("min_automatic_tolerations"),+ include_quarantined=query["include_quarantined"],+ run_type=query.get("run_type"),+ limit=query["limit"],+ )+ return Response(TolerationPileupsSerializer(instance=result).data)+class SnapshotViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):"""Snapshot identities under a repo, keyed by (run_type, identifier).diff --git a/products/visual_review/backend/tests/test_flakiness.py b/products/visual_review/backend/tests/test_flakiness.pyindex 1d324a2291ad..c9d6e02616ab 100644--- a/products/visual_review/backend/tests/test_flakiness.py+++ b/products/visual_review/backend/tests/test_flakiness.py@@ -729,6 +729,43 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):assert len(entry["daily_hard_counts"]) == FLAKINESS_WINDOW_DAYSassert data["totals"]["tracked"] == 1+ @parameterized.expand(+ [+ ("digest_rule_keeps_quarantined_flagged", "", [("muted", 3, 0, True), ("piled", 3, 0, False)], 2, False),+ (+ "automatic_threshold_adds_noisy",+ "?min_automatic_tolerations=2",+ [("muted", 3, 0, True), ("piled", 3, 0, False), ("noisy", 0, 2, False)],+ 3,+ False,+ ),+ ("quarantined_can_be_left_out", "?include_quarantined=false", [("piled", 3, 0, False)], 1, False),+ ("limit_truncates", "?limit=1", [("muted", 3, 0, True)], 2, True),+ ]+ )+ def test_toleration_pileups_endpoint(self, _name, query, expected, total, truncated):+ for identifier, reason, variants in (+ ("piled", ToleratedReason.HUMAN, 3),+ ("muted", ToleratedReason.HUMAN, 3),+ ("once", ToleratedReason.HUMAN, 1),+ ("noisy", ToleratedReason.AUTO_THRESHOLD, 2),+ ):+ _mk_snapshot(self.master_run, identifier=identifier)+ for index in range(variants):+ self._mk_variant(identifier=identifier, alternate_hash=f"v{index}", reason=reason)+ self._mk_quarantine("muted")++ url = f"/api/projects/{self.team.id}/visual_review/repos/{self.repo.id}/toleration-pileups/{query}"+ response = self.client.get(url)++ assert response.status_code == 200+ data = response.json()+ assert [+ (entry["identifier"], entry["intentional_count"], entry["automatic_count"], entry["is_quarantined"])+ for entry in data["entries"]+ ] == expected+ assert (data["total"], data["truncated"]) == (total, truncated)+def test_endpoint_404_for_unknown_repo(self):url = f"/api/projects/{self.team.id}/visual_review/repos/{uuid4()}/flakiness/"response = self.client.get(url)diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.tsindex 409bd60ec389..f7a037643fc3 100644--- a/products/visual_review/frontend/generated/api.schemas.ts+++ b/products/visual_review/frontend/generated/api.schemas.ts@@ -303,6 +303,39 @@ export interface UnquarantineQueryApi {identifier: string}+export interface TolerationPileupEntryApi {+ /** Snapshot identifier, for example a Storybook story id plus theme. */+ identifier: string+ /** Run type the snapshot belongs to, for example `storybook`. */+ run_type: string+ /** Tolerations a person or agent recorded for this snapshot in the window, across every baseline. Each one accepted a different exact rendering, so a high count means the snapshot renders differently from run to run. */+ intentional_count: number+ /** Automatic tolerations in the window: renderings that came in under both diff thresholds. */+ automatic_count: number+ /** Whether an active quarantine already covers this snapshot, so it no longer blocks pull requests. */+ is_quarantined: boolean+}++export interface TolerationPileupsApi {+ /** Matching snapshots, most manual tolerations first. */+ entries: TolerationPileupEntryApi[]+ /** Length of the counting window in days that was applied. */+ window_days: number+ /** Manual toleration threshold that was applied. */+ min_tolerations: number+ /**+ * Automatic toleration threshold that was applied, or null when none was.+ * @nullable+ */+ min_automatic_tolerations: number | null+ /** How many snapshots matched before `limit` was applied. */+ total: number+ /** True when `limit` cut the list short. */+ truncated: boolean+ /** When the list was computed. */+ generated_at: string+}+export type SearchMatchTypeEnumApi = (typeof SearchMatchTypeEnumApi)[keyof typeof SearchMatchTypeEnumApi]export const SearchMatchTypeEnumApi = {@@ -662,6 +695,43 @@ export type VisualReviewReposThumbnailsRetrieveParams = {run_type?: string}+export type VisualReviewReposTolerationPileupsRetrieveParams = {+ /**+ * Keep snapshots that an active quarantine already covers. They are marked with `is_quarantined`. Set to false to see only piles nobody has acted on yet.+ */+ include_quarantined?: boolean+ /**+ * Maximum number of snapshots to return. `total` and `truncated` say whether more matched.+ * @minimum 1+ * @maximum 500+ */+ limit?: number+ /**+ * Also list a snapshot when it collected at least this many automatic tolerations in the window. An automatic toleration is a rendering under both diff thresholds, so it never blocked anybody; many of them still mean the story is unstable. Omit to ignore automatic tolerations when deciding what to list. With 10, the list matches the Tolerate dialog's quarantine suggestion.+ * @minimum 1+ * @maximum 10000+ */+ min_automatic_tolerations?: number+ /**+ * List a snapshot when a person or agent tolerated it at least this many times in the window. The default, 3, is the weekly debt digest's rule. Lower it to see snapshots that are starting to pile up, raise it to see only the worst ones.+ * @minimum 1+ * @maximum 100+ */+ min_tolerations?: number+ /**+ * Only list snapshots of this run type, for example `storybook` or `playwright`.+ * @minLength 1+ * @maxLength 64+ */+ run_type?: string+ /**+ * How many days back to count tolerations. Defaults to 30.+ * @minimum 1+ * @maximum 90+ */+ window_days?: number+}+export type VisualReviewReposRunsListParams = {/*** Number of results to return per page.diff --git a/products/visual_review/frontend/generated/api.ts b/products/visual_review/frontend/generated/api.tsindex ac117665ffcb..7a4bfa4e97b8 100644--- a/products/visual_review/frontend/generated/api.ts+++ b/products/visual_review/frontend/generated/api.ts@@ -34,12 +34,14 @@ import type {ReviewStateCountsApi,RunApi,SnapshotApi,+ TolerationPileupsApi,UnquarantineQueryApi,VisualReviewReposListParams,VisualReviewReposQuarantineListParams,VisualReviewReposRunsListParams,VisualReviewReposSnapshotsListParams,VisualReviewReposThumbnailsRetrieveParams,+ VisualReviewReposTolerationPileupsRetrieveParams,VisualReviewRunsListParams,VisualReviewRunsSnapshotHistoryListParams,VisualReviewRunsSnapshotsListParams,@@ -290,6 +292,41 @@ export const visualReviewReposThumbnailsRetrieve = async (})}+export const getVisualReviewReposTolerationPileupsRetrieveUrl = (+ projectId: string,+ id: string,+ params?: VisualReviewReposTolerationPileupsRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/visual_review/repos/${id}/toleration-pileups/?${stringifiedParams}`+ : `/api/projects/${projectId}/visual_review/repos/${id}/toleration-pileups/`+}++/**+ * Snapshots that keep getting tolerated, counted across baselines, most manual tolerations first. A toleration accepts one exact rendering, so a snapshot that keeps needing them renders differently from run to run, and the fix belongs in the story. With no parameters this is the weekly debt digest's rule (3 or more tolerations by a person or agent in 30 days), except that quarantined snapshots are kept and marked with `is_quarantined`. The list is small and returns fast; start here to find flaky stories worth fixing, then read one snapshot's history with the per-snapshot tools.+ */+export const visualReviewReposTolerationPileupsRetrieve = async (+ projectId: string,+ id: string,+ params?: VisualReviewReposTolerationPileupsRetrieveParams,+ options?: RequestInit+): Promise<TolerationPileupsApi> => {+ return apiMutator<TolerationPileupsApi>(getVisualReviewReposTolerationPileupsRetrieveUrl(projectId, id, params), {+ ...options,+ method: 'GET',+ })+}+export const getVisualReviewReposRunsListUrl = (projectId: string,repoId: string,diff --git a/products/visual_review/mcp/tools.yaml b/products/visual_review/mcp/tools.yamlindex 296fad9b504a..99e16e2b0afc 100644--- a/products/visual_review/mcp/tools.yaml+++ b/products/visual_review/mcp/tools.yaml@@ -214,6 +214,32 @@ tools:visual-review-repos-thumbnails-retrieve:operation: visual_review_repos_thumbnails_retrieveenabled: false+ visual-review-repos-toleration-pileups-retrieve:+ operation: visual_review_repos_toleration_pileups_retrieve+ enabled: false+ scopes:+ - visual_review:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: Visual review toleration pile-ups+ description: >+ Snapshots in a repo that keep getting tolerated, counted across baselines, most manual tolerations first. A+ toleration accepts one exact rendering, so a snapshot that keeps needing them renders differently from run+ to run, and the fix belongs in the story (a pinned date, a disabled animation, a wait for a loader). Called+ with no parameters it applies the weekly debt digest's rule and keeps quarantined snapshots, marked with+ `is_quarantined`. Tune it with `min_tolerations`, `min_automatic_tolerations`, `window_days`,+ `include_quarantined`, `run_type` and `limit`; the response echoes the rule it applied. The list is short+ and returns quickly, so use it instead of the flakiness overview to find flaky stories worth fixing, then+ read one snapshot's history with `visual-review-runs-snapshot-history-list` or its tolerations with+ `visual-review-runs-tolerated-hashes-list`.+ param_overrides:+ id:+ description: The repo's UUID, from `visual-review-repos-list`.+ aliases:+ - repo_id+ feature_flag: visual-reviewvisual-review-runs-add-snapshots-create:operation: visual_review_runs_add_snapshots_createenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex f3c438745bdf..df95d0688c57 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -96873,6 +96873,39 @@ export namespace Schemas {tags?: string[];}+ export interface TolerationPileupEntry {+ /** Snapshot identifier, for example a Storybook story id plus theme. */+ identifier: string;+ /** Run type the snapshot belongs to, for example `storybook`. */+ run_type: string;+ /** Tolerations a person or agent recorded for this snapshot in the window, across every baseline. Each one accepted a different exact rendering, so a high count means the snapshot renders differently from run to run. */+ intentional_count: number;+ /** Automatic tolerations in the window: renderings that came in under both diff thresholds. */+ automatic_count: number;+ /** Whether an active quarantine already covers this snapshot, so it no longer blocks pull requests. */+ is_quarantined: boolean;+ }++ export interface TolerationPileups {+ /** Matching snapshots, most manual tolerations first. */+ entries: TolerationPileupEntry[];+ /** Length of the counting window in days that was applied. */+ window_days: number;+ /** Manual toleration threshold that was applied. */+ min_tolerations: number;+ /**+ * Automatic toleration threshold that was applied, or null when none was.+ * @nullable+ */+ min_automatic_tolerations: number | null;+ /** How many snapshots matched before `limit` was applied. */+ total: number;+ /** True when `limit` cut the list short. */+ truncated: boolean;+ /** When the list was computed. */+ generated_at: string;+ }+/*** Whether the current organization has each toolbar plan entitlement, keyed by feature name.*/@@ -113626,6 +113659,43 @@ export namespace Schemas {run_type?: string;};+ export type VisualReviewReposTolerationPileupsRetrieveParams = {+ /**+ * Keep snapshots that an active quarantine already covers. They are marked with `is_quarantined`. Set to false to see only piles nobody has acted on yet.+ */+ include_quarantined?: boolean;+ /**+ * Maximum number of snapshots to return. `total` and `truncated` say whether more matched.+ * @minimum 1+ * @maximum 500+ */+ limit?: number;+ /**+ * Also list a snapshot when it collected at least this many automatic tolerations in the window. An automatic toleration is a rendering under both diff thresholds, so it never blocked anybody; many of them still mean the story is unstable. Omit to ignore automatic tolerations when deciding what to list. With 10, the list matches the Tolerate dialog's quarantine suggestion.+ * @minimum 1+ * @maximum 10000+ */+ min_automatic_tolerations?: number;+ /**+ * List a snapshot when a person or agent tolerated it at least this many times in the window. The default, 3, is the weekly debt digest's rule. Lower it to see snapshots that are starting to pile up, raise it to see only the worst ones.+ * @minimum 1+ * @maximum 100+ */+ min_tolerations?: number;+ /**+ * Only list snapshots of this run type, for example `storybook` or `playwright`.+ * @minLength 1+ * @maxLength 64+ */+ run_type?: string;+ /**+ * How many days back to count tolerations. Defaults to 30.+ * @minimum 1+ * @maximum 90+ */+ window_days?: number;+ };+export type VisualReviewReposRunsListParams = {/*** Number of results to return per page.