Skip to content

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

feat(visual-review): send the story index from ci and filter by team (#100074)

Julian Bez85ff1edfce46
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index b730cab3207e..da6f6a6203aa 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10021,9 +10021,9 @@ snapshots:
scenes-app-visual-review-flakiness--nothing-to-show--light:
hash: v1.k794b7964.099f7cf91596a9cb775d2936404ce36f55ff670df7b02e336fa9e68dbcbc3f64.SEL1SJqeSDSHYy8DECMu7cK3hXN73TQe6QquscuJIFQ
scenes-app-visual-review-flakiness--unstable--dark:
- hash: v1.k794b7964.279785cef1cdca7baf63fce81ff85ec35e30399a062c78c376d79e6f1e3e4148.29947X3E4KxIBVIIESxhsPeQzbaESc41kwWzIkDEY3E
+ hash: v1.k794b7964.12bc6373464176d7fb6b9251bb7d6342cd381a64e3ee28c8380045b06f5e97ec.BLZ-Fbl_W9xx4oAA39xVucIxMtSpBAzm5Pwp6f1Bk6w
scenes-app-visual-review-flakiness--unstable--light:
- hash: v1.k794b7964.b7ed7d1fd134416708818961f5d8c2c4ac1cfaa6d9337fc9798015cff0ff446c.ArB6eVT85c9Vwx5S4ZE5MvBPfo9KZ3VKqWYLUNLInMs
+ hash: v1.k794b7964.26ff0c274624f9d1ea71f4377d104d5e4feae204ba8ea0b68735c7f5fae8423e.WaXT0zPJ1WHOerBWKkJmHERCIZwpJT_L_4AHvWL3bSE
scenes-app-visual-review-run--ready-to-finalize--dark:
hash: v1.k794b7964.879549ba86b942a0497ef5b08bb0172ac58c62fe8da41a21584c82bea231db20.lG7LsOxr5tzXDBwFMJwt3c7IgoQuIH6h8qlUZnPNJVw
scenes-app-visual-review-run--ready-to-finalize--light:
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 0793a72c11d3..fa10675469b7 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -1086,12 +1086,9 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="sweep visual review retention",
)
- # The digest itself posts weekly, but it reads a Storybook build artifact GitHub keeps for one
- # day. Running twice a day pulls that story index into the cache while the artifact still
- # exists; the task posts only on the Monday morning run.
add_periodic_task_with_expiry(
sender,
- crontab(hour="7,19", minute="30"),
+ crontab(day_of_week="mon", hour="7", minute="30"),
send_visual_review_debt_digests.s(),
name="send visual review debt digests",
expires_seconds=60 * 60,
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index ea58ec701ba6..4f9b376bbeaa 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -39,6 +39,7 @@ The windows and the reasons behind them are constants in `backend/logic/retentio
An artifact goes when no snapshot of the repo points at it or names its hash, no artifact uses it as a thumbnail, and it is over 7 days old.
- Rows go before objects, and run registration and the delete share a per-repo lock, so a run is never told an artifact exists that the sweep then removes.
An 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.
+- A story-to-file map goes when the sweep deletes the last run that names it.
- Each invocation is capped by rows and by a time budget, so a backlog drains over days.
### Weekly debt digest
@@ -46,8 +47,6 @@ The windows and the reasons behind them are constants in `backend/logic/retentio
Every Monday morning a 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 Monday both conditions below are evaluated from current data, and nothing is stored about what was sent.
An item repeats every week while it stands, and stops the week the condition no longer holds.
-The same task runs twice a day, and only the Monday morning run posts.
-The other runs read the Storybook story index into the cache, because the build artifact it comes from is short lived and the Monday run would otherwise have nothing to attribute against.
Each message is Block Kit.
The lead names the team and the week, and counts each condition that has items, with buttons to the repository's flakiness overview and its snapshots.
@@ -75,12 +74,13 @@ A baseline change invalidates the tolerations recorded against the old baseline:
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.
+Attribution runs through the story index of the newest default-branch Storybook run, and then through `owners.yaml`.
+`vr run upload --storybook-index <index.json> --storybook-root <dir>` turns the build's `index.json` into a story-to-file map, and each default-branch run records the map's SHA-256 in `metadata["story_index_hash"]`.
+The map is stored once per distinct content, under `visual_review/<repo_id>/story-index/<hash>.json`, and uploaded only when the store does not hold that hash yet.
+A reader accepts the stored bytes only when they hash to their name.
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 eight days, and the key rotates on its own whenever the baseline moves.
-The cache has to outlive a week, because the run that reads the artifact and the run that posts are usually days apart.
+The parsed map is cached by its hash, so a cached copy is never stale.
Nothing is guessed from the identifier: a story name is not a path.
Only Storybook runs are attributed today.
@@ -88,7 +88,7 @@ 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 the message carries.
- **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.
+- **Ownership could not be worked out.** The newest default-branch run recorded no story index, the stored map could not be read, or the run type is not supported yet.
All three go to whoever owns `products/visual_review/`, in a message of their own rather than inside the digest those maintainers get for what they own.
Holding an item until a team takes it is not owning it, and the wording says so.
@@ -96,8 +96,6 @@ The message goes out only when at least one item asks somebody to act.
The first two outcomes are listed, each with a button to the file or the snapshot.
The third is only counted in the footer, because it asks the reader for nothing; the reasons go to the log instead.
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, so the digest reads it on the day the baseline moves and serves the Monday post from the cache.
-A baseline whose artifact expired before any run read it 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.
@@ -105,7 +103,7 @@ A shared Slack channel is refused, so a name match never carries an internal rem
The digest is off for a repository until `debt_digest_enabled` is set on it.
Set it through the repo API (`PATCH /api/projects/:team_id/visual_review/repos/:id/`), the `visual-review-repos-partial-update` MCP tool, or Django admin.
-The beat task runs twice a day and fans out only to the repositories that are on.
+The beat task runs on Monday morning and fans out only to the repositories that are on.
A repository that owes nothing posts nothing.
`./manage.py visual_review_debt_digest --repo owner/name [--mode preview]` runs one repository by hand on any day, whatever `debt_digest_enabled` says, because a run somebody starts is already a decision to send it.
@@ -166,6 +164,7 @@ Setup job: `vr run create --type storybook`
Each shard: `vr run upload --run-id <id> --dir ./screenshots`
- hash PNGs, POST /runs/{id}/add-snapshots
- upload missing artifacts to S3
+ - with --storybook-index: send the story-to-file map's hash, upload the map if missing
(shards run in parallel, idempotent per identifier)
│
▼
@@ -194,7 +193,7 @@ The CLI uploads directly to S3 via presigned POST URLs — the backend never pro
**`vr run create`** — creates an empty pending run, outputs the run ID to stdout. Call once before shards. Default `--purpose review`; pass `--purpose observe` on master to make the run tracking-only (non-approvable, no PR comment).
-**`vr run upload`** — per-shard: hashes PNGs in a directory, sends identifiers + hashes via `add-snapshots`, uploads missing artifacts.
+**`vr run upload`** — per-shard: hashes PNGs in a directory, sends identifiers + hashes via `add-snapshots`, uploads missing artifacts. Pass `--storybook-index <index.json> --storybook-root <dir>` to send the Storybook build's story-to-file map, which the debt digest and the flakiness page use to find each snapshot's owning team. A map that cannot be read or sent is logged and does not fail the upload.
**`vr run complete`** — triggers completion (classification, removal detection, diffs).
Exits 1 if unapproved changes are detected, 0 if clean or `--auto-approve` is set, and 2 if the command itself failed (auth, network, timeout, backend processing).
@@ -241,6 +240,11 @@ The share is split in two, because the two cost different things: a `hard` run f
Rows are read over 30 days but rated over 7.
The rate has to lapse before the history does, so a quarantine over a snapshot that stopped failing last week becomes liftable while the activity strip still shows what it used to do.
+The Team facet narrows the list to the snapshots one team owns.
+Each Storybook entry carries `owner_team`, resolved the same way as the debt digest: the newest default-branch run's story index names the story file, and `owners.yaml` names the team that owns it.
+`unowned` means no entry covers the file, and a null owner means the file or its owner is unknown, so the row only appears when no team is selected.
+The digest's "Open flakiness overview" button links here with `#teams=<team slug>`.
+
The states are an urgency ladder, and each rung asks for a different fix:
| State | Meaning | Fix |
diff --git a/products/visual_review/backend/facade/api.py b/products/visual_review/backend/facade/api.py
index 7acab1da8428..9ab8855d5f50 100644
--- a/products/visual_review/backend/facade/api.py
+++ b/products/visual_review/backend/facade/api.py
@@ -38,10 +38,12 @@ from ..logic import (
flakiness,
gating,
history,
+ owners,
quarantine,
repos,
run_queries,
runs,
+ story_index,
thumbnails,
toleration,
)
@@ -365,13 +367,16 @@ def get_baselines_overview(repo_id: UUID) -> contracts.BaselineOverview:
)
-def get_flakiness_overview(repo_id: UUID) -> contracts.FlakinessOverview:
+def get_flakiness_overview(repo_id: UUID, team_id: int) -> contracts.FlakinessOverview:
"""Snapshot identities carrying rendering instability or an open quarantine.
Backs the flakiness page. See `flakiness.get_flakiness_overview` for the
scoping rule and query shape.
"""
raw = flakiness.get_flakiness_overview(repo_id)
+ owner_team_by_key = owners.owner_teams(
+ repos.get_repo(repo_id, team_id), [flakiness.snapshot_key(row) for row in raw.rows], raw.newest_run_by_type
+ )
quarantine_user_ids = {
row.quarantine.created_by_id for row in raw.rows if row.quarantine and row.quarantine.created_by_id
@@ -414,6 +419,7 @@ def get_flakiness_overview(repo_id: UUID) -> contracts.FlakinessOverview:
if row.quarantine is not None
else None
),
+ owner_team=owner_team_by_key.get(flakiness.snapshot_key(row)),
)
)
@@ -523,7 +529,15 @@ def add_snapshots(input: contracts.AddSnapshotsInput, run_id: UUID, team_id: int
contracts.UploadTarget(content_hash=u["content_hash"], url=u["url"], fields=u["fields"]) for u in uploads
]
- return contracts.AddSnapshotsResult(added=added, uploads=upload_targets)
+ story_index_upload = None
+ if input.story_index_hash:
+ upload = story_index.register_story_index(run_id, team_id, input.story_index_hash)
+ if upload is not None:
+ story_index_upload = contracts.UploadTarget(
+ content_hash=input.story_index_hash, url=upload.url, fields=upload.fields
+ )
+
+ return contracts.AddSnapshotsResult(added=added, uploads=upload_targets, story_index_upload=story_index_upload)
def get_run(run_id: UUID, team_id: int | None = None) -> contracts.Run:
diff --git a/products/visual_review/backend/facade/contracts.py b/products/visual_review/backend/facade/contracts.py
index 771d02646ef1..2b5740635f5c 100644
--- a/products/visual_review/backend/facade/contracts.py
+++ b/products/visual_review/backend/facade/contracts.py
@@ -150,6 +150,7 @@ class AddSnapshotsInput:
snapshots: list[SnapshotManifestItem]
baseline_hashes: dict[str, str] = field(default_factory=dict)
+ story_index_hash: str = ""
@dataclass(frozen=True)
@@ -158,6 +159,7 @@ class AddSnapshotsResult:
added: int
uploads: list[UploadTarget]
+ story_index_upload: UploadTarget | None = None
@dataclass(frozen=True)
@@ -712,6 +714,9 @@ class FlakinessEntry:
# between extending it and lifting it.
needs_decision: bool
quarantine: BaselineQuarantineSummary | None = None
+ # Team that owns the story file, `UNOWNED_TEAM` when no entry covers it, and None when
+ # ownership is unknown.
+ owner_team: str | None = None
@dataclass(frozen=True)
diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.py
index fbc89ea76b49..2bade52746f5 100644
--- a/products/visual_review/backend/logic/debt_digest.py
+++ b/products/visual_review/backend/logic/debt_digest.py
@@ -27,9 +27,8 @@ index to read. All three go to the visual review maintainers, in a message of th
inside the digest those maintainers get for what they own, because holding an item until a team
takes it is not owning it.
-GitHub keeps that build artifact for one day, so a baseline set on any other day of the week has no
-readable artifact left by Monday. The scheduled task therefore runs twice a day: every run reads the
-index into the cache while the artifact still exists, and only the Monday morning run posts.
+The CLI uploads that story index with the run that built it, named by its content hash, so the
+digest reads the index of the newest default-branch Storybook run and needs nothing else from CI.
Every message is Block Kit: a lead naming the team and the counts, then one thread reply per
condition, with the one action that resolves an item on a button beside it.
@@ -37,7 +36,6 @@ condition, with the one action that resolves an item on a button beside it.
from __future__ import annotations
-from calendar import MONDAY
from collections.abc import Mapping, Sequence
from datetime import date, datetime, timedelta
from enum import StrEnum
@@ -98,8 +96,6 @@ _PRODUCER: Producer = "visual_review"
# 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.
@@ -119,10 +115,6 @@ MODES = (MODE_PREVIEW, MODE_LIVE)
# seven days apart, and without the overlap a quarantine expiring in that gap is never reported.
_DIGEST_EXPIRY_WINDOW_DAYS = FLAKINESS_EXPIRY_SOON_DAYS + 1
-# A run at or after this hour posts nothing, so the second run of a Monday only warms the story
-# index. Late enough that a child task held in a queue still counts as the morning run it came from.
-_POSTS_BEFORE_HOUR_UTC = 12
-
_LEAD_BODY = "Each item and its action is in the thread."
_LEAD_LAPSE_NOTE = "Quarantines that lapse start failing the gate again on the next run."
_QUARANTINE_HEADING = (
@@ -395,51 +387,26 @@ def _display_names(user_ids: set[int]) -> dict[int, str]:
}
-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.
+ One map read per run type, not per item. A run type nothing owes today is never read, so a repo
+ with no Storybook debt reads no map 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"
- )
+ sources[run_type] = story_index.latest_story_index(repo, newest_run_by_type)
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)
+ source = sources[run_type]
if isinstance(source, str):
return Attribution(kind=AttributionKind.UNAVAILABLE, detail=source)
path = story_index.story_path(source, identifier)
@@ -712,7 +679,11 @@ def lead_message(repo: Repo, digest: TeamDigest, now: datetime) -> SlackMessage:
section_block(f"{_LEAD_BODY} {_LEAD_LAPSE_NOTE}" if digest.expiring_quarantines else _LEAD_BODY),
actions_block(
[
- SlackButton(text="Open flakiness overview", url=_repo_flakiness_url(repo), primary=True),
+ SlackButton(
+ text="Open flakiness overview",
+ url=f"{_repo_flakiness_url(repo)}#teams={quote(digest.team_slug, safe='')}",
+ primary=True,
+ ),
SlackButton(text="Open snapshots", url=_repo_snapshots_url(repo)),
]
),
@@ -967,32 +938,6 @@ def _send_one(
return _post_text(post)
-def posts_today(now: datetime) -> bool:
- """Whether a run at this moment posts the digest, or only warms the story index.
-
- The weekday and the hour are read here rather than passed down from the beat, because that
- keeps the child task's arguments unchanged and there is only one rule to read.
- """
- return now.weekday() == MONDAY and now.hour < _POSTS_BEFORE_HOUR_UTC
-
-
-def warm_story_index(repo: Repo) -> None:
- """Read the story index behind the repo's current Storybook baseline into the cache.
-
- Nothing is evaluated and nothing is posted. This runs on the days the digest does not, so the
- weekly post still finds an index for a baseline whose build artifact GitHub has since deleted.
- """
- newest_run_by_type = run_queries.newest_run_by_run_type(run_queries.latest_default_branch_runs(repo.id))
- run_types: set[str] = {RunType.STORYBOOK}
- source = _attribution_sources(repo, run_types, newest_run_by_type)[RunType.STORYBOOK]
- logger.info(
- "visual_review.debt_digest_story_index_warmed",
- repo_id=str(repo.id),
- team_id=repo.team_id,
- read=isinstance(source, story_index.StoryIndex),
- )
-
-
def repos_in_scope() -> list[Repo]:
"""Every repo that opted in, oldest first.
diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.py
index 1395457d0d16..7bd6289835d5 100644
--- a/products/visual_review/backend/logic/flakiness.py
+++ b/products/visual_review/backend/logic/flakiness.py
@@ -445,6 +445,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:
return _FlakinessRaw(
rows=listed,
+ newest_run_by_type=newest_run_by_type,
snapshots_by_key=snapshots_by_key,
tracked_total=tracked_total,
totals_broken=sum(1 for row in rows if row.state == FlakinessState.BROKEN),
@@ -500,6 +501,7 @@ def _quarantine_only_raw(
listed = rows[:max_entries]
return _FlakinessRaw(
rows=listed,
+ newest_run_by_type={},
snapshots_by_key={},
tracked_total=0,
totals_broken=0,
@@ -769,6 +771,8 @@ class _FlakinessRaw:
totals_quarantined: int
totals_needs_decision: int
by_run_type: dict[str, int]
+ # The runs the scores were read from, so a caller needing them does not query again.
+ newest_run_by_type: dict[str, Run]
truncated: bool
generated_at: datetime
@@ -786,6 +790,7 @@ class _FlakinessRaw:
totals_quarantined=0,
totals_needs_decision=0,
by_run_type={},
+ newest_run_by_type={},
truncated=False,
generated_at=generated_at,
)
diff --git a/products/visual_review/backend/logic/github_api.py b/products/visual_review/backend/logic/github_api.py
index ec6d1b595985..ef69806721d4 100644
--- a/products/visual_review/backend/logic/github_api.py
+++ b/products/visual_review/backend/logic/github_api.py
@@ -159,7 +159,6 @@ 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:
@@ -175,9 +174,7 @@ def _github_api_request(
github = get_github_integration_for_repo(repo)
- response = github.api_request(
- method, f"/repos/{repo.repo_full_name}/{safe_path}", params=params, json_body=json, timeout=timeout
- )
+ response = github.api_request(method, f"/repos/{repo.repo_full_name}/{safe_path}", 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)
@@ -192,7 +189,7 @@ def _github_api_request(
repo.save(update_fields=["repo_full_name"])
response = github.api_request(
- method, f"/repos/{new_full_name}/{safe_path}", params=params, json_body=json, timeout=timeout
+ method, f"/repos/{new_full_name}/{safe_path}", json_body=json, timeout=timeout
)
return response
diff --git a/products/visual_review/backend/logic/owners.py b/products/visual_review/backend/logic/owners.py
new file mode 100644
index 000000000000..4aa41ac52122
--- /dev/null
+++ b/products/visual_review/backend/logic/owners.py
@@ -0,0 +1,57 @@
+"""The team that owns each snapshot, read from the story index and the repository's ownership files."""
+
+from collections.abc import Iterable, Mapping
+
+import structlog
+
+from products.engineering_analytics.backend.facade.api import resolve_path_owners
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM
+
+from ..facade.enums import RunType
+from ..models import Repo, Run
+from . import story_index
+from .run_queries import SnapshotKey
+
+logger = structlog.get_logger(__name__)
+
+# Each distinct story file adds the ownership files of its parent directories to one batch of GitHub
+# reads. A snapshot set that names more story files than a real Storybook build has is left without
+# owners, so a crafted story index cannot turn one page load into thousands of fetches.
+_MAX_OWNED_PATHS = 2_000
+
+
+def owner_teams(
+ repo: Repo, keys: Iterable[SnapshotKey], newest_run_by_type: Mapping[str, Run]
+) -> dict[SnapshotKey, str]:
+ """The owning team of each Storybook snapshot whose story file is known.
+
+ A key is left out when there is no team to name: the run type has no story index, the newest
+ default-branch run sent none, the story is not in it, or the ownership files could not be read.
+ `UNOWNED_TEAM` means the file is known and no ownership entry covers it.
+ """
+ storybook_keys = [key for key in keys if key.run_type == RunType.STORYBOOK]
+ if not storybook_keys:
+ return {}
+
+ index = story_index.latest_story_index(repo, newest_run_by_type)
+ if isinstance(index, str):
+ return {}
+
+ path_by_key: dict[SnapshotKey, str] = {}
+ for key in storybook_keys:
+ path = story_index.story_path(index, key.identifier)
+ if path is not None:
+ path_by_key[key] = path
+ if not path_by_key:
+ return {}
+
+ paths = sorted(set(path_by_key.values()))
+ if len(paths) > _MAX_OWNED_PATHS:
+ logger.warning("visual_review.owner_teams_too_many_paths", repo_id=str(repo.id), paths=len(paths))
+ return {}
+
+ ownership = resolve_path_owners(repo.repo_full_name, paths)
+ if not ownership.resolved:
+ logger.info("visual_review.owner_teams_unresolved", repo_id=str(repo.id))
+ return {}
+ return {key: ownership.team_by_path.get(path, UNOWNED_TEAM) for key, path in path_by_key.items()}
diff --git a/products/visual_review/backend/logic/retention.py b/products/visual_review/backend/logic/retention.py
index fab906dad817..f8b1ab63e840 100644
--- a/products/visual_review/backend/logic/retention.py
+++ b/products/visual_review/backend/logic/retention.py
@@ -10,6 +10,7 @@ from uuid import UUID
from django.db import connections, transaction
from django.db.models import Exists, OuterRef, Q, QuerySet
+from django.db.models.fields.json import KeyTextTransform
from django.utils import timezone
import structlog
@@ -19,8 +20,8 @@ from posthog.dataclasses import frozen
from ..db import WRITER_DB
from ..facade.enums import RunStatus
from ..models import Artifact, Repo, Run, RunSnapshot
-from ..storage import ArtifactStorage
-from . import artifact_store, run_queries
+from ..storage import ArtifactStorage, StoryIndexStorage
+from . import artifact_store, run_queries, story_index
logger = structlog.get_logger(__name__)
@@ -105,6 +106,7 @@ class RetentionSweepResult:
runs_deleted: int
artifacts_deleted: int
objects_leaked: int
+ story_indexes_deleted: int = 0
class RetentionSweep:
@@ -117,6 +119,8 @@ class RetentionSweep:
self.team_id = repo.team_id
self.now = now
self.deadline = deadline
+ # Hashes of the story-to-file maps named by runs this sweep deleted.
+ self.released_story_index_hashes: set[str] = set()
def _out_of_time(self) -> bool:
return time.monotonic() >= self.deadline
@@ -183,6 +187,11 @@ class RetentionSweep:
def _delete_runs(self, run_ids: list[UUID]) -> int:
deleted = 0
+ hash_by_run_id = dict(
+ self._runs()
+ .filter(id__in=run_ids, metadata__has_key=story_index.METADATA_KEY)
+ .values_list("id", KeyTextTransform(story_index.METADATA_KEY, "metadata"))
+ )
# One run per DELETE, in the order given (oldest first). Django applies
# SET_NULL to the runs that point at a deleted run before it deletes
# anything, so a batch that holds two links of one supersession chain
@@ -200,7 +209,10 @@ class RetentionSweep:
with transaction.atomic(using=WRITER_DB):
self._splice_out_of_chain(run_id)
_total, per_model = self._runs().filter(id=run_id).delete()
- deleted += per_model.get(Run._meta.label, 0)
+ run_deleted = per_model.get(Run._meta.label, 0)
+ deleted += run_deleted
+ if run_deleted and run_id in hash_by_run_id:
+ self.released_story_index_hashes.add(hash_by_run_id[run_id])
return deleted
def delete_expired_runs(self) -> int:
@@ -275,6 +287,36 @@ class RetentionSweep:
)
return ArtifactSweepResult(deleted=deleted, objects_leaked=objects_leaked)
+ def delete_released_story_indexes(self) -> int:
+ """Delete the story-to-file maps that no remaining run names, among those the deleted runs named.
+
+ A map is stored once per distinct content and no row tracks it, so this is the only thing that
+ removes one. Only the maps of runs this sweep deleted are candidates, so nothing lists storage.
+ """
+ if not self.released_story_index_hashes or self._out_of_time():
+ return 0
+
+ still_named = set(
+ self._runs()
+ .annotate(story_index_hash=KeyTextTransform(story_index.METADATA_KEY, "metadata"))
+ .filter(story_index_hash__in=self.released_story_index_hashes)
+ .values_list("story_index_hash", flat=True)
+ )
+ unnamed = sorted(self.released_story_index_hashes - still_named)
+ if not unnamed:
+ return 0
+
+ failed_paths = StoryIndexStorage(str(self.repo.id)).delete_hashes(unnamed)
+ deleted = len(unnamed) - len(failed_paths)
+ logger.info(
+ "visual_review.retention_story_indexes_deleted",
+ repo_id=str(self.repo.id),
+ team_id=self.team_id,
+ deleted=deleted,
+ failed=len(failed_paths),
+ )
+ return deleted
+
def rotate_for_day(items: list[T], day: date) -> list[T]:
"""Move the start of the list on by one place a day.
@@ -299,9 +341,12 @@ def sweep_repo(repo: Repo, now: datetime | None = None, deadline: float | None =
# Runs go first, because the snapshot rows they take with them are what
# holds most artifacts in use.
runs_deleted = sweep.delete_expired_runs()
+ # Right after the runs, because only this sweep knows which maps the deleted runs named.
+ story_indexes_deleted = sweep.delete_released_story_indexes()
artifacts = sweep.delete_orphaned_artifacts()
return RetentionSweepResult(
runs_deleted=runs_deleted,
artifacts_deleted=artifacts.deleted,
objects_leaked=artifacts.objects_leaked,
+ story_indexes_deleted=story_indexes_deleted,
)
diff --git a/products/visual_review/backend/logic/story_index.py b/products/visual_review/backend/logic/story_index.py
index fd09a2bca2b7..9599abd1cc5d 100644
--- a/products/visual_review/backend/logic/story_index.py
+++ b/products/visual_review/backend/logic/story_index.py
@@ -1,32 +1,33 @@
-"""Which repository file each Storybook snapshot renders, read from the run's build artifact.
+"""The story-to-file map of a repository's Storybook build.
-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.
+The CLI builds the map from the build's `index.json` and uploads it once per distinct content, named
+by its SHA-256. Each run records that hash in `metadata["story_index_hash"]`. Readers take the hash of
+the newest default-branch Storybook run and load the map from object storage through the cache. A
+hash names exactly one map, so a cached map is never stale, and nothing here depends on how long a
+CI system keeps its build artifacts.
"""
from __future__ import annotations
-import io
+import re
import json
-import zipfile
-import posixpath
+import hashlib
from collections.abc import Mapping
+from typing import TypeGuard
+from uuid import UUID
-from django.core.cache import cache
+from django.db import transaction
-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 posthog.storage.object_storage import ObjectStorageError
-from ..models import Repo
-from . import errors, github_api
+from ..db import WRITER_DB
+from ..facade.enums import RunType
+from ..models import Repo, Run
+from ..storage import StoryIndexStorage
+from . import content_cache, run_queries
logger = structlog.get_logger(__name__)
@@ -37,21 +38,16 @@ _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
-# GitHub keeps the Storybook build artifact for one day, and the debt digest that reads this index
-# posts once a week. A daily task warms the cache while the artifact still exists, so an entry has
-# to outlive a full week for the next weekly post to still find it.
-_CACHE_TTL_SECONDS = 60 * 60 * 24 * 8
+METADATA_KEY = "story_index_hash"
+_MAP_VERSION = 1
+_HASH_PATTERN = re.compile(r"^[0-9a-f]{64}$")
+# The owners lookup reads two ownership files in every parent directory of a path, so a path longer
+# or deeper than any real story file is refused rather than handed to it.
+_MAX_PATH_CHARS = 512
+_MAX_PATH_SEGMENTS = 16
+# A caller with write access controls the map, and readers parse and cache all of it. A map with more
+# entries than any real Storybook build has is refused, so it cannot fill the shared cache.
+_MAX_STORIES = 20_000
@frozen
@@ -61,6 +57,14 @@ class StoryIndex:
path_by_story_id: Mapping[str, str]
+@frozen
+class StoryIndexUpload:
+ """Where the CLI posts a map that the store does not hold yet."""
+
+ url: str
+ fields: dict[str, str]
+
+
@frozen
class ThemeSplit:
"""An identifier taken apart around its theme. The theme is empty when the identifier carries none."""
@@ -118,114 +122,102 @@ def story_path(index: StoryIndex, identifier: str) -> str | None:
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.
+def register_story_index(run_id: UUID, team_id: int, story_index_hash: str) -> StoryIndexUpload | None:
+ """Record the map a run's build produced, and ask for the map when the store does not hold it.
- Raises ValueError when the payload is not a story index. `json.JSONDecodeError` is a ValueError,
- so a truncated download lands in the same branch.
+ Every shard of a run sends the same hash, so the first shard records it and the others change
+ nothing. A value that is not a SHA-256 cannot name a stored map, so it is ignored. Only a
+ default-branch run records a map, because readers only use the newest default-branch run.
"""
- 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")
+ if not _HASH_PATTERN.match(story_index_hash):
+ logger.info("visual_review.story_index_hash_invalid", run_id=str(run_id))
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")
+ with transaction.atomic(using=WRITER_DB):
+ run = (
+ Run.objects.using(WRITER_DB)
+ .select_for_update()
+ .only("id", "repo_id", "branch", "metadata")
+ .get(id=run_id, team_id=team_id)
+ )
+ if run.branch not in run_queries._DEFAULT_BRANCHES:
return None
- if archive.getinfo(_INDEX_MEMBER).file_size > _MAX_INDEX_BYTES:
- _log_unavailable(repo, github_run_id, "artifact_too_large")
+ metadata = run.metadata or {}
+ recorded = metadata.get(METADATA_KEY)
+ if recorded is None:
+ run.metadata = {**metadata, METADATA_KEY: story_index_hash}
+ run.save(using=WRITER_DB, update_fields=["metadata"])
+ elif recorded != story_index_hash:
+ # Shards of one run test one build, so two maps mean two builds fed the same run. The
+ # recorded map stays, so there is nothing to upload for this one.
+ logger.warning("visual_review.story_index_hash_conflict", run_id=str(run_id))
return None
- return archive.read(_INDEX_MEMBER)
+ storage = StoryIndexStorage(str(run.repo_id))
+ # The map only attributes snapshots to teams, so a storage failure must not fail the shard's upload.
+ try:
+ if storage.exists(story_index_hash):
+ return None
+ post = storage.get_presigned_upload_url(story_index_hash)
+ except ObjectStorageError:
+ logger.warning("visual_review.story_index_storage_unavailable", run_id=str(run_id), exc_info=True)
+ return None
+ if post is None:
+ return None
+ return StoryIndexUpload(url=post["url"], fields=post["fields"])
-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):
- # The artifact behind an entry is deleted after a day, so an entry that expires can never
- # be filled again. A hit extends it, which is how the warm runs hold a long-lived baseline.
- cache.touch(cache_key, _CACHE_TTL_SECONDS)
- return StoryIndex(path_by_story_id=cached)
+def _is_repository_path(path: object) -> TypeGuard[str]:
+ if not isinstance(path, str) or not path or len(path) > _MAX_PATH_CHARS or path.startswith("/"):
+ return False
+ segments = path.split("/")
+ return len(segments) <= _MAX_PATH_SEGMENTS and ".." not in segments
+
+def _read_paths(repo: Repo, story_index_hash: str) -> dict[str, str] | None:
+ """Story id to repository path, from the stored map. None when the map cannot be trusted."""
+ log = logger.bind(repo_id=str(repo.id), story_index_hash=story_index_hash)
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")
+ raw = StoryIndexStorage(str(repo.id)).read(story_index_hash)
+ except ObjectStorageError:
+ # None is never cached, so a storage outage reads as an unknown owner until the store recovers.
+ log.warning("visual_review.story_index_storage_unavailable", exc_info=True)
return None
- except (GitHubIntegrationError, GitHubRateLimitError, requests.RequestException, zipfile.BadZipFile):
- _log_unavailable(repo, github_run_id, "download_failed")
+ if raw is None:
+ log.info("visual_review.story_index_missing")
return None
- except ValueError:
- _log_unavailable(repo, github_run_id, "index_invalid")
+ # The CLI uploads through a presigned post, so the bytes count only once they hash to their name.
+ if hashlib.sha256(raw).hexdigest() != story_index_hash:
+ log.warning("visual_review.story_index_hash_mismatch")
return None
-
- cache.set(cache_key, paths, timeout=_CACHE_TTL_SECONDS)
+ try:
+ document = json.loads(raw)
+ # A deeply nested document raises RecursionError, which is not a ValueError.
+ except (ValueError, RecursionError):
+ document = None
+ paths = document.get("paths") if isinstance(document, dict) and document.get("version") == _MAP_VERSION else None
+ if not isinstance(paths, dict):
+ log.warning("visual_review.story_index_invalid")
+ return None
+ if len(paths) > _MAX_STORIES:
+ log.warning("visual_review.story_index_too_large", stories=len(paths))
+ return None
+ return {
+ story_id: path for story_id, path in paths.items() if isinstance(story_id, str) and _is_repository_path(path)
+ }
+
+
+def latest_story_index(repo: Repo, newest_run_by_type: Mapping[str, Run]) -> StoryIndex | str:
+ """The story index of the newest default-branch Storybook run, or a short phrase saying why there is none."""
+ run = newest_run_by_type.get(RunType.STORYBOOK)
+ if run is None:
+ return "there is no default branch Storybook run to read"
+ # Read on a query of its own because the shared default-branch universe defers `metadata`.
+ metadata = Run.objects.filter(id=run.id, team_id=repo.team_id).values_list("metadata", flat=True).first()
+ story_index_hash = (metadata or {}).get(METADATA_KEY)
+ if not isinstance(story_index_hash, str) or not _HASH_PATTERN.match(story_index_hash):
+ return "the newest default branch Storybook run recorded no story index"
+ paths = content_cache.load_by_hash("story_index", story_index_hash, lambda: _read_paths(repo, story_index_hash))
+ if paths is None:
+ return f"the story index {story_index_hash[:12]} could not be read"
return StoryIndex(path_by_story_id=paths)
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index c0a9c7de2646..96c2815c17fd 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -197,9 +197,26 @@ class CreateRunInputSerializer(DataclassSerializer):
class AddSnapshotsInputSerializer(DataclassSerializer):
class Meta:
dataclass = AddSnapshotsInput
+ extra_kwargs = {
+ "story_index_hash": {
+ "help_text": (
+ "SHA-256 of the story-to-file map the CLI built from the Storybook index.json of this "
+ "run's build. Every shard of a run sends the same value. Empty when the run sends no map."
+ )
+ },
+ }
class AddSnapshotsResultSerializer(DataclassSerializer):
+ story_index_upload = UploadTargetSerializer(
+ allow_null=True,
+ required=False,
+ help_text=(
+ "Where to upload the story-to-file map, as a presigned POST with a JSON body. Null when the "
+ "request sent no map, or the store already holds a map with that hash."
+ ),
+ )
+
class Meta:
dataclass = AddSnapshotsResult
@@ -519,6 +536,16 @@ class FlakinessEntrySerializer(DataclassSerializer):
required=False,
help_text="Active quarantine details when `is_quarantined` is true. Null otherwise.",
)
+ owner_team = serializers.CharField(
+ allow_null=True,
+ required=False,
+ help_text=(
+ "Slug of the team that owns the file this snapshot's story lives in, from the repository's "
+ "ownership files. `unowned` when no entry covers the file. Null when ownership is unknown: "
+ "the snapshot is not a Storybook snapshot, the newest default-branch run sent no story index, "
+ "the story is not in it, or the ownership files could not be read."
+ ),
+ )
class Meta:
dataclass = FlakinessEntry
diff --git a/products/visual_review/backend/presentation/views.py b/products/visual_review/backend/presentation/views.py
index 837eb7a4afd2..ea73fe0c4f30 100644
--- a/products/visual_review/backend/presentation/views.py
+++ b/products/visual_review/backend/presentation/views.py
@@ -386,7 +386,7 @@ class RepoViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
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)
- result = api.get_flakiness_overview(repo_id)
+ result = api.get_flakiness_overview(repo_id, self.team_id)
return Response(FlakinessOverviewSerializer(instance=result).data)
diff --git a/products/visual_review/backend/storage.py b/products/visual_review/backend/storage.py
index 4403f9940eaa..539efe6e9634 100644
--- a/products/visual_review/backend/storage.py
+++ b/products/visual_review/backend/storage.py
@@ -18,6 +18,7 @@ class ArtifactStorage:
FOLDER = os.getenv("OBJECT_STORAGE_VISUAL_REVIEW_FOLDER", "visual_review")
MAX_SIZE_BYTES = 10 * 1024 * 1024 # 10MB per image
+ CONTENT_TYPE_CONDITION = ["starts-with", "$Content-Type", "image/"]
PRESIGNED_EXPIRATION = 60 * 60 # 1 hour
def __init__(self, repo_id: str):
@@ -37,7 +38,7 @@ class ArtifactStorage:
file_key=self._key(content_hash),
conditions=[
["content-length-range", 0, self.MAX_SIZE_BYTES],
- ["starts-with", "$Content-Type", "image/"],
+ self.CONTENT_TYPE_CONDITION,
],
expiration=self.PRESIGNED_EXPIRATION,
)
@@ -91,3 +92,25 @@ class ArtifactStorage:
return None
return object_storage.read_bytes(self._key(content_hash), missing_ok=True)
+
+
+class StoryIndexStorage(ArtifactStorage):
+ """
+ Object storage for the story-to-file maps the CLI uploads, one object per distinct map.
+
+ The maps sit under their own prefix rather than among the artifact keys, so a sweep of artifact
+ keys can never delete one.
+ """
+
+ MAX_SIZE_BYTES = 8 * 1024 * 1024
+ CONTENT_TYPE_CONDITION = ["eq", "$Content-Type", "application/json"]
+
+ def _prefix(self) -> str:
+ return f"{self.FOLDER}/{self.repo_id}/story-index/"
+
+ def _key(self, content_hash: str) -> str:
+ return f"{self._prefix()}{content_hash}.json"
+
+ def delete_hashes(self, story_index_hashes: list[str]) -> list[str]:
+ """Delete maps by hash. Returns the storage paths that were not deleted."""
+ return self.delete_paths([self._key(story_index_hash) for story_index_hash in story_index_hashes])
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 5e7b0ebf3a5e..41ef4660e87a 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -13,7 +13,6 @@ from datetime import date
from uuid import UUID
from django.core.cache import cache
-from django.utils import timezone
import structlog
from celery import shared_task
@@ -232,8 +231,7 @@ def sweep_visual_review_retention() -> None:
def send_visual_review_debt_digests() -> None:
"""Fan out to every repo, one task each.
- Runs more often than the digest posts, and the child decides which kind of run this is. One
- repo's failure must not stop the rest, and nothing is stored about what was sent, so next
+ One repo's failure must not stop the rest, and nothing is stored about what was sent, so next
Monday's run recomputes and resends whatever is still owed.
"""
from ..logic import debt_digest # noqa: PLC0415 — avoids the logic/tasks circular import
@@ -250,7 +248,7 @@ def send_visual_review_debt_digests() -> None:
)
@with_team_scope()
def send_visual_review_debt_digest(team_id: int, repo_id: str) -> None:
- """Post one repo's digest on the posting day, and only warm its story index on the other days.
+ """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.
@@ -267,7 +265,4 @@ def send_visual_review_debt_digest(team_id: int, repo_id: str) -> None:
logger.warning("visual_review.debt_digest_repo_missing", repo_id=repo_id, team_id=team_id)
return
- if not debt_digest.posts_today(timezone.now()):
- debt_digest.warm_story_index(repo)
- 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.py
index 0686ed7c9194..03c0507c428d 100644
--- a/products/visual_review/backend/tests/logic/test_debt_digest.py
+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py
@@ -38,7 +38,6 @@ _OTHER_PATH = "frontend/src/scenes/Card.stories.tsx"
_OTHER_STORY_ID = "scenes-app-card--primary"
_OTHER_IDENTIFIER = f"{_OTHER_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})
# The renderers take the moment they render for, so a fixed Monday never ages against a real clock.
@@ -48,7 +47,7 @@ _PLACED = debt_digest.Attribution(kind=debt_digest.AttributionKind.PLACED, sourc
_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",
+ detail="the story index 0123456789ab could not be read",
)
@@ -83,8 +82,8 @@ def _maintainers_digest(*groups: debt_digest.TriageGroup) -> debt_digest.Maintai
return debt_digest.MaintainersDigest(team_slug="team-devex", groups=list(groups))
-def _with_index(index: story_index.StoryIndex | None):
- return patch("products.visual_review.backend.logic.story_index.fetch_story_index", return_value=index)
+def _with_index(index: story_index.StoryIndex | str):
+ return patch("products.visual_review.backend.logic.story_index.latest_story_index", return_value=index)
def _section_texts(message: debt_digest.SlackMessage) -> list[str]:
@@ -125,7 +124,11 @@ class TestLead:
message = debt_digest.lead_message(_repo(), _team_digest(pileups=1), _MONDAY)
assert [(button["text"]["text"], button["url"]) for button in _buttons(message)] == [
- ("Open flakiness overview", f"{settings.SITE_URL}/project/7/visual_review/repos/abc/flakiness"),
+ # The page opens on the team's own rows, so a shared repo does not bury them.
+ (
+ "Open flakiness overview",
+ f"{settings.SITE_URL}/project/7/visual_review/repos/abc/flakiness#teams=team-devex",
+ ),
("Open snapshots", f"{settings.SITE_URL}/project/7/visual_review/repos/abc/snapshots"),
]
@@ -494,7 +497,6 @@ class TestCollectAndSend:
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
],
@@ -546,11 +548,11 @@ class TestCollectAndSend:
]
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):
+ def test_an_unreadable_story_index_leaves_the_items_unattributed(self, repo, mocker):
self._completed_run(repo, mocker)
self._pile_up(repo)
- with _with_index(None):
+ with _with_index(_UNAVAILABLE.detail):
debt = debt_digest.collect_debt(repo, timezone.now())
assert [item.attribution for item in debt.variant_pileups] == [_UNAVAILABLE]
diff --git a/products/visual_review/backend/tests/logic/test_owners.py b/products/visual_review/backend/tests/logic/test_owners.py
new file mode 100644
index 000000000000..a0d1fcdcd95b
--- /dev/null
+++ b/products/visual_review/backend/tests/logic/test_owners.py
@@ -0,0 +1,47 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
+from products.visual_review.backend.logic import owners, story_index
+from products.visual_review.backend.logic.run_queries import SnapshotKey
+
+_BUTTON = SnapshotKey(run_type="storybook", identifier="scenes-app-button--primary--light")
+_CARD = SnapshotKey(run_type="storybook", identifier="scenes-app-card--primary--dark")
+_GONE = SnapshotKey(run_type="storybook", identifier="scenes-app-gone--primary--light")
+_PLAYWRIGHT = SnapshotKey(run_type="playwright", identifier="scenes-app-button--primary--light")
+
+_INDEX = story_index.StoryIndex(
+ path_by_story_id={
+ "scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx",
+ "scenes-app-card--primary": "frontend/src/scenes/Card.stories.tsx",
+ }
+)
+
+
+class TestOwnerTeams:
+ @pytest.mark.parametrize(
+ "resolved,max_paths,expected",
+ [
+ # A file no entry covers is unowned. A story the index lacks, or a run type with no
+ # index, has no file at all, which is not the same answer.
+ (True, 2, {_BUTTON: "team-replay", _CARD: UNOWNED_TEAM}),
+ # Unreadable ownership files would otherwise read every file as unowned.
+ (False, 2, {}),
+ # More story files than the cap are never sent to the ownership lookup.
+ (True, 1, {}),
+ ],
+ )
+ def test_names_a_team_only_for_a_story_file_it_can_place(
+ self, resolved: bool, max_paths: int, expected: dict
+ ) -> None:
+ ownership = PathOwnership(
+ team_by_path={"frontend/src/scenes/Button.stories.tsx": "team-replay"}, registry={}, resolved=resolved
+ )
+ with (
+ patch("products.visual_review.backend.logic.story_index.latest_story_index", return_value=_INDEX),
+ patch("products.visual_review.backend.logic.owners.resolve_path_owners", return_value=ownership),
+ patch.object(owners, "_MAX_OWNED_PATHS", max_paths),
+ ):
+ result = owners.owner_teams(MagicMock(repo_full_name="org/repo"), [_BUTTON, _CARD, _GONE, _PLAYWRIGHT], {})
+
+ assert result == expected
diff --git a/products/visual_review/backend/tests/logic/test_retention.py b/products/visual_review/backend/tests/logic/test_retention.py
index 00daf80d6bf0..8dec1640ef32 100644
--- a/products/visual_review/backend/tests/logic/test_retention.py
+++ b/products/visual_review/backend/tests/logic/test_retention.py
@@ -7,7 +7,7 @@ import pytest
from django.utils import timezone
from products.visual_review.backend.facade.enums import RunStatus, RunType, ToleratedReason
-from products.visual_review.backend.logic import artifact_store, repos, retention
+from products.visual_review.backend.logic import artifact_store, repos, retention, story_index
from products.visual_review.backend.models import Artifact, QuarantinedIdentifier, Run, RunSnapshot, ToleratedHash
from products.visual_review.backend.tasks.tasks import sweep_visual_review_retention
from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
@@ -287,6 +287,23 @@ class TestRetentionSweep:
assert result.artifacts_deleted == 1
assert Artifact.objects.filter(repo_id=repo.id).count() == 1
+ def test_a_story_index_goes_with_the_last_run_that_names_it(self, repo, now, stub_object_delete):
+ released, shared = "a" * 64, "b" * 64
+ latest = self._run(repo, now, age_days=1)
+ for story_index_hash, run in (
+ (shared, latest),
+ (released, self._run(repo, now, age_days=400, superseded_by=latest)),
+ (shared, self._run(repo, now, age_days=400, superseded_by=latest)),
+ ):
+ run.metadata = {story_index.METADATA_KEY: story_index_hash}
+ run.save(update_fields=["metadata"])
+
+ result = retention.sweep_repo(repo, now=now)
+
+ # The shared map is still named by the run that stays, so only the released one goes.
+ assert result.story_indexes_deleted == 1
+ stub_object_delete.assert_called_once_with([f"visual_review/{repo.id}/story-index/{released}.json"])
+
def test_sweeping_one_repo_leaves_another_repo_alone(self, repo, other_repo, now):
kept_latest = self._run(other_repo, now, age_days=200)
kept_superseded = self._run(other_repo, now, age_days=300, superseded_by=kept_latest)
diff --git a/products/visual_review/backend/tests/logic/test_story_index.py b/products/visual_review/backend/tests/logic/test_story_index.py
index 7f4e9a6ce932..8d37c1c6d8de 100644
--- a/products/visual_review/backend/tests/logic/test_story_index.py
+++ b/products/visual_review/backend/tests/logic/test_story_index.py
@@ -1,20 +1,20 @@
-"""Unit tests for logic/story_index.py — the snapshot-to-file map from the Storybook artifact."""
+"""Unit tests for logic/story_index.py — the story-to-file map the CLI uploads with a run."""
-import io
import json
-import zipfile
-from datetime import UTC, datetime, timedelta
-from uuid import uuid4
+import hashlib
import pytest
-import time_machine
-from unittest.mock import MagicMock, patch
+from unittest.mock import patch
-import requests
+from django.core.cache import cache
-from products.visual_review.backend.logic import errors, story_index
+from posthog.storage.object_storage import ObjectStorageError
-_ARTIFACT_NAME = story_index.STORYBOOK_ARTIFACT_NAME
+from products.visual_review.backend.facade.contracts import CreateRunInput
+from products.visual_review.backend.facade.enums import RunType
+from products.visual_review.backend.logic import repos, runs, story_index
+from products.visual_review.backend.models import Run
+from products.visual_review.backend.tests.conftest import PRODUCT_DATABASES
_INDEX = story_index.StoryIndex(
path_by_story_id={
@@ -26,28 +26,24 @@ _INDEX = story_index.StoryIndex(
)
-def _repo() -> MagicMock:
- return MagicMock(id=uuid4())
+def _map_bytes(paths: dict[str, str]) -> bytes:
+ return json.dumps({"version": 1, "paths": paths}).encode()
-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()
+_MAP = _map_bytes({"scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx"})
+_MAP_HASH = hashlib.sha256(_MAP).hexdigest()
+_OTHER_HASH = hashlib.sha256(b"another build").hexdigest()
+_DEEP_MAP = _map_bytes(
+ {
+ "scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx",
+ "scenes-app-deep--primary": "/".join(["nested"] * 200) + "/Deep.stories.tsx",
+ }
+)
+_DEEP_HASH = hashlib.sha256(_DEEP_MAP).hexdigest()
+_HUGE_MAP = _map_bytes(
+ {f"scenes-app-story-{i}--primary": "frontend/src/scenes/Story.stories.tsx" for i in range(20_001)}
+)
+_HUGE_HASH = hashlib.sha256(_HUGE_MAP).hexdigest()
class TestStoryPath:
@@ -70,140 +66,119 @@ class TestStoryPath:
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"}
-
- def test_a_read_keeps_the_index_of_a_baseline_that_does_not_move(self) -> None:
- repo = _repo()
- zip_bytes = _zip_bytes(
- {"index.json": _index_document({"a--b": {"type": "story", "importPath": "../../frontend/src/A.tsx"}})}
[email protected]_db(databases=PRODUCT_DATABASES)
+class TestUploadedStoryIndex:
+ @pytest.fixture(autouse=True)
+ def _clear_cache(self):
+ cache.clear()
+
+ @pytest.fixture
+ def repo(self, team):
+ return repos.create_repo(team_id=team.id, repo_external_id=4242, repo_full_name="org/story-index")
+
+ def _run(self, repo, metadata: dict | None = None, branch: str = "master") -> Run:
+ run, _uploads = runs.create_run(
+ CreateRunInput(
+ repo_id=repo.id,
+ run_type=RunType.STORYBOOK,
+ commit_sha="abc",
+ branch=branch,
+ snapshots=[],
+ metadata=metadata or {},
+ ),
+ team_id=repo.team_id,
)
- start = datetime(2026, 9, 14, 7, 30, tzinfo=UTC)
- # A second pair of responses, so an expired entry reads as another GitHub call rather than
- # an exhausted mock. One read is two calls: the artifact listing and the download.
- responses = [_listing({"name": _ARTIFACT_NAME, "id": 42}), _response(content=zip_bytes)] * 2
+ return run
+
+ @pytest.mark.parametrize(
+ "stored,asks_for_upload",
+ [(False, True), (True, False)],
+ )
+ def test_the_first_shard_records_the_hash_and_the_map_is_asked_for_only_when_missing(
+ self, repo, stored: bool, asks_for_upload: bool
+ ) -> None:
+ run = self._run(repo)
with (
- patch(
- "products.visual_review.backend.logic.github_api._github_api_request",
- side_effect=responses,
- ) as request,
- time_machine.travel(start, tick=False) as traveller,
+ patch.object(story_index.StoryIndexStorage, "exists", return_value=stored),
+ patch.object(
+ story_index.StoryIndexStorage,
+ "get_presigned_upload_url",
+ return_value={"url": "https://storage.example.com", "fields": {"key": "k"}},
+ ),
):
- assert story_index.fetch_story_index(repo, "98765") is not None
- traveller.move_to(start + timedelta(days=7))
- assert story_index.fetch_story_index(repo, "98765") is not None
- traveller.move_to(start + timedelta(days=14))
- index = story_index.fetch_story_index(repo, "98765")
+ first = story_index.register_story_index(run.id, repo.team_id, _MAP_HASH)
+ # A later shard reporting a different build must not replace what the first one recorded,
+ # or get an upload target for a map no reader will use.
+ conflicting = story_index.register_story_index(run.id, repo.team_id, _OTHER_HASH)
- assert index is not None
- assert request.call_count == 2
+ run.refresh_from_db()
+ assert run.metadata[story_index.METADATA_KEY] == _MAP_HASH
+ assert (first is not None) is asks_for_upload
+ assert conflicting is None
@pytest.mark.parametrize(
- "responses",
+ "branch,story_index_hash",
[
- 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",
- ),
+ ("master", "../../other-repo/map"),
+ # Readers only use the newest default-branch run, so a map from any other branch is never read.
+ ("feature/x", _MAP_HASH),
],
)
- 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
+ def test_a_map_nothing_would_read_is_not_recorded(self, repo, branch: str, story_index_hash: str) -> None:
+ run = self._run(repo, branch=branch)
- @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
+ with patch.object(story_index.StoryIndexStorage, "exists") as exists:
+ assert story_index.register_story_index(run.id, repo.team_id, story_index_hash) is None
+
+ run.refresh_from_db()
+ assert story_index.METADATA_KEY not in run.metadata
+ assert exists.call_count == 0
@pytest.mark.parametrize(
- "error",
+ "metadata,stored,expected",
[
- errors.GitHubIntegrationNotFoundError("no integration"),
- requests.ConnectionError("boom"),
+ (
+ {story_index.METADATA_KEY: _MAP_HASH},
+ _MAP,
+ story_index.StoryIndex(
+ path_by_story_id={"scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx"}
+ ),
+ ),
+ # Bytes that do not hash to their name were not what the CLI built, so they are not trusted.
+ (
+ {story_index.METADATA_KEY: _MAP_HASH},
+ _map_bytes({"scenes-app-button--primary": "frontend/src/Elsewhere.stories.tsx"}),
+ f"the story index {_MAP_HASH[:12]} could not be read",
+ ),
+ ({}, _MAP, "the newest default branch Storybook run recorded no story index"),
+ # The owners lookup walks every parent directory, so a path deeper than any real file is dropped.
+ (
+ {story_index.METADATA_KEY: _DEEP_HASH},
+ _DEEP_MAP,
+ story_index.StoryIndex(
+ path_by_story_id={"scenes-app-button--primary": "frontend/src/scenes/Button.stories.tsx"}
+ ),
+ ),
+ # A map with more entries than any real build is refused before it reaches the cache.
+ (
+ {story_index.METADATA_KEY: _HUGE_HASH},
+ _HUGE_MAP,
+ f"the story index {_HUGE_HASH[:12]} could not be read",
+ ),
+ # A storage outage reads as an unknown owner rather than failing the page or the digest.
+ (
+ {story_index.METADATA_KEY: _MAP_HASH},
+ ObjectStorageError("read failed"),
+ f"the story index {_MAP_HASH[:12]} could not be read",
+ ),
],
)
- 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 None
+ def test_reads_the_map_the_newest_run_recorded(
+ self, repo, metadata: dict, stored: bytes | Exception, expected
+ ) -> None:
+ run = self._run(repo, metadata)
+
+ with patch.object(story_index.StoryIndexStorage, "read", side_effect=[stored]):
+ result = story_index.latest_story_index(repo, {RunType.STORYBOOK: run})
+
+ assert result == expected
diff --git a/products/visual_review/backend/tests/test_flakiness.py b/products/visual_review/backend/tests/test_flakiness.py
index 2123cb8ad315..1d324a2291ad 100644
--- a/products/visual_review/backend/tests/test_flakiness.py
+++ b/products/visual_review/backend/tests/test_flakiness.py
@@ -205,7 +205,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
)
def _entry(self, identifier: str):
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
return next((e for e in result.entries if e.identifier == identifier), None)
def test_a_quarantine_over_a_snapshot_still_failing_does_not_ask_to_be_lifted(self):
@@ -481,7 +481,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
_mk_snapshot(self.master_run, identifier="shared")
self._render("shared", outcome=HARD, count=3)
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
by_type = {e.run_type: e for e in result.entries if e.identifier == "shared"}
assert by_type[RunType.STORYBOOK].hard_count == 3
@@ -497,7 +497,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
entry = next(
e
- for e in vr_api.get_flakiness_overview(self.repo.id).entries
+ for e in vr_api.get_flakiness_overview(self.repo.id, self.team.id).entries
if e.identifier == "shared" and e.run_type == RunType.PLAYWRIGHT
)
@@ -557,7 +557,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
self._mk_variant(identifier="flaky", alternate_hash="a")
with CaptureQueriesContext(connections[WRITER_DB]) as captured:
- vr_api.get_flakiness_overview(self.repo.id)
+ vr_api.get_flakiness_overview(self.repo.id, self.team.id)
soft_queries = [q["sql"] for q in captured.captured_queries if ClassificationReason.TOLERATED_HASH in q["sql"]]
assert soft_queries
@@ -571,7 +571,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
_mk_snapshot(self.master_run, identifier="brand-new", baseline_hash="")
self._mk_quarantine("brand-new")
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
assert [e.identifier for e in result.entries] == ["brand-new"]
assert result.totals.quarantined == 1
@@ -582,7 +582,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
Run.objects.filter(repo=self.repo).update(status=RunStatus.PENDING)
self._mk_quarantine("muted-early")
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
assert [e.identifier for e in result.entries] == ["muted-early"]
assert result.totals.tracked == 0
@@ -635,7 +635,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
variant = self._mk_variant(identifier="noisy", alternate_hash="a")
self._render("noisy", outcome=SOFT_MATCH, count=5, diff_percentage=0.01, tolerated_hash_match=variant)
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
assert [e.identifier for e in result.entries] == ["muted", "noisy"]
@@ -644,7 +644,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
_mk_snapshot(self.master_run, identifier="flaky")
self._mk_variant(identifier="flaky", alternate_hash="a")
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
assert [e.identifier for e in result.entries] == ["flaky"]
assert result.totals.listed == 1
@@ -654,7 +654,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
_mk_snapshot(self.master_run, identifier="compared")
_mk_snapshot(self.master_run, identifier="brand-new", baseline_hash="")
- result = vr_api.get_flakiness_overview(self.repo.id)
+ result = vr_api.get_flakiness_overview(self.repo.id, self.team.id)
assert result.totals.tracked == 1
@@ -702,7 +702,7 @@ class TestFlakinessOverview(VisualReviewTeamScopedTestMixin, APIBaseTest):
_mk_snapshot(self.master_run, identifier="stable")
self._mk_quarantine("wrecked")
- totals = vr_api.get_flakiness_overview(self.repo.id).totals
+ totals = vr_api.get_flakiness_overview(self.repo.id, self.team.id).totals
assert totals.tracked == 3
assert totals.listed == 2
diff --git a/products/visual_review/backend/tests/test_presentation.py b/products/visual_review/backend/tests/test_presentation.py
index a33aa4095566..871b28d3f96e 100644
--- a/products/visual_review/backend/tests/test_presentation.py
+++ b/products/visual_review/backend/tests/test_presentation.py
@@ -146,6 +146,39 @@ class TestRunViewSet(VisualReviewTeamScopedTestMixin, APIBaseTest):
upload_hashes = {u["content_hash"] for u in data["uploads"]}
self.assertEqual(upload_hashes, {"hash1", "hash2"})
+ @patch("products.visual_review.backend.storage.StoryIndexStorage.get_presigned_upload_url")
+ @patch("products.visual_review.backend.storage.StoryIndexStorage.exists", return_value=False)
+ @patch("products.visual_review.backend.storage.ArtifactStorage.get_presigned_upload_url")
+ def test_add_snapshots_records_the_story_index_and_asks_for_the_map(
+ self, mock_artifact_presigned, _mock_exists, mock_index_presigned
+ ):
+ mock_artifact_presigned.return_value = {"url": "https://s3.example.com/upload", "fields": {"key": "png"}}
+ mock_index_presigned.return_value = {"url": "https://s3.example.com/upload", "fields": {"key": "map"}}
+ create_result = api.create_run(
+ CreateRunInput(
+ repo_id=self.vr_project.id, run_type=RunType.STORYBOOK, commit_sha="abc", branch="main", snapshots=[]
+ ),
+ team_id=self.team.id,
+ )
+ story_index_hash = "a" * 64
+
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/visual_review/runs/{create_result.run_id}/add-snapshots/",
+ {
+ "snapshots": [{"identifier": "Button-primary", "content_hash": "hash1", "width": 100, "height": 200}],
+ "story_index_hash": story_index_hash,
+ },
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ response.json()["story_index_upload"],
+ {"content_hash": story_index_hash, "url": "https://s3.example.com/upload", "fields": {"key": "map"}},
+ )
+ run = Run.objects.get(id=create_result.run_id)
+ self.assertEqual(run.metadata["story_index_hash"], story_index_hash)
+
def test_retrieve_run(self):
create_result = api.create_run(
CreateRunInput(
diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.py
index 94f32f73f33b..5d04cce9e030 100644
--- a/products/visual_review/backend/tests/test_tasks.py
+++ b/products/visual_review/backend/tests/test_tasks.py
@@ -2,10 +2,8 @@
import io
from contextlib import contextmanager
-from datetime import UTC, datetime
import pytest
-import time_machine
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -586,29 +584,14 @@ class TestDebtDigestTask(VisualReviewTeamScopedTestMixin, BaseTest):
assert ((repo.team_id, str(repo.id)), tasks._DEBT_DIGEST_EXPIRY_SECONDS) in enqueued
assert str(switched_off.id) not in {args[1] for args, _ in enqueued}
- @parameterized.expand(
- [
- ("monday_morning", datetime(2026, 9, 14, 7, 30, tzinfo=UTC), True),
- # The evening run of a posting day only warms, or a team gets the same digest twice.
- ("monday_evening", datetime(2026, 9, 14, 19, 30, tzinfo=UTC), False),
- ("friday_morning", datetime(2026, 9, 18, 7, 30, tzinfo=UTC), False),
- ]
- )
- def test_only_the_monday_morning_run_posts_and_the_others_warm_the_index(
- self, _name: str, moment: datetime, posts: bool
- ) -> None:
+ def test_the_child_posts_the_live_digest(self) -> None:
repo = Repo.objects.create(team_id=self.team.id, repo_external_id=55512, repo_full_name="org/scheduled")
try:
- with (
- time_machine.travel(moment, tick=False),
- patch("products.visual_review.backend.logic.debt_digest.send_debt_digest") as send,
- patch("products.visual_review.backend.logic.debt_digest.warm_story_index") as warm,
- ):
+ 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_count == 1) is posts
- assert (warm.call_count == 1) is not posts
- if posts:
- assert send.call_args.kwargs["mode"] == debt_digest.MODE_LIVE
+ # Preview mode posts nothing, so a scheduled run in any other mode is a digest nobody gets.
+ assert send.call_count == 1
+ assert send.call_args.kwargs["mode"] == debt_digest.MODE_LIVE
diff --git a/products/visual_review/cli/src/client.ts b/products/visual_review/cli/src/client.ts
index a9e7f9ea1333..f2655e5eb1f8 100644
--- a/products/visual_review/cli/src/client.ts
+++ b/products/visual_review/cli/src/client.ts
@@ -5,6 +5,8 @@
* Uses generated types from the frontend package.
*/
import type {
+ AddSnapshotsInputApi,
+ AddSnapshotsResultApi,
ApproveSnapshotInputApi,
ArtifactApi,
CreateRunInputApi,
@@ -143,7 +145,7 @@ export class VisualReviewClient {
/**
* Upload artifact to S3 using presigned URL from createRun response.
*/
- async uploadToS3(uploadTarget: UploadTargetApi, data: Buffer): Promise<void> {
+ async uploadToS3(uploadTarget: UploadTargetApi, data: Buffer, contentType = 'image/png'): Promise<void> {
const formData = new FormData()
// Add all presigned fields
@@ -152,10 +154,10 @@ export class VisualReviewClient {
}
// Content-Type must be in form data (required by presigned POST policy)
- formData.append('Content-Type', 'image/png')
+ formData.append('Content-Type', contentType)
// Add file data (must be last field in form data for S3)
- formData.append('file', new Blob([new Uint8Array(data)], { type: 'image/png' }))
+ formData.append('file', new Blob([new Uint8Array(data)], { type: contentType }))
const response = await fetch(uploadTarget.url, {
method: 'POST',
@@ -174,13 +176,16 @@ export class VisualReviewClient {
runId: string,
input: {
snapshots: SnapshotManifestItemApi[]
+ storyIndexHash?: string
}
- ): Promise<{ added: number; uploads: UploadTargetApi[] }> {
- return this.request(`/visual_review/runs/${runId}/add-snapshots/`, {
+ ): Promise<AddSnapshotsResultApi> {
+ const body: AddSnapshotsInputApi = {
+ snapshots: input.snapshots,
+ story_index_hash: input.storyIndexHash,
+ }
+ return this.request<AddSnapshotsResultApi>(`/visual_review/runs/${runId}/add-snapshots/`, {
method: 'POST',
- body: JSON.stringify({
- snapshots: input.snapshots,
- }),
+ body: JSON.stringify(body),
})
}
diff --git a/products/visual_review/cli/src/index.ts b/products/visual_review/cli/src/index.ts
index db3dd253d5f4..a91ded7fbabb 100644
--- a/products/visual_review/cli/src/index.ts
+++ b/products/visual_review/cli/src/index.ts
@@ -17,6 +17,7 @@ import { hashImageWithDimensions } from './hasher.js'
import { log, reportRunOutcome } from './outcome.js'
import { scanDirectory } from './scanner.js'
import { readBaselineHashes, readSnapshotsFile } from './snapshots.js'
+import { buildStoryIndex, type StoryIndexMap } from './storyIndex.js'
program.name('vr').description('Visual Review CLI for snapshot testing').version('0.0.1')
@@ -113,7 +114,19 @@ run.command('upload')
.option('--team <id>', 'Team ID (overrides snapshots.yml config)')
.option('--token <value>', 'Personal API token')
.option('--cookie <value>', 'Session cookie')
+ .option(
+ '--storybook-index <path>',
+ "Storybook index.json of the build these snapshots came from. Sends the story-to-file map Visual Review uses to find each snapshot's owning team."
+ )
+ .option(
+ '--storybook-root <dir>',
+ 'Directory Storybook ran in, relative to the repository root. Required with --storybook-index.'
+ )
.action(async (options: RunUploadOptions) => {
+ if (options.storybookIndex && !options.storybookRoot) {
+ console.error('Error: --storybook-root is required with --storybook-index')
+ process.exit(2)
+ }
if (!baselineExists(options.baseline)) {
process.exit(0)
}
@@ -200,6 +213,8 @@ interface RunUploadOptions {
team?: string
token?: string
cookie?: string
+ storybookIndex?: string
+ storybookRoot?: string
}
interface RunCompleteOptions {
@@ -332,6 +347,26 @@ async function runCreate(options: RunCreateOptions): Promise<string> {
return result.run_id
}
+// The map only attributes snapshots to teams, so a map that cannot be read or sent must not fail the
+// upload of the snapshots themselves.
+function readStoryIndex(
+ indexPath: string | undefined,
+ storybookRoot: string | undefined,
+ runId: string
+): StoryIndexMap | undefined {
+ if (!indexPath || !storybookRoot) {
+ return undefined
+ }
+ try {
+ const map = buildStoryIndex(readFileSync(indexPath, 'utf-8'), storybookRoot)
+ log(`[run:${runId}] Story index: ${map.storyCount} stories, ${map.hash.slice(0, 12)}`)
+ return map
+ } catch (error) {
+ log(`[run:${runId}] Could not read the Storybook index, sending snapshots without it: ${error}`)
+ return undefined
+ }
+}
+
async function runUpload(options: RunUploadOptions): Promise<void> {
const { client } = makeClient(options)
const runId = options.runId
@@ -362,6 +397,7 @@ async function runUpload(options: RunUploadOptions): Promise<void> {
log(`[run:${runId}] Sending ${snapshots.length} snapshots to backend`)
+ const storyIndex = readStoryIndex(options.storybookIndex, options.storybookRoot, runId)
const addResult = await client.addSnapshots(runId, {
snapshots: snapshots.map((s) => ({
identifier: s.identifier,
@@ -369,8 +405,18 @@ async function runUpload(options: RunUploadOptions): Promise<void> {
width: s.width,
height: s.height,
})),
+ storyIndexHash: storyIndex?.hash,
})
+ if (storyIndex && addResult.story_index_upload) {
+ try {
+ await client.uploadToS3(addResult.story_index_upload, storyIndex.content, 'application/json')
+ log(`[run:${runId}] Uploaded story index ${storyIndex.hash.slice(0, 12)}`)
+ } catch (error) {
+ log(`[run:${runId}] Story index upload failed: ${error}`)
+ }
+ }
+
log(`[run:${runId}] Registered ${addResult.added} snapshot(s), ${addResult.uploads.length} upload(s) needed`)
if (addResult.uploads.length > 0) {
diff --git a/products/visual_review/cli/src/storyIndex.test.ts b/products/visual_review/cli/src/storyIndex.test.ts
new file mode 100644
index 000000000000..2bd08dc55975
--- /dev/null
+++ b/products/visual_review/cli/src/storyIndex.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest'
+
+import { buildStoryIndex } from './storyIndex.js'
+
+function indexJson(entries: Record<string, { type: string; importPath: string }>): string {
+ return JSON.stringify({ v: 5, entries })
+}
+
+describe('buildStoryIndex', () => {
+ it('resolves each story against the Storybook directory and leaves out what no team can own', () => {
+ const map = buildStoryIndex(
+ indexJson({
+ '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' },
+ 'outside--story': { type: 'story', importPath: '../../../elsewhere/Outside.stories.tsx' },
+ 'absolute--story': { type: 'story', importPath: '/tmp/Absolute.stories.tsx' },
+ }),
+ 'common/storybook'
+ )
+
+ expect(JSON.parse(map.content.toString())).toEqual({
+ version: 1,
+ paths: { 'scenes-app-button--primary': 'frontend/src/scenes/Button.stories.tsx' },
+ })
+ expect(map.storyCount).toBe(1)
+ })
+
+ it('hashes the same build to the same value whatever order the index lists it in', () => {
+ const button = { type: 'story', importPath: './src/Button.stories.tsx' }
+ const card = { type: 'story', importPath: './src/Card.stories.tsx' }
+
+ const first = buildStoryIndex(indexJson({ 'button--primary': button, 'card--primary': card }), '.')
+ const second = buildStoryIndex(indexJson({ 'card--primary': card, 'button--primary': button }), '.')
+
+ expect(second.hash).toBe(first.hash)
+ expect(first.hash).toMatch(/^[0-9a-f]{64}$/)
+ })
+})
diff --git a/products/visual_review/cli/src/storyIndex.ts b/products/visual_review/cli/src/storyIndex.ts
new file mode 100644
index 000000000000..e6d3bbcc5ba0
--- /dev/null
+++ b/products/visual_review/cli/src/storyIndex.ts
@@ -0,0 +1,55 @@
+/**
+ * The story-to-file map of a Storybook build.
+ *
+ * Visual Review reads it to find the file each snapshot's story lives in, and from that the team
+ * that owns the snapshot. The map is uploaded once per distinct content, so it has to serialize to
+ * the same bytes every time the same build is read.
+ */
+import { createHash } from 'node:crypto'
+import { posix } from 'node:path'
+
+export interface StoryIndexMap {
+ content: Buffer
+ hash: string
+ storyCount: number
+}
+
+type StorybookIndex = { entries?: Record<string, { type?: string; importPath?: string }> }
+
+/**
+ * Build the map from a Storybook `index.json`.
+ *
+ * Storybook writes each `importPath` relative to the directory it ran in, so paths resolve against
+ * `storybookRoot`, given relative to the repository root. A story imported from outside the
+ * checkout has no repository path, so no team can own it, and it is left out.
+ */
+export function buildStoryIndex(indexJson: string, storybookRoot: string): StoryIndexMap {
+ const document = JSON.parse(indexJson) as StorybookIndex
+ const entries = document.entries ?? {}
+ const root = posix.normalize(storybookRoot.replaceAll('\\', '/'))
+
+ const paths: Record<string, string> = {}
+ // Sorted, so the same build always serializes to the same bytes and so to the same hash.
+ for (const storyId of Object.keys(entries).sort()) {
+ const entry = entries[storyId]
+ // Docs pages carry an importPath too, and no snapshot is taken of one.
+ if (entry?.type !== 'story' || typeof entry.importPath !== 'string' || !entry.importPath) {
+ continue
+ }
+ if (posix.isAbsolute(entry.importPath)) {
+ continue
+ }
+ const path = posix.normalize(posix.join(root, entry.importPath))
+ if (path === '..' || path.startsWith('../')) {
+ continue
+ }
+ paths[storyId] = path
+ }
+
+ const content = Buffer.from(JSON.stringify({ version: 1, paths }))
+ return {
+ content,
+ hash: createHash('sha256').update(content).digest('hex'),
+ storyCount: Object.keys(paths).length,
+ }
+}
diff --git a/products/visual_review/frontend/components/SnapshotFacetSidebar.tsx b/products/visual_review/frontend/components/SnapshotFacetSidebar.tsx
index 64e61a7dcb2c..7f933fe16b30 100644
--- a/products/visual_review/frontend/components/SnapshotFacetSidebar.tsx
+++ b/products/visual_review/frontend/components/SnapshotFacetSidebar.tsx
@@ -1,6 +1,6 @@
-// Faceted sidebar for the snapshots overview. Three groups (TYPE / AREA /
-// STABILITY), each a flat column of `<button>` rows. Counts are pre-computed
-// by the scene logic so this stays purely presentational.
+// Faceted sidebar for the snapshots and flakiness pages. Each group is a flat
+// column of `<button>` rows, and a group with no buckets is not shown. Counts
+// are pre-computed by the scene logic so this stays purely presentational.
export type FacetBucket = { value: string; label: string; count: number }
@@ -8,19 +8,23 @@ export type FacetGroups = {
type: FacetBucket[]
area: FacetBucket[]
stability: FacetBucket[]
+ team: FacetBucket[]
}
export type FacetSelection = {
type: Set<string>
area: Set<string>
stability: Set<string>
+ team: Set<string>
}
// Stability first — it's the most actionable facet for the page's primary use
-// case ("which snapshots am I tolerating drift on?"). Type and Area are
-// context refinements after that.
+// case ("which snapshots am I tolerating drift on?"). Team comes next because a
+// team's digest links straight to its own rows. Type and Area are context
+// refinements after that.
const GROUP_LABELS: Array<{ key: keyof FacetGroups; label: string }> = [
{ key: 'stability', label: 'Stability' },
+ { key: 'team', label: 'Team' },
{ key: 'type', label: 'Type' },
{ key: 'area', label: 'Area' },
]
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index 11dc5d94f5b5..61a500f4b03c 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -200,6 +200,11 @@ export interface FlakinessEntryApi {
needs_decision: boolean
/** Active quarantine details when `is_quarantined` is true. Null otherwise. */
quarantine?: BaselineQuarantineSummaryApi | null
+ /**
+ * Slug of the team that owns the file this snapshot's story lives in, from the repository's ownership files. `unowned` when no entry covers the file. Null when ownership is unknown: the snapshot is not a Storybook snapshot, the newest default-branch run sent no story index, the story is not in it, or the ownership files could not be read.
+ * @nullable
+ */
+ owner_team?: string | null
identifier: string
run_type: string
/** @nullable */
@@ -489,9 +494,13 @@ export type AddSnapshotsInputApiBaselineHashes = { [key: string]: string }
export interface AddSnapshotsInputApi {
snapshots: SnapshotManifestItemApi[]
baseline_hashes?: AddSnapshotsInputApiBaselineHashes
+ /** SHA-256 of the story-to-file map the CLI built from the Storybook index.json of this run's build. Every shard of a run sends the same value. Empty when the run sends no map. */
+ story_index_hash?: string
}
export interface AddSnapshotsResultApi {
+ /** Where to upload the story-to-file map, as a presigned POST with a JSON body. Null when the request sent no map, or the store already holds a map with that hash. */
+ story_index_upload?: UploadTargetApi | null
added: number
uploads: UploadTargetApi[]
}
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index 70383d4385ac..9df774c5a395 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -111,6 +111,12 @@ export const VisualReviewRunsAddSnapshotsCreateBody = /* @__PURE__ */ zod.object
})
),
baseline_hashes: zod.record(zod.string(), zod.string()).optional(),
+ story_index_hash: zod
+ .string()
+ .optional()
+ .describe(
+ "SHA-256 of the story-to-file map the CLI built from the Storybook index.json of this run's build. Every shard of a run sends the same value. Empty when the run sends no map."
+ ),
})
/**
diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx
index fdffae5ed3a9..2dd6be3bfe3e 100644
--- a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.stories.tsx
@@ -58,6 +58,7 @@ const entry = (overrides: Partial<FlakinessEntryApi>): FlakinessEntryApi => ({
is_quarantined: false,
needs_decision: false,
quarantine: null,
+ owner_team: 'team-replay',
...overrides,
})
@@ -96,6 +97,7 @@ const overview: FlakinessOverviewApi = {
// Absorbed on every run, but its worst diff is a rounding error
// away from the threshold, so it is one restyle from turning red.
identifier: 'charts-heatmap--linear-color-scale--light',
+ owner_team: 'team-web-analytics',
variant_count: 2,
hard_count: 0,
soft_count: 705,
diff --git a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx
index 8beea1a96f14..48dd6e8fb804 100644
--- a/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx
+++ b/products/visual_review/frontend/scenes/VisualReviewFlakinessScene.tsx
@@ -71,6 +71,7 @@ export function VisualReviewFlakinessScene(): JSX.Element {
setPreset,
toggleType,
toggleArea,
+ toggleTeam,
setSearch,
setSort,
clearAllFilters,
@@ -78,7 +79,8 @@ export function VisualReviewFlakinessScene(): JSX.Element {
unquarantineIdentifier,
} = useActions(visualReviewFlakinessSceneLogic)
- const isFiltered = filters.typeKeys.length > 0 || filters.areas.length > 0 || filters.search.length > 0
+ const isFiltered =
+ filters.typeKeys.length > 0 || filters.areas.length > 0 || filters.teams.length > 0 || filters.search.length > 0
const hasPopulation = (overview?.entries.length ?? 0) > 0
const confirmLift = (entry: FlakinessEntryApi): void => {
@@ -202,6 +204,8 @@ export function VisualReviewFlakinessScene(): JSX.Element {
toggleType(value)
} else if (group === 'area') {
toggleArea(value)
+ } else if (group === 'team') {
+ toggleTeam(value)
}
}}
/>
diff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts
index 273f296cbcbb..6fba76c9ebd0 100644
--- a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts
+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.test.ts
@@ -137,6 +137,80 @@ describe('visualReviewFlakinessSceneLogic', () => {
})
})
+ describe('when a team arrives in the URL', () => {
+ const brokenEntry = (
+ identifier: string,
+ ownerTeam: string | null
+ ): FlakinessOverviewApi['entries'][number] => ({
+ identifier,
+ run_type: 'storybook',
+ browser: null,
+ thumbnail_hash: null,
+ width: null,
+ height: null,
+ variant_count: 0,
+ hard_count: 40,
+ soft_count: 0,
+ window_runs: 41,
+ hard_rate: 40 / 41,
+ soft_rate: 0,
+ last_flaked_at: '2026-06-10T09:00:00Z',
+ avg_diff_percentage: null,
+ worst_soft_diff_percentage: null,
+ headroom: null,
+ baseline_age_days: 3,
+ daily_hard_counts: [],
+ daily_soft_counts: [],
+ baseline_moved_day_index: null,
+ flakiness_state: 'broken',
+ is_quarantined: false,
+ needs_decision: false,
+ quarantine: null,
+ owner_team: ownerTeam,
+ })
+
+ beforeEach(() => {
+ initKeaTests()
+ useMocks({
+ get: {
+ [FLAKINESS_URL]: {
+ ...overview,
+ entries: [
+ brokenEntry('replay-player--default--light', 'team-replay'),
+ brokenEntry('heatmaps-scene--default--light', 'team-web-analytics'),
+ brokenEntry('settings-domains--default--light', 'unowned'),
+ brokenEntry('playwright-login--default', null),
+ ],
+ },
+ },
+ })
+ logic = visualReviewFlakinessSceneLogic({ repoId: REPO_ID })
+ logic.mount()
+ })
+
+ // A team's digest links here with its slug, and has to open on that team's rows.
+ it('shows only the rows that team owns', async () => {
+ router.actions.push(`/visual_review/repos/${REPO_ID}/flakiness`, {}, { teams: 'team-replay' })
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.filters.teams).toEqual(['team-replay'])
+ expect(logic.values.filteredEntries.map((entry) => entry.identifier)).toEqual([
+ 'replay-player--default--light',
+ ])
+ expect(logic.values.filters.preset).toBe('broken')
+ })
+
+ it('lists each known owner and leaves out rows with no known owner', async () => {
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.facetGroups.team.map((bucket) => bucket.label).sort()).toEqual([
+ 'No owner',
+ 'team-replay',
+ 'team-web-analytics',
+ ])
+ })
+ })
+
describe('when the preset arrives in the URL', () => {
beforeEach(() => {
initKeaTests()
diff --git a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts
index d04b0b792b4c..539f472ff98f 100644
--- a/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewFlakinessSceneLogic.ts
@@ -31,6 +31,7 @@ export type Filters = {
preset: FlakinessPreset
typeKeys: string[]
areas: string[]
+ teams: string[]
search: string
sort: FlakinessSort
}
@@ -43,6 +44,7 @@ const EMPTY_FILTERS: Filters = {
preset: 'needs_decision',
typeKeys: [],
areas: [],
+ teams: [],
search: '',
sort: 'failures',
}
@@ -68,6 +70,14 @@ function typeLabelOf(key: string): string {
return key
}
+// Pinned to UNOWNED_TEAM in the engineering analytics facade, which the backend sends for a story
+// file that no ownership entry covers.
+const UNOWNED_TEAM = 'unowned'
+
+function teamLabelOf(team: string): string {
+ return team === UNOWNED_TEAM ? 'No owner' : team
+}
+
function matchesPreset(entry: DecoratedEntry, preset: FlakinessPreset): boolean {
switch (preset) {
case 'broken':
@@ -122,6 +132,13 @@ function applyFilters(
if (exclude !== 'areas' && filters.areas.length && !filters.areas.includes(entry._area)) {
return false
}
+ if (
+ exclude !== 'teams' &&
+ filters.teams.length &&
+ !(entry.owner_team && filters.teams.includes(entry.owner_team))
+ ) {
+ return false
+ }
if (exclude !== 'search' && search && !entry.identifier.toLowerCase().includes(search)) {
return false
}
@@ -250,6 +267,9 @@ export interface visualReviewFlakinessSceneLogicActions {
toggleArea: (value: string) => {
value: string
}
+ toggleTeam: (value: string) => {
+ value: string
+ }
toggleType: (value: string) => {
value: string
}
@@ -297,6 +317,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
landOnPreset: (preset: FlakinessPreset) => ({ preset }),
toggleType: (value: string) => ({ value }),
toggleArea: (value: string) => ({ value }),
+ toggleTeam: (value: string) => ({ value }),
setSearch: (search: string) => ({ search }),
setSort: (sort: FlakinessSort) => ({ sort }),
clearAllFilters: true,
@@ -367,6 +388,12 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
? state.areas.filter((area) => area !== value)
: [...state.areas, value],
}),
+ toggleTeam: (state, { value }) => ({
+ ...state,
+ teams: state.teams.includes(value)
+ ? state.teams.filter((team) => team !== value)
+ : [...state.teams, value],
+ }),
setSearch: (state, { search }) => ({ ...state, search }),
setSort: (state, { sort }) => ({ ...state, sort }),
clearAllFilters: (state) => ({ ...EMPTY_FILTERS, preset: state.preset }),
@@ -424,6 +451,12 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
),
area: bucketize(applyFilters(entries, filters, 'areas').map((entry) => entry._area)),
stability: [],
+ team: bucketize(
+ applyFilters(entries, filters, 'teams').flatMap((entry) =>
+ entry.owner_team ? [entry.owner_team] : []
+ ),
+ teamLabelOf
+ ),
}),
],
facetSelection: [
@@ -432,6 +465,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
type: new Set(filters.typeKeys),
area: new Set(filters.areas),
stability: new Set<string>(),
+ team: new Set(filters.teams),
}),
],
thumbnailBasePath: [
@@ -465,7 +499,9 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
// the whole population while the entry list stops at the cap, so a
// tile can read 12 with none of those twelve actually listed, and
// landing on it would show a filled tile above an empty table.
- const rows = values.decoratedEntries
+ // Every other filter applies, so a link that names a team lands on
+ // a preset that team has rows in.
+ const rows = applyFilters(values.decoratedEntries, values.filters, 'preset')
const has = (preset: FlakinessPreset): boolean => rows.some((entry) => matchesPreset(entry, preset))
if (has(values.filters.preset)) {
return
@@ -525,6 +561,9 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
if (filters.areas.length) {
hash.areas = filters.areas.join(',')
}
+ if (filters.teams.length) {
+ hash.teams = filters.teams.join(',')
+ }
if (filters.search) {
hash.q = filters.search
}
@@ -539,6 +578,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
setPreset: toUrl,
toggleType: toUrl,
toggleArea: toUrl,
+ toggleTeam: toUrl,
setSearch: toUrl,
setSort: toUrl,
// Not an empty hash: the preset survives a clear, and dropping it from
@@ -557,6 +597,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
preset: presetFromHash(hash.preset),
typeKeys: hash.types ? hash.types.split(',') : [],
areas: hash.areas ? hash.areas.split(',') : [],
+ teams: hash.teams ? hash.teams.split(',') : [],
search: hash.q ?? '',
sort: hash.sort === 'recent' ? 'recent' : 'failures',
}
@@ -575,6 +616,7 @@ export const visualReviewFlakinessSceneLogic = kea<visualReviewFlakinessSceneLog
}
syncToggles(next.typeKeys, current.typeKeys, actions.toggleType)
syncToggles(next.areas, current.areas, actions.toggleArea)
+ syncToggles(next.teams, current.teams, actions.toggleTeam)
},
})),
afterMount(({ actions }) => {
diff --git a/products/visual_review/frontend/scenes/visualReviewSnapshotOverviewSceneLogic.ts b/products/visual_review/frontend/scenes/visualReviewSnapshotOverviewSceneLogic.ts
index ea2969787b30..2ee2a379d3ec 100644
--- a/products/visual_review/frontend/scenes/visualReviewSnapshotOverviewSceneLogic.ts
+++ b/products/visual_review/frontend/scenes/visualReviewSnapshotOverviewSceneLogic.ts
@@ -477,6 +477,7 @@ export const visualReviewSnapshotOverviewSceneLogic = kea<visualReviewSnapshotOv
count: stabilityBase.filter((e) => e._stability.includes(k as keyof typeof STABILITY_KEYS))
.length,
})),
+ team: [],
}
},
],
@@ -486,6 +487,7 @@ export const visualReviewSnapshotOverviewSceneLogic = kea<visualReviewSnapshotOv
type: new Set(filters.typeKeys),
area: new Set(filters.areas),
stability: new Set(filters.stability),
+ team: new Set<string>(),
}),
],
thumbnailBasePath: [
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 88748b534f89..2ecc6d18774a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -9475,6 +9475,8 @@ export namespace Schemas {
export interface AddSnapshotsInput {
snapshots: SnapshotManifestItem[];
baseline_hashes?: AddSnapshotsInputBaselineHashes;
+ /** SHA-256 of the story-to-file map the CLI built from the Storybook index.json of this run's build. Every shard of a run sends the same value. Empty when the run sends no map. */
+ story_index_hash?: string;
}
export type UploadTargetFields = {[key: string]: string};
@@ -9486,6 +9488,8 @@ export namespace Schemas {
}
export interface AddSnapshotsResult {
+ /** Where to upload the story-to-file map, as a presigned POST with a JSON body. Null when the request sent no map, or the store already holds a map with that hash. */
+ story_index_upload?: UploadTarget | null;
added: number;
uploads: UploadTarget[];
}
@@ -42225,6 +42229,11 @@ export namespace Schemas {
needs_decision: boolean;
/** Active quarantine details when `is_quarantined` is true. Null otherwise. */
quarantine?: BaselineQuarantineSummary | null;
+ /**
+ * Slug of the team that owns the file this snapshot's story lives in, from the repository's ownership files. `unowned` when no entry covers the file. Null when ownership is unknown: the snapshot is not a Storybook snapshot, the newest default-branch run sent no story index, the story is not in it, or the ownership files could not be read.
+ * @nullable
+ */
+ owner_team?: string | null;
identifier: string;
run_type: string;
/** @nullable */