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 debt digest weekly as a structured slack message (#99776)

Julian Bezc5e08428239f
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index f8b978a92f92..46832fed46e5 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -1082,9 +1082,12 @@ 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", minute="30", day_of_week="1-5"),
+ crontab(hour="7,19", minute="30"),
send_visual_review_debt_digests.s(),
name="send visual review debt digests",
expires_seconds=60 * 60,
diff --git a/posthog/team_notifications/slack.py b/posthog/team_notifications/slack.py
index 58aeaf571ce4..fce09a27f9e5 100644
--- a/posthog/team_notifications/slack.py
+++ b/posthog/team_notifications/slack.py
@@ -7,8 +7,8 @@ failure does to the product's own records, stay with the product.
from __future__ import annotations
-from collections.abc import Mapping
-from typing import Literal
+from collections.abc import Mapping, Sequence
+from typing import Any, Literal
import structlog
from slack_sdk.errors import SlackApiError
@@ -22,6 +22,14 @@ logger = structlog.get_logger(__name__)
# Slack rejects a section block over 3000 characters. The margin covers the mrkdwn escaping, which
# can turn one character into five.
MAX_SECTION_CHARS = 2900
+# Slack's other caps on one message. A block over any of them makes Slack refuse the whole post,
+# so a caller that cannot cut the value has to leave the block out.
+MAX_HEADER_CHARS = 150
+MAX_BUTTON_TEXT_CHARS = 75
+MAX_BUTTON_URL_CHARS = 3000
+MAX_BLOCKS = 50
+# The plain-text fallback. Slack cuts a longer one without saying so, rather than refusing the post.
+MAX_TEXT_CHARS = 40_000
def clip_text(text: str, limit: int) -> str:
@@ -31,9 +39,58 @@ def clip_text(text: str, limit: int) -> str:
return text[: max(limit - 1, 0)] + "…"
-def section_block(text: str) -> list[dict]:
- """One mrkdwn section, in the block list a post takes."""
- return [{"type": "section", "text": {"type": "mrkdwn", "text": text}}]
+@frozen
+class SlackButton:
+ """A link button, under a message or beside a section."""
+
+ text: str
+ url: str
+ primary: bool = False
+
+
+def _button_element(button: SlackButton) -> dict[str, Any]:
+ element: dict[str, Any] = {
+ "type": "button",
+ # Clipped here rather than at each call site, because Slack refuses the post instead of
+ # cutting the label itself.
+ "text": {"type": "plain_text", "text": clip_text(button.text, MAX_BUTTON_TEXT_CHARS), "emoji": True},
+ "url": button.url,
+ }
+ if button.primary:
+ element["style"] = "primary"
+ return element
+
+
+def header_block(text: str) -> dict[str, Any]:
+ """A message's title. Slack renders it as plain text, so mrkdwn in it stays literal."""
+ return {"type": "header", "text": {"type": "plain_text", "text": clip_text(text, MAX_HEADER_CHARS), "emoji": True}}
+
+
+def context_block(text: str) -> dict[str, Any]:
+ """A line of small print under whatever it belongs to."""
+ return {"type": "context", "elements": [{"type": "mrkdwn", "text": text}]}
+
+
+def section_block(text: str, button: SlackButton | None = None) -> dict[str, Any]:
+ """One mrkdwn section, with a link button on its right when the section has one action."""
+ block: dict[str, Any] = {"type": "section", "text": {"type": "mrkdwn", "text": text}}
+ if button is not None:
+ block["accessory"] = _button_element(button)
+ return block
+
+
+def fields_block(fields: Sequence[str]) -> dict[str, Any]:
+ """A section of short mrkdwn fields, which Slack lays out in two columns."""
+ return {"type": "section", "fields": [{"type": "mrkdwn", "text": field} for field in fields]}
+
+
+def actions_block(buttons: Sequence[SlackButton]) -> dict[str, Any]:
+ """A row of link buttons of its own, for actions that belong to the whole message."""
+ return {"type": "actions", "elements": [_button_element(button) for button in buttons]}
+
+
+def divider_block() -> dict[str, Any]:
+ return {"type": "divider"}
# Slack channel flags that mark a channel as shared beyond this workspace. A caller that maps a team
@@ -100,7 +157,7 @@ def find_channel(
def post_message(
slack: SlackIntegration,
channel_id: str,
- blocks: list[dict],
+ blocks: list[dict[str, Any]],
text: str,
thread_ts: str | None = None,
) -> SlackResponse:
@@ -148,7 +205,7 @@ class SlackPostRefused(Exception):
def post_with_join(
slack: SlackIntegration,
channel_id: str,
- blocks: list[dict],
+ blocks: list[dict[str, Any]],
text: str,
*,
channel_name: str | None = None,
diff --git a/products/visual_review/README.md b/products/visual_review/README.md
index 55ca63a6d338..bd09496799de 100644
--- a/products/visual_review/README.md
+++ b/products/visual_review/README.md
@@ -41,16 +41,26 @@ The windows and the reasons behind them are constants in `backend/logic/retentio
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.
- Each invocation is capped by rows and by a time budget, so a backlog drains over days.
-### Daily debt digest
+### Weekly debt digest
-Every weekday 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 morning both conditions below are evaluated from current data, and nothing is stored about what was sent.
-An item repeats every weekday while it stands, and stops the day the condition no longer holds.
+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, the week, and the two counts, with buttons to the repository's flakiness overview and its snapshots.
+Under it, one thread reply per condition that has items: a line saying what to do about that condition, then one section per item with the single action that resolves it on a button beside it.
+The last reply says when the next digest comes and how to opt out.
+A team that owns nothing gets no message at all.
Two conditions, and nothing else:
- **Quarantine expiring.**
- An active quarantine that runs out inside `FLAKINESS_EXPIRY_SOON_DAYS`.
+ An active quarantine that runs out inside `FLAKINESS_EXPIRY_SOON_DAYS`, plus one day.
+ The extra day is overlap: two weekly runs can fall slightly more than seven days apart, and a quarantine expiring in that gap would otherwise never be reported.
+ The flakiness page keeps the plain seven days.
It clears when somebody extends it past the window, lifts it, or lets it lapse.
- **N accepted variants of the current baseline.**
`VARIANT_PILEUP_MIN` or more active intentional tolerations recorded against the hash the baseline currently holds, with no quarantine already covering the identity.
@@ -66,22 +76,25 @@ Attribution runs through the Storybook build behind the current baseline, and th
The build uploads its story index as a GitHub Actions artifact, so the digest reads the artifact of the workflow run recorded on that baseline run (`metadata["github_run_id"]`), and the index names the file each story lives in.
A snapshot identifier is a story id plus the theme, the browser when it is not chromium, and the viewport width for a story that snapshots several.
The full story id is looked up first and the width suffix is only stripped when that misses, because a story can be named after a width.
-The parsed index is cached per repository and workflow run for two days, and the key rotates on its own whenever the baseline moves.
+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.
Nothing is guessed from the identifier: a story name is not a path.
Only Storybook runs are attributed today.
Three outcomes have no owning team, and the digest keeps them apart:
-- **Nobody owns the file.** The story maps to a file, and no owners entry covers it. Add one for the path, which stays on the line.
+- **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.
-All three go to whoever owns `products/visual_review/`, in a triage part of that team's digest kept separate from the items those maintainers own.
+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.
-A missing artifact never turns the digest into "nobody owns this": the items still go out, and the lead says ownership is worked out again tomorrow.
+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, which is enough for a daily read of a moving baseline.
-A baseline that has not moved for longer reads as ownership could not be worked out, and the digest says so instead of guessing.
+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.
@@ -89,11 +102,11 @@ 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 Monday to Friday, and it fans out only to the repositories that are on.
+The beat task runs twice a day 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, whatever `debt_digest_enabled` says, because a run somebody starts is already a decision to send it.
-`--mode preview`, the default, renders every team's message and logs it without posting.
+`./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.
+`--mode preview`, the default, prints and logs the plain text behind every message without posting.
`--mode live` posts.
## The flow
diff --git a/products/visual_review/backend/logic/debt_digest.py b/products/visual_review/backend/logic/debt_digest.py
index 2425092866e4..3b009c6955bd 100644
--- a/products/visual_review/backend/logic/debt_digest.py
+++ b/products/visual_review/backend/logic/debt_digest.py
@@ -1,15 +1,16 @@
-"""The daily reminder about visual review debt a team is still carrying.
+"""The weekly reminder about visual review debt a team is still carrying.
-Stateless by design. Every morning the two conditions below are evaluated from current data,
+Stateless by design. Every Monday the two conditions below are evaluated from current data,
attributed to the team that owns the file the snapshot's story lives in today, and posted. Nothing
-is stored about what was sent, so an item repeats every day until the condition stops holding and
-disappears the moment it does. A team whose post fails is logged and the run moves on; tomorrow
+is stored about what was sent, so an item repeats every week until the condition stops holding and
+disappears the moment it does. A team whose post fails is logged and the run moves on; next Monday
recomputes everything from scratch.
The two conditions:
- Quarantine expiring. An active quarantine that runs out inside `FLAKINESS_EXPIRY_SOON_DAYS`.
- Somebody has to extend it, lift it, or decide to let it lapse.
+ Quarantine expiring. An active quarantine that runs out inside `FLAKINESS_EXPIRY_SOON_DAYS`, plus
+ a day of overlap so two weekly runs cannot skip one. Somebody has to extend it, lift it, or decide
+ to let it lapse.
Variant pile-up. `VARIANT_PILEUP_MIN` or more accepted variants standing against the baseline's
current hash, with no quarantine already covering the identity. The baseline has stopped
@@ -22,16 +23,25 @@ Nothing here claims a snapshot got better.
Attribution runs through the Storybook build behind the current baseline. Its story index names the
file each story lives in, and the repository's own ownership files name the team that owns that file.
Three things stop that: no owners entry covers the file, the index has no such story, or there is no
-index to read. All three go to the visual review maintainers as triage, kept apart from the items
-those maintainers own, because holding an item until a team takes it is not owning it.
+index to read. All three go to the visual review maintainers, in a message of their own rather than
+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.
+
+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.
"""
from __future__ import annotations
-from collections.abc import Mapping
-from dataclasses import field
-from datetime import datetime
+from calendar import MONDAY
+from collections.abc import Mapping, Sequence
+from datetime import date, datetime, timedelta
from enum import StrEnum
+from typing import Any
from urllib.parse import quote
from django.conf import settings
@@ -46,12 +56,21 @@ from posthog.dataclasses import frozen
from posthog.models.integration import Integration, SlackIntegration
from posthog.models.user import User
from posthog.team_notifications.slack import (
+ MAX_BLOCKS,
+ MAX_BUTTON_URL_CHARS,
MAX_SECTION_CHARS,
+ MAX_TEXT_CHARS,
+ SlackButton,
SlackChannel,
SlackPostRefused,
+ actions_block,
clip_text,
+ context_block,
+ divider_block,
fetch_channel_map,
+ fields_block,
find_channel,
+ header_block,
post_message,
post_with_join,
section_block,
@@ -60,7 +79,7 @@ from posthog.team_notifications.slack import (
from products.engineering_analytics.backend.facade.api import resolve_path_owners
from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
-from ..facade.contracts import VARIANT_PILEUP_MIN
+from ..facade.contracts import FLAKINESS_EXPIRY_SOON_DAYS, VARIANT_PILEUP_MIN
from ..facade.enums import RunType
from ..models import QuarantinedIdentifier, Repo, Run
from . import quarantine, run_queries, story_index, toleration
@@ -86,13 +105,35 @@ _MAX_LINE_CHARS = MAX_SECTION_CHARS // 2
_MAX_IDENTIFIER_CHARS = 160
_MAX_REASON_CHARS = 200
+# Slack takes 50 blocks in one message. One chunk size is used everywhere, so it keeps room for the
+# heading every message repeats, the divider and context that close the last one, and the header and
+# context a top-level message opens with.
+_ITEMS_PER_MESSAGE = MAX_BLOCKS - 5
+
MODE_PREVIEW = "preview"
MODE_LIVE = "live"
MODES = (MODE_PREVIEW, MODE_LIVE)
-_FOOTER = (
- "This repeats every weekday while the items stay unresolved. "
- "To opt out, set notifications: {visual_review: false} under your team in owners.yaml."
+# One day wider than the window the flakiness page uses. Two weekly runs can fall slightly more than
+# 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. Quarantines that lapse start failing the gate again on the next run."
+)
+_QUARANTINE_HEADING = (
+ "*Quarantines expiring soon*\n"
+ "Fix the story and let the quarantine lapse, or extend it with a new reason. "
+ "A lapsed quarantine fails the gate again."
+)
+_PILEUP_HEADING = (
+ "*Snapshots with piled-up variants*\n"
+ f"{VARIANT_PILEUP_MIN} or more accepted renderings mean the baseline is wrong. "
+ "Approve the current rendering as the baseline and the variants stop counting."
)
@@ -104,14 +145,12 @@ class AttributionKind(StrEnum):
UNAVAILABLE = "unavailable" # there is no index to ask for this run type today
-# Each outcome asks the reader for a different fix. A placed path in triage is one no owners entry covers.
-_TRIAGE_HEADERS: dict[AttributionKind, str] = {
- AttributionKind.PLACED: "*Nobody owns the file yet.* Add an owners entry for the path at the end of each line.",
+# Each outcome asks the reader for a different fix. A placed path here is one no owners entry covers.
+# UNAVAILABLE is missing on purpose: it asks the reader for nothing, so it is counted, not listed.
+_TRIAGE_HEADINGS: dict[AttributionKind, str] = {
+ AttributionKind.PLACED: "*The file has no owners entry*\nAdd an owners entry for the path.",
AttributionKind.STORY_ABSENT: (
- "*The story is not in the Storybook index.* Check whether it moved, was renamed, or was deleted."
- ),
- AttributionKind.UNAVAILABLE: (
- "*Ownership could not be worked out today.* Nothing to do, the digest tries again tomorrow."
+ "*The story is not in the Storybook index*\nCheck whether it moved, was renamed, or was deleted."
),
}
@@ -133,12 +172,18 @@ class Attribution:
@frozen
class DebtItem:
- """One thing somebody still has to decide about, and what is known about where it lives."""
+ """One thing somebody still has to decide about, and what is known about where it lives.
+
+ Carries both renderings of itself, because Slack needs both: `facts` goes under the identity in
+ a block, and `line` is the whole item on one line for the plain text a notification falls back
+ to.
+ """
identifier: str
run_type: str
attribution: Attribution
line: str
+ facts: str
@frozen
@@ -163,14 +208,65 @@ class TriageGroup:
@frozen
class TeamDigest:
- """One team's share of a repo's debt, ready to post."""
+ """One team's share of a repo's debt, ready to post.
+
+ Never empty. A team that owns nothing gets no message, so no team is told it owes nothing.
+ """
team_slug: str
expiring_quarantines: list[DebtItem]
variant_pileups: list[DebtItem]
- # Items nobody owns yet. Only the maintainers' digest carries them, and they hold them until a
- # team takes them.
- triage: list[TriageGroup] = field(default_factory=list)
+
+
+@frozen
+class MaintainersDigest:
+ """The items nobody owns yet, and the team that holds them until somebody takes them."""
+
+ team_slug: str
+ groups: list[TriageGroup]
+
+
+@frozen
+class RepoDigests:
+ """Everything one repo's run has to post: a digest per owning team, plus the unowned items."""
+
+ teams: list[TeamDigest]
+ maintainers: MaintainersDigest | None
+
+
+@frozen
+class SlackMessage:
+ """One post: the blocks Slack renders, and the plain text it shows wherever they do not."""
+
+ blocks: list[dict[str, Any]]
+ text: str
+
+
+@frozen
+class MessagePart:
+ """One block, and the plain line that stands in for it in the message's fallback text."""
+
+ block: dict[str, Any]
+ line: str
+
+
+@frozen
+class ReplyGroup:
+ """One subject inside a message: a heading that says what to do, and the items it holds."""
+
+ heading: MessagePart
+ items: list[MessagePart]
+
+
+@frozen
+class Post:
+ """One top-level Slack message and the replies that belong in its thread."""
+
+ team_slug: str
+ lead: SlackMessage
+ replies: list[SlackMessage]
+ item_count: int
+ triage_count: int
@frozen
@@ -193,6 +289,19 @@ def _repo_snapshots_url(repo: Repo) -> str:
return f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/repos/{repo.id}/snapshots"
+def _repo_flakiness_url(repo: Repo) -> str:
+ return f"{settings.SITE_URL}/project/{repo.team_id}/visual_review/repos/{repo.id}/flakiness"
+
+
+def _snapshot_button(repo: Repo, item: DebtItem, text: str) -> SlackButton:
+ """The item's button, pointing at the repo's list when the snapshot URL is too long for Slack.
+
+ Same reason as `_linked_line` below: an encoded identifier can outgrow the cap on its own.
+ """
+ url = _snapshot_url(repo, item.run_type, item.identifier)
+ return SlackButton(text=text, url=url if len(url) <= MAX_BUTTON_URL_CHARS else _repo_snapshots_url(repo))
+
+
def _linked_line(repo: Repo, body: str, run_type: str, identifier: str) -> str:
"""One item's line with its link, kept under the per-line cap.
@@ -208,14 +317,54 @@ def _linked_line(repo: Repo, body: str, run_type: str, identifier: str) -> str:
return f"{clip_text(body, _MAX_LINE_CHARS - len(listed))}{listed}"
+def _monday_of(moment: datetime) -> date:
+ return moment.date() - timedelta(days=moment.weekday())
+
+
+def _month_day(day: date) -> str:
+ """A date the way a person says it out loud, such as Sep 14."""
+ return f"{day:%b} {day.day}"
+
+
+def _expiry_word(expires_at: datetime | None, now: datetime) -> str:
+ """When a quarantine runs out, said the way a reader plans a week.
+
+ A weekday name only carries inside the coming week: seven days out it names the day the reader
+ is reading on, so that one falls back to the date.
+ """
+ if expires_at is None:
+ return "soon"
+ days = (expires_at.date() - now.date()).days
+ if days <= 0:
+ return "today"
+ if days < 7:
+ return f"{expires_at:%A}"
+ return _month_day(expires_at.date())
+
+
+def _author_name(entry: QuarantinedIdentifier, authors: dict[int, str]) -> str:
+ return escape_slack_mrkdwn(authors.get(entry.created_by_id or 0, "someone"))
+
+
+def _quarantine_facts(entry: QuarantinedIdentifier, authors: dict[int, str], now: datetime) -> str:
+ return (
+ f"Expires *{_expiry_word(entry.expires_at, now)}* · opened by {_author_name(entry, authors)}\n"
+ f'_"{escape_slack_mrkdwn(clip_text(entry.reason, _MAX_REASON_CHARS))}"_'
+ )
+
+
+def _pileup_facts(count: int) -> str:
+ return f"*{count}* accepted variants of the current baseline"
+
+
def _quarantine_line(repo: Repo, entry: QuarantinedIdentifier, authors: dict[int, str], now: datetime) -> str:
days = max((entry.expires_at - now).days, 0) if entry.expires_at is not None else 0
- who = authors.get(entry.created_by_id or 0, "someone")
body = (
f"Quarantine expires in {days} days"
f" · {escape_slack_mrkdwn(clip_text(entry.identifier, _MAX_IDENTIFIER_CHARS))}"
f" ({escape_slack_mrkdwn(entry.run_type)})"
- f' · opened by {escape_slack_mrkdwn(who)} for "{escape_slack_mrkdwn(clip_text(entry.reason, _MAX_REASON_CHARS))}"'
+ f" · opened by {_author_name(entry, authors)}"
+ f' for "{escape_slack_mrkdwn(clip_text(entry.reason, _MAX_REASON_CHARS))}"'
)
return _linked_line(repo, body, entry.run_type, entry.identifier)
@@ -293,7 +442,7 @@ def _attribution(sources: Mapping[str, story_index.StoryIndex | str], run_type:
def collect_debt(repo: Repo, now: datetime) -> RepoDebt:
"""Evaluate both conditions against current data, attribute each item, and render its line."""
newest_run_by_type = run_queries.newest_run_by_run_type(run_queries.latest_default_branch_runs(repo.id))
- expiring = quarantine.list_expiring_quarantines(repo.id, now=now)
+ expiring = quarantine.list_expiring_quarantines(repo.id, now=now, within_days=_DIGEST_EXPIRY_WINDOW_DAYS)
quarantined_keys = quarantine.active_quarantine_keys(repo.id, now=now)
piled_up = {
key: count
@@ -317,6 +466,7 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:
run_type=entry.run_type,
attribution=_attribution(sources, entry.run_type, entry.identifier),
line=_quarantine_line(repo, entry, authors, now),
+ facts=_quarantine_facts(entry, authors, now),
)
for entry in expiring
],
@@ -326,6 +476,7 @@ def collect_debt(repo: Repo, now: datetime) -> RepoDebt:
run_type=key.run_type,
attribution=_attribution(sources, key.run_type, key.identifier),
line=_pileup_line(repo, key.run_type, key.identifier, count),
+ facts=_pileup_facts(count),
)
# Biggest pile first, then by identity so a tie reads the same way every morning.
for key, count in sorted(
@@ -348,12 +499,12 @@ def _owning_team(item: DebtItem, ownership: PathOwnership) -> str:
return ownership.team_by_path.get(item.attribution.source_path, UNOWNED_TEAM)
-def split_by_team(debt: RepoDebt, ownership: PathOwnership) -> list[TeamDigest]:
+def split_by_team(debt: RepoDebt, ownership: PathOwnership) -> RepoDigests:
"""Group a repo's debt by the team that owns each item's story file.
- Everything else is triage rather than debt of the maintainers' own: it goes into the digest of
- the team that owns the product directory, grouped by why it has no owner. When that team is
- unowned too, the item is dropped with a log line rather than posted somewhere arbitrary.
+ Everything else is not debt of the maintainers' own, so it goes to them as a message apart from
+ their own digest, grouped by why it has no owner. When nobody owns the product directory either,
+ the item is dropped with a log line rather than posted somewhere arbitrary.
"""
fallback = ownership.team_by_path.get(_PRODUCT_PATH, UNOWNED_TEAM)
expiring_by_team: dict[str, list[DebtItem]] = {}
@@ -377,57 +528,138 @@ def split_by_team(debt: RepoDebt, ownership: PathOwnership) -> list[TeamDigest]:
# Declaration order, so the three groups always read in the same order.
triage = [TriageGroup(kind=kind, items=triage_by_kind[kind]) for kind in AttributionKind if kind in triage_by_kind]
- teams = expiring_by_team.keys() | pileups_by_team.keys()
- if triage:
- teams = teams | {fallback}
- return [
- TeamDigest(
- team_slug=team,
- expiring_quarantines=expiring_by_team.get(team, []),
- variant_pileups=pileups_by_team.get(team, []),
- triage=triage if team == fallback else [],
- )
- for team in sorted(teams)
- ]
+ return RepoDigests(
+ teams=[
+ TeamDigest(
+ team_slug=team,
+ expiring_quarantines=expiring_by_team.get(team, []),
+ variant_pileups=pileups_by_team.get(team, []),
+ )
+ for team in sorted(expiring_by_team.keys() | pileups_by_team.keys())
+ ],
+ maintainers=MaintainersDigest(team_slug=fallback, groups=triage) if triage else None,
+ )
+
+
+def _message(parts: Sequence[MessagePart]) -> SlackMessage:
+ """One post from its parts. A part with no line of its own, such as a divider, adds none."""
+ text = "\n".join(part.line for part in parts if part.line)
+ # Slack cuts a fallback over the cap without saying so, and the blocks carry every item anyway.
+ return SlackMessage(blocks=[part.block for part in parts], text=clip_text(text, MAX_TEXT_CHARS))
-def _unavailable_details(digest: TeamDigest) -> list[str]:
- """Every distinct reason ownership could not be worked out for this digest's triage items."""
- return sorted(
- {item.attribution.detail for group in digest.triage for item in group.items if item.attribution.detail}
+def _split_into_messages(
+ groups: Sequence[ReplyGroup], footer: Sequence[MessagePart], preamble: Sequence[MessagePart] = ()
+) -> list[SlackMessage]:
+ """One message per group, split again when a group holds more items than Slack takes in a post.
+
+ A group with no items produces no message at all. The heading repeats on a continuation, because
+ a message that opens with an item says nothing about what the reader is looking at.
+ """
+ parts_by_message: list[list[MessagePart]] = []
+ for group in groups:
+ for start in range(0, len(group.items), _ITEMS_PER_MESSAGE):
+ parts_by_message.append([group.heading, *group.items[start : start + _ITEMS_PER_MESSAGE]])
+ if not parts_by_message:
+ return []
+ parts_by_message[0] = [*preamble, *parts_by_message[0]]
+ parts_by_message[-1].extend(footer)
+ return [_message(parts) for parts in parts_by_message]
+
+
+def _heading_part(text: str) -> MessagePart:
+ return MessagePart(block=section_block(text), line=text)
+
+
+def _header_part(text: str) -> MessagePart:
+ return MessagePart(block=header_block(text), line=text)
+
+
+def _context_part(text: str) -> MessagePart:
+ return MessagePart(block=context_block(text), line=text)
+
+
+def _closing_parts(text: str) -> list[MessagePart]:
+ """A rule and one line of small print, which is how a message signs off."""
+ return [MessagePart(block=divider_block(), line=""), _context_part(text)]
+
+
+def _item_text(item: DebtItem, extra: str = "") -> str:
+ """One item's section: what it is, then its facts, then whatever its group adds under them."""
+ title = (
+ f"*{escape_slack_mrkdwn(clip_text(item.identifier, _MAX_IDENTIFIER_CHARS))}* "
+ f"{escape_slack_mrkdwn(item.run_type)}"
+ )
+ return clip_text("\n".join(part for part in (title, item.facts, extra) if part), MAX_SECTION_CHARS)
+
+
+def _item_part(repo: Repo, item: DebtItem, button_text: str) -> MessagePart:
+ return MessagePart(block=section_block(_item_text(item), _snapshot_button(repo, item, button_text)), line=item.line)
+
+
+def _footer_parts(now: datetime) -> list[MessagePart]:
+ """What closes the last reply: when the next one comes, and how to stop getting them."""
+ return _closing_parts(
+ f"Next digest Monday, {_month_day(_monday_of(now) + timedelta(days=7))}. "
+ "Opt out with `notifications: {visual_review: false}` under your team in owners.yaml."
)
-def lead_text(digest: TeamDigest, repo: Repo) -> str:
+def lead_text(repo: Repo, digest: TeamDigest) -> str:
+ """The lead as one sentence, for the notification Slack shows before the blocks render."""
expiring = len(digest.expiring_quarantines)
pileups = len(digest.variant_pileups)
- # A digest that carries triage only still names the team and the repo, so the maintainers can
- # see whose channel it landed in without opening the thread.
- owed = (
+ return clip_text(
+ f"Visual review debt for {digest.team_slug} in {repo.repo_full_name}: "
f"{expiring} quarantine{'' if expiring == 1 else 's'} expire{'s' if expiring == 1 else ''} soon, "
- f"{pileups} snapshot{'' if pileups == 1 else 's'} with piled-up variants."
- if expiring or pileups
- else "nothing this team owns today."
+ f"{pileups} snapshot{'' if pileups == 1 else 's'} with piled-up variants.",
+ MAX_SECTION_CHARS,
+ )
+
+
+def lead_message(repo: Repo, digest: TeamDigest, now: datetime) -> SlackMessage:
+ """What lands in the channel: the team, the week, the two counts, and the pages behind them."""
+ expiring = len(digest.expiring_quarantines)
+ pileups = len(digest.variant_pileups)
+ return SlackMessage(
+ blocks=[
+ header_block(f"Visual review debt for {digest.team_slug}"),
+ context_block(f"{repo.repo_full_name} · week of {_month_day(_monday_of(now))} · weekly digest"),
+ fields_block(
+ [
+ f"*{expiring} quarantine{'' if expiring == 1 else 's'}* expire{'s' if expiring == 1 else ''} soon",
+ f"*{pileups} snapshot{'' if pileups == 1 else 's'}* with piled-up variants",
+ ]
+ ),
+ section_block(_LEAD_BODY),
+ actions_block(
+ [
+ SlackButton(text="Open flakiness overview", url=_repo_flakiness_url(repo), primary=True),
+ SlackButton(text="Open snapshots", url=_repo_snapshots_url(repo)),
+ ]
+ ),
+ ],
+ text=lead_text(repo, digest),
)
- sentences = [f"Visual review debt for {digest.team_slug} in {repo.repo_full_name}: {owed}"]
- triage_count = sum(len(group.items) for group in digest.triage)
- if triage_count:
- sentences.append(
- f"Plus {triage_count} in triage that nobody owns yet: visual review maintainers hold them "
- "until a team takes them."
- )
- details = _unavailable_details(digest)
- if details:
- sentences.append(
- "Ownership could not be worked out for some of them today, because "
- f"{escape_slack_mrkdwn('; '.join(details))}. The digest tries again tomorrow."
- )
- # The lead is one Slack section like every thread line, so it takes the same cap.
- return clip_text(" ".join(sentences), MAX_SECTION_CHARS)
+
+
+def thread_messages(repo: Repo, digest: TeamDigest, now: datetime) -> list[SlackMessage]:
+ """One reply per condition that has items, each item carrying the action that resolves it."""
+ groups = [
+ ReplyGroup(
+ heading=_heading_part(_QUARANTINE_HEADING),
+ items=[_item_part(repo, item, "Extend or fix") for item in digest.expiring_quarantines],
+ ),
+ ReplyGroup(
+ heading=_heading_part(_PILEUP_HEADING),
+ items=[_item_part(repo, item, "Reset baseline") for item in digest.variant_pileups],
+ ),
+ ]
+ return _split_into_messages(groups, _footer_parts(now))
def _triage_line(item: DebtItem) -> str:
- """One triage item's line, carrying what its group's header asks the reader to act on."""
+ """One triage item's line, carrying what its group's heading asks the reader to act on."""
if item.attribution.kind == AttributionKind.PLACED:
return f"{item.line} · {escape_slack_mrkdwn(item.attribution.source_path)}"
if item.attribution.kind == AttributionKind.UNAVAILABLE:
@@ -435,44 +667,91 @@ def _triage_line(item: DebtItem) -> str:
return item.line
-def thread_texts(digest: TeamDigest) -> list[str]:
- """The item lines, grouped by condition and then by triage reason, split to fit Slack's section cap."""
- lines = [
- *(item.line for item in digest.expiring_quarantines),
- *(item.line for item in digest.variant_pileups),
+def _file_button(repo: Repo, item: DebtItem) -> SlackButton | None:
+ """The story's file on the default branch, which is where an owners entry is written against.
+
+ None when the URL is longer than Slack accepts. A long or non-ASCII path can outgrow the cap on
+ its own, and Slack refuses the whole message over one oversized button. The path is in the
+ section text as well, so leaving the button out costs the reader the link and nothing else.
+ """
+ path = quote(item.attribution.source_path)
+ url = f"https://github.com/{repo.repo_full_name}/blob/HEAD/{path}"
+ return SlackButton(text="Open file", url=url) if len(url) <= MAX_BUTTON_URL_CHARS else None
+
+
+def _placed_part(repo: Repo, item: DebtItem) -> MessagePart:
+ # The path stays in the text as well as behind the button, because it is what somebody types
+ # into owners.yaml.
+ text = _item_text(item, f"`{escape_slack_mrkdwn(item.attribution.source_path)}`")
+ return MessagePart(block=section_block(text, _file_button(repo, item)), line=_triage_line(item))
+
+
+def _triage_group(repo: Repo, group: TriageGroup) -> ReplyGroup:
+ """One reason for having no owner, and the items behind it."""
+ if group.kind == AttributionKind.PLACED:
+ items = [_placed_part(repo, item) for item in group.items]
+ else:
+ items = [
+ MessagePart(
+ block=section_block(_item_text(item), _snapshot_button(repo, item, "Open snapshot")),
+ line=_triage_line(item),
+ )
+ for item in group.items
+ ]
+ return ReplyGroup(heading=_heading_part(_TRIAGE_HEADINGS[group.kind]), items=items)
+
+
+def _unavailable_parts(items: Sequence[DebtItem]) -> list[MessagePart]:
+ """What closes the maintainers' message when a run could not read the index for some items.
+
+ They are counted rather than listed, because they ask the reader for nothing: the fix is another
+ run against another baseline, not a decision anybody makes this week. The reasons stay in the
+ log, where whoever maintains the digest looks for them.
+ """
+ if not items:
+ return []
+ logger.info(
+ "visual_review.debt_digest_ownership_unreadable",
+ item_count=len(items),
+ details=sorted({item.attribution.detail for item in items if item.attribution.detail}),
+ )
+ count = len(items)
+ return _closing_parts(
+ f"{count} item{'' if count == 1 else 's'} with no readable Storybook index this week "
+ f"{'is' if count == 1 else 'are'} not listed. Ownership is read again next Monday."
+ )
+
+
+def maintainers_messages(repo: Repo, digest: MaintainersDigest) -> list[SlackMessage]:
+ """The unowned items as their own post, or nothing when none of them asks anybody to act."""
+ groups = [_triage_group(repo, group) for group in digest.groups if group.kind in _TRIAGE_HEADINGS]
+ if not groups:
+ return []
+ listed = sum(len(group.items) for group in groups)
+ unavailable = [item for group in digest.groups if group.kind == AttributionKind.UNAVAILABLE for item in group.items]
+ preamble = [
+ _header_part(f"Unowned visual review debt in {repo.repo_full_name}"),
+ _context_part(
+ f"{listed} item{'' if listed == 1 else 's'} nobody owns yet · sent to the visual review maintainers"
+ ),
]
- for group in digest.triage:
- lines.append(_TRIAGE_HEADERS[group.kind])
- lines.extend(_triage_line(item) for item in group.items)
- lines.append(_FOOTER)
- # A cut line costs one reader one path; a line Slack refuses costs the team the rest of the thread.
- lines = [clip_text(line, MAX_SECTION_CHARS) for line in lines]
- messages: list[str] = []
- current: list[str] = []
- for line in lines:
- if current and len("\n".join([*current, line])) > MAX_SECTION_CHARS:
- messages.append("\n".join(current))
- current = []
- current.append(line)
- if current:
- messages.append("\n".join(current))
- return messages
+ return _split_into_messages(groups, _unavailable_parts(unavailable), preamble)
def resolve_channel(
- digest: TeamDigest, registry: Mapping[str, TeamEntry], channels_by_name: Mapping[str, SlackChannel]
+ team_slug: str, registry: Mapping[str, TeamEntry], channels_by_name: Mapping[str, SlackChannel]
) -> Delivery | None:
"""The team's own notifications channel, or None when it opted out or the name does not resolve."""
- answer = team_channel(digest.team_slug, registry, _CHANNEL_PURPOSE, _PRODUCER)
+ answer = team_channel(team_slug, registry, _CHANNEL_PURPOSE, _PRODUCER)
if answer.channel is None:
- logger.info("visual_review.debt_digest_team_opted_out", team_slug=digest.team_slug)
+ logger.info("visual_review.debt_digest_team_opted_out", team_slug=team_slug)
return None
name = answer.channel.removeprefix("#")
match = find_channel(channels_by_name, name, allow_shared=False)
if match.channel is None:
logger.info(
"visual_review.debt_digest_channel_unusable",
- team_slug=digest.team_slug,
+ team_slug=team_slug,
channel_name=name,
reason=match.reason,
)
@@ -480,18 +759,52 @@ def resolve_channel(
return Delivery(channel_id=match.channel.channel_id, channel_name=name)
+def plan_posts(repo: Repo, digests: RepoDigests, now: datetime) -> list[Post]:
+ """Every message this run sends, in the order it sends them.
+
+ A team is here only when it owns something, so no team is ever told it owns nothing. The
+ maintainers appear once for their own debt and again for what nobody owns, because the two ask
+ different things of them.
+ """
+ posts = [
+ Post(
+ team_slug=digest.team_slug,
+ lead=lead_message(repo, digest, now),
+ replies=thread_messages(repo, digest, now),
+ item_count=len(digest.expiring_quarantines) + len(digest.variant_pileups),
+ triage_count=0,
+ )
+ for digest in digests.teams
+ ]
+ maintainers = digests.maintainers
+ if maintainers is not None:
+ messages = maintainers_messages(repo, maintainers)
+ if messages:
+ posts.append(
+ Post(
+ team_slug=maintainers.team_slug,
+ lead=messages[0],
+ replies=messages[1:],
+ item_count=0,
+ triage_count=sum(len(group.items) for group in maintainers.groups),
+ )
+ )
+ return posts
+
+
def send_debt_digest(repo: Repo, mode: str) -> list[str]:
"""Evaluate, attribute, and post one repo's digest. One team's failure does not stop the rest.
- Returns each team's rendered message, so an operator running this by hand can read what the
- run would send without reaching into the logs.
+ Returns each post's plain text, so an operator running this by hand can read what the run would
+ send without reaching into the logs.
"""
# Anything that is not preview posts, so an undefined mode must stop here rather than go live.
if mode not in MODES:
logger.warning("visual_review.debt_digest_mode_unknown", mode=mode)
return []
- debt = collect_debt(repo, timezone.now())
+ now = timezone.now()
+ debt = collect_debt(repo, now)
if not debt.items:
logger.info("visual_review.debt_digest_nothing_owed", repo_id=str(repo.id), team_id=repo.team_id)
return []
@@ -499,13 +812,13 @@ def send_debt_digest(repo: Repo, mode: str) -> list[str]:
ownership = resolve_path_owners(repo.repo_full_name, paths_to_resolve(debt))
if not ownership.resolved:
# A blind answer names no team and carries no registry, so every item would read as
- # unowned and be dropped. Say so instead, and send the same items tomorrow.
+ # unowned and be dropped. Say so instead, and send the same items next week.
logger.warning("visual_review.debt_digest_ownership_unavailable", repo_id=str(repo.id), team_id=repo.team_id)
return []
- digests = split_by_team(debt, ownership)
+ posts = plan_posts(repo, split_by_team(debt, ownership), now)
if mode == MODE_PREVIEW:
- return [_preview_one(repo, digest, ownership.registry) for digest in digests]
+ return [_preview_one(repo, post, ownership.registry) for post in posts]
integration = Integration.objects.filter(team_id=repo.team_id, kind="slack").first()
if integration is None:
@@ -514,34 +827,38 @@ def send_debt_digest(repo: Repo, mode: str) -> list[str]:
channels_by_name = fetch_channel_map(integration)
rendered: list[str] = []
- for digest in digests:
+ for post in posts:
try:
- rendered.append(_send_one(repo, digest, ownership.registry, channels_by_name, integration))
+ rendered.append(_send_one(repo, post, ownership.registry, channels_by_name, integration))
except Exception as e:
# One team's Slack failure must not cost the rest of the repo its reminder, and there is
- # nothing to retry against: tomorrow's run sends the same items again.
+ # nothing to retry against: next Monday's run sends the same items again.
logger.warning(
"visual_review.debt_digest_team_failed",
repo_id=str(repo.id),
- team_slug=digest.team_slug,
+ team_slug=post.team_slug,
error=str(e),
)
return rendered
-def _preview_one(repo: Repo, digest: TeamDigest, registry: Mapping[str, TeamEntry]) -> str:
- """Render one team's digest and log it, without reading Slack at all."""
- rendered = "\n".join([lead_text(digest, repo), *thread_texts(digest)])
+def _post_text(post: Post) -> str:
+ return "\n".join([post.lead.text, *(reply.text for reply in post.replies)])
+
+
+def _preview_one(repo: Repo, post: Post, registry: Mapping[str, TeamEntry]) -> str:
+ """Render one post and log it, without reading Slack at all."""
+ rendered = _post_text(post)
# Preview holds no channel map, because fetching one needs the integration it deliberately does
# not touch. So the routing here only ever reports the team's own opt-out.
- resolved = resolve_channel(digest, registry, {})
+ resolved = resolve_channel(post.team_slug, registry, {})
logger.info(
"visual_review.debt_digest_preview",
repo_id=str(repo.id),
- team_slug=digest.team_slug,
+ team_slug=post.team_slug,
channel_name=resolved.channel_name if resolved is not None else None,
- item_count=len(digest.expiring_quarantines) + len(digest.variant_pileups),
- triage_count=sum(len(group.items) for group in digest.triage),
+ item_count=post.item_count,
+ triage_count=post.triage_count,
rendered=rendered,
)
return rendered
@@ -549,40 +866,64 @@ def _preview_one(repo: Repo, digest: TeamDigest, registry: Mapping[str, TeamEntr
def _send_one(
repo: Repo,
- digest: TeamDigest,
+ post: Post,
registry: Mapping[str, TeamEntry],
channels_by_name: Mapping[str, SlackChannel],
integration: Integration,
) -> str:
- lead = lead_text(digest, repo)
- thread = thread_texts(digest)
- delivery = resolve_channel(digest, registry, channels_by_name)
+ delivery = resolve_channel(post.team_slug, registry, channels_by_name)
if delivery is None:
return ""
slack = SlackIntegration(integration)
try:
thread_ts = post_with_join(
- slack, delivery.channel_id, section_block(lead), lead, channel_name=delivery.channel_name
+ slack, delivery.channel_id, post.lead.blocks, post.lead.text, channel_name=delivery.channel_name
)
except SlackPostRefused as e:
- logger.warning("visual_review.debt_digest_post_refused", team_slug=digest.team_slug, error=str(e))
+ logger.warning("visual_review.debt_digest_post_refused", team_slug=post.team_slug, error=str(e))
return ""
- # Without a parent to hang them on, the item lines land in the channel as separate top-level
+ # Without a parent to hang them on, the item blocks land in the channel as separate top-level
# posts, which is the noise the thread exists to remove.
if thread_ts is not None:
- for text in thread:
- post_message(slack, delivery.channel_id, section_block(text), text, thread_ts=thread_ts)
- return "\n".join([lead, *thread])
+ for reply in post.replies:
+ post_message(slack, delivery.channel_id, reply.blocks, reply.text, thread_ts=thread_ts)
+ 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.
The switch is the only way to stop the digest without a deploy, so the fan-out reads it rather
- than the per-repo task: a repo that is off costs no child task at all. For the repos that are
- on, the per-repo task stops as soon as one owes nothing, so a repo that never carries debt
- costs one cheap read a day. The fan-out only routes, so the rows stay unhydrated.
+ than the per-repo task: a repo that is off costs no child task at all, and it reads no Storybook
+ artifact on the runs that only warm the cache. The fan-out only routes, so the rows stay
+ unhydrated.
"""
# nosemgrep: idor-lookup-without-team — cross-team beat sweep, no user input
return list(Repo.objects.unscoped().filter(debt_digest_enabled=True).only("id", "team_id").order_by("created_at"))
diff --git a/products/visual_review/backend/logic/quarantine.py b/products/visual_review/backend/logic/quarantine.py
index 3b8e5ba90250..929a2cac7046 100644
--- a/products/visual_review/backend/logic/quarantine.py
+++ b/products/visual_review/backend/logic/quarantine.py
@@ -40,9 +40,9 @@ def list_quarantined_identifiers(
return list(qs.order_by("-created_at"))
-def expiry_soon_cutoff(now: datetime) -> datetime:
+def expiry_soon_cutoff(now: datetime, within_days: int = FLAKINESS_EXPIRY_SOON_DAYS) -> datetime:
"""The moment past which an expiry is close enough that somebody has to decide about it."""
- return now + timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS)
+ return now + timedelta(days=within_days)
def is_expiring_soon(entry: QuarantinedIdentifier, cutoff: datetime) -> bool:
@@ -54,14 +54,18 @@ def is_expiring_soon(entry: QuarantinedIdentifier, cutoff: datetime) -> bool:
return entry.expires_at is not None and entry.expires_at <= cutoff
-def list_expiring_quarantines(repo_id: UUID, *, now: datetime) -> list[QuarantinedIdentifier]:
+def list_expiring_quarantines(
+ repo_id: UUID, *, now: datetime, within_days: int = FLAKINESS_EXPIRY_SOON_DAYS
+) -> list[QuarantinedIdentifier]:
"""Active quarantines that run out inside the window, soonest first.
An entry leaves this list when somebody extends it past the window, lifts it, or lets it lapse.
+ A caller that reads this on a schedule widens `within_days`, so an entry cannot expire in the
+ gap between two of its runs.
"""
return list(
QuarantinedIdentifier.objects.using(READER_DB)
- .filter(repo_id=repo_id, expires_at__gt=now, expires_at__lte=expiry_soon_cutoff(now))
+ .filter(repo_id=repo_id, expires_at__gt=now, expires_at__lte=expiry_soon_cutoff(now, within_days))
# Preload `source_run` so the caller can render the "what was wrong" link without an extra
# fetch per row. `Run.metadata` (JSONField) and `Run.error_message` (TextField) can be
# large and aren't needed for the summary.
diff --git a/products/visual_review/backend/logic/story_index.py b/products/visual_review/backend/logic/story_index.py
index 0cab9088c625..bbd247b75c0c 100644
--- a/products/visual_review/backend/logic/story_index.py
+++ b/products/visual_review/backend/logic/story_index.py
@@ -48,7 +48,10 @@ _ZIP_TIMEOUT_SECONDS = 60
# rather than made the worker's problem.
_MAX_ARTIFACT_BYTES = 512 * 1024 * 1024
_MAX_INDEX_BYTES = 32 * 1024 * 1024
-_CACHE_TTL_SECONDS = 2 * 24 * 60 * 60
+# 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
@frozen
@@ -182,6 +185,9 @@ def fetch_story_index(repo: Repo, github_run_id: str) -> StoryIndex | None:
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)
try:
diff --git a/products/visual_review/backend/presentation/serializers.py b/products/visual_review/backend/presentation/serializers.py
index ed694d4e0a4b..c0a9c7de2646 100644
--- a/products/visual_review/backend/presentation/serializers.py
+++ b/products/visual_review/backend/presentation/serializers.py
@@ -214,7 +214,7 @@ class UpdateRepoInputSerializer(DataclassSerializer):
"debt_digest_enabled": {
"help_text": (
"Post the visual review debt digest to the Slack channels of the teams that own the "
- "snapshots. Off by default. The digest runs each weekday morning."
+ "snapshots. Off by default. The digest goes out every Monday morning."
)
},
}
diff --git a/products/visual_review/backend/tasks/tasks.py b/products/visual_review/backend/tasks/tasks.py
index 1da746e2a559..5e7b0ebf3a5e 100644
--- a/products/visual_review/backend/tasks/tasks.py
+++ b/products/visual_review/backend/tasks/tasks.py
@@ -13,6 +13,7 @@ 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
@@ -231,8 +232,9 @@ def sweep_visual_review_retention() -> None:
def send_visual_review_debt_digests() -> None:
"""Fan out to every repo, one task each.
- One repo's failure must not stop the rest, and nothing is stored about what was sent, so the
- next morning's run recomputes and resends whatever is still owed.
+ 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
+ Monday's run recomputes and resends whatever is still owed.
"""
from ..logic import debt_digest # noqa: PLC0415 — avoids the logic/tasks circular import
@@ -248,7 +250,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.
+ """Post one repo's digest on the posting day, and only warm its story index on the other days.
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.
@@ -264,4 +266,8 @@ def send_visual_review_debt_digest(team_id: int, repo_id: str) -> None:
if repo is 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 d91fc37aa6e6..ede6ccd0711a 100644
--- a/products/visual_review/backend/tests/logic/test_debt_digest.py
+++ b/products/visual_review/backend/tests/logic/test_debt_digest.py
@@ -1,6 +1,6 @@
-"""Unit tests for logic/debt_digest.py — the daily visual review debt reminder."""
+"""Unit tests for logic/debt_digest.py — the weekly visual review debt reminder."""
-from datetime import timedelta
+from datetime import UTC, datetime, timedelta
import pytest
from unittest.mock import MagicMock, patch
@@ -11,7 +11,13 @@ from django.utils import timezone
from posthog_owners.schema import TeamEntry
from posthog.models.team.team import Team
-from posthog.team_notifications.slack import MAX_SECTION_CHARS, SlackChannel, SlackPostRefused
+from posthog.team_notifications.slack import (
+ MAX_BLOCKS,
+ MAX_SECTION_CHARS,
+ MAX_TEXT_CHARS,
+ SlackChannel,
+ SlackPostRefused,
+)
from products.engineering_analytics.backend.facade.contracts import UNOWNED_TEAM, PathOwnership
from products.visual_review.backend.facade.contracts import (
@@ -28,10 +34,16 @@ _PRODUCT_PATH = "products/visual_review/"
_SOURCE_PATH = "frontend/src/scenes/Button.stories.tsx"
_STORY_ID = "scenes-app-button--primary"
_IDENTIFIER = f"{_STORY_ID}--light"
+_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.
+_MONDAY = datetime(2026, 9, 14, 7, 30, tzinfo=UTC)
+
_PLACED = debt_digest.Attribution(kind=debt_digest.AttributionKind.PLACED, source_path=_SOURCE_PATH)
_STORY_ABSENT = debt_digest.Attribution(kind=debt_digest.AttributionKind.STORY_ABSENT)
_UNAVAILABLE = debt_digest.Attribution(
@@ -44,30 +56,212 @@ def _ownership(team_by_path: dict[str, str], registry: dict[str, TeamEntry] | No
return PathOwnership(team_by_path=team_by_path, registry=registry or {}, resolved=True)
+def _repo() -> MagicMock:
+ return MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")
+
+
def _item(
- attribution: debt_digest.Attribution, identifier: str = _IDENTIFIER, line: str = "a line"
+ attribution: debt_digest.Attribution,
+ identifier: str = _IDENTIFIER,
+ line: str = "a line",
+ facts: str = "*3* accepted variants of the current baseline",
) -> debt_digest.DebtItem:
- return debt_digest.DebtItem(identifier=identifier, run_type="storybook", attribution=attribution, line=line)
+ return debt_digest.DebtItem(
+ identifier=identifier, run_type="storybook", attribution=attribution, line=line, facts=facts
+ )
+
+
+def _team_digest(expiring: int = 0, pileups: int = 0, team_slug: str = "team-devex") -> debt_digest.TeamDigest:
+ return debt_digest.TeamDigest(
+ team_slug=team_slug,
+ expiring_quarantines=[_item(_PLACED)] * expiring,
+ variant_pileups=[_item(_PLACED)] * pileups,
+ )
+
+
+def _maintainers_digest(*groups: debt_digest.TriageGroup) -> debt_digest.MaintainersDigest:
+ 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 _digest(team_slug: str = "team-devex") -> debt_digest.TeamDigest:
- return debt_digest.TeamDigest(team_slug=team_slug, expiring_quarantines=[_item(_PLACED)], variant_pileups=[])
+def _section_texts(message: debt_digest.SlackMessage) -> list[str]:
+ return [block["text"]["text"] for block in message.blocks if block["type"] == "section" and "text" in block]
-def _triage_digest() -> debt_digest.TeamDigest:
- return debt_digest.TeamDigest(
- team_slug="team-devex",
- expiring_quarantines=[],
- variant_pileups=[],
- triage=[
- debt_digest.TriageGroup(kind=debt_digest.AttributionKind.PLACED, items=[_item(_PLACED)]),
- debt_digest.TriageGroup(kind=debt_digest.AttributionKind.UNAVAILABLE, items=[_item(_UNAVAILABLE)]),
+def _buttons(message: debt_digest.SlackMessage) -> list[dict]:
+ accessories = [block["accessory"] for block in message.blocks if "accessory" in block]
+ rows = [element for block in message.blocks if block["type"] == "actions" for element in block["elements"]]
+ return [*accessories, *rows]
+
+
+def _all_buttons(messages: list[debt_digest.SlackMessage]) -> list[dict]:
+ return [button for message in messages for button in _buttons(message)]
+
+
+class TestLead:
+ @pytest.mark.parametrize(
+ "expiring,pileups,fields",
+ [
+ (1, 0, ["*1 quarantine* expires soon", "*0 snapshots* with piled-up variants"]),
+ (0, 2, ["*0 quarantines* expire soon", "*2 snapshots* with piled-up variants"]),
+ (3, 1, ["*3 quarantines* expire soon", "*1 snapshot* with piled-up variants"]),
+ ],
+ )
+ def test_the_lead_names_the_team_and_counts_both_conditions(
+ self, expiring: int, pileups: int, fields: list[str]
+ ) -> None:
+ message = debt_digest.lead_message(_repo(), _team_digest(expiring, pileups), _MONDAY)
+
+ assert message.blocks[0]["type"] == "header"
+ assert message.blocks[0]["text"]["text"] == "Visual review debt for team-devex"
+ assert [field["text"] for field in message.blocks[2]["fields"]] == fields
+ assert "week of Sep 14" in message.blocks[1]["elements"][0]["text"]
+
+ def test_the_lead_links_to_the_two_pages_the_counts_come_from(self) -> None:
+ 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"),
+ ("Open snapshots", f"{settings.SITE_URL}/project/7/visual_review/repos/abc/snapshots"),
+ ]
+
+ def test_the_fallback_text_says_what_the_blocks_say(self) -> None:
+ message = debt_digest.lead_message(_repo(), _team_digest(expiring=1, pileups=2), _MONDAY)
+
+ assert message.text == (
+ "Visual review debt for team-devex in PostHog/posthog: 1 quarantine expires soon, "
+ "2 snapshots with piled-up variants."
+ )
+
+
+class TestThreadReplies:
+ @pytest.mark.parametrize(
+ "expiring,pileups,headings",
+ [
+ (1, 0, ["*Quarantines expiring soon*"]),
+ (0, 1, ["*Snapshots with piled-up variants*"]),
+ (2, 2, ["*Quarantines expiring soon*", "*Snapshots with piled-up variants*"]),
],
)
+ def test_one_reply_per_condition_that_has_items(self, expiring: int, pileups: int, headings: list[str]) -> None:
+ messages = debt_digest.thread_messages(_repo(), _team_digest(expiring, pileups), _MONDAY)
+
+ assert [_section_texts(message)[0].split("\n")[0] for message in messages] == headings
+
+ def test_every_item_carries_the_one_button_that_resolves_it(self) -> None:
+ messages = debt_digest.thread_messages(_repo(), _team_digest(expiring=1, pileups=1), _MONDAY)
+
+ buttons = _all_buttons(messages)
+ assert [button["text"]["text"] for button in buttons] == ["Extend or fix", "Reset baseline"]
+ assert all(
+ button["url"] == f"{settings.SITE_URL}/project/7/visual_review/repos/abc/storybook/snapshots/{_IDENTIFIER}"
+ for button in buttons
+ )
+
+ def test_a_button_url_too_long_for_slack_points_at_the_repo_list(self) -> None:
+ # Each of these percent-encodes to nine characters, so the URL alone outgrows the button.
+ digest = debt_digest.TeamDigest(
+ team_slug="team-devex", expiring_quarantines=[], variant_pileups=[_item(_PLACED, identifier="界" * 400)]
+ )
+
+ messages = debt_digest.thread_messages(_repo(), digest, _MONDAY)
+
+ assert _all_buttons(messages)[0]["url"] == f"{settings.SITE_URL}/project/7/visual_review/repos/abc/snapshots"
+
+ def test_the_last_reply_says_when_the_next_digest_comes(self) -> None:
+ messages = debt_digest.thread_messages(_repo(), _team_digest(expiring=1, pileups=1), _MONDAY)
+
+ assert messages[0].blocks[-1]["type"] == "section"
+ assert messages[-1].blocks[-2]["type"] == "divider"
+ assert messages[-1].blocks[-1]["elements"][0]["text"].startswith("Next digest Monday, Sep 21.")
+ assert "notifications: {visual_review: false}" in messages[-1].text
+
+ def test_a_group_over_the_block_limit_splits_and_repeats_its_heading(self) -> None:
+ items = [_item(_PLACED)] * (debt_digest._ITEMS_PER_MESSAGE + 1)
+ digest = debt_digest.TeamDigest(team_slug="team-devex", expiring_quarantines=items, variant_pileups=[])
+
+ messages = debt_digest.thread_messages(_repo(), digest, _MONDAY)
+
+ assert len(messages) == 2
+ assert all(len(message.blocks) <= MAX_BLOCKS for message in messages)
+ assert all(_section_texts(message)[0].startswith("*Quarantines expiring soon*") for message in messages)
+ # Every item is carried once, under a heading that says what the reader is looking at.
+ assert sum(len(_section_texts(message)) - 1 for message in messages) == len(items)
+
+ def test_the_fallback_of_a_full_message_stays_under_the_slack_cap(self) -> None:
+ items = [_item(_PLACED, line="x" * debt_digest._MAX_LINE_CHARS)] * debt_digest._ITEMS_PER_MESSAGE
+ digest = debt_digest.TeamDigest(team_slug="team-devex", expiring_quarantines=items, variant_pileups=[])
+
+ messages = debt_digest.thread_messages(_repo(), digest, _MONDAY)
+
+ assert len(items) * debt_digest._MAX_LINE_CHARS > MAX_TEXT_CHARS
+ assert len(messages) == 1
+ assert len(messages[0].text) <= MAX_TEXT_CHARS
+
+
+class TestMaintainersMessage:
+ def test_it_lists_each_unowned_reason_with_the_action_it_asks_for(self) -> None:
+ digest = _maintainers_digest(
+ debt_digest.TriageGroup(kind=debt_digest.AttributionKind.PLACED, items=[_item(_PLACED)]),
+ debt_digest.TriageGroup(
+ kind=debt_digest.AttributionKind.STORY_ABSENT,
+ items=[_item(_STORY_ABSENT, identifier=_ABSENT_IDENTIFIER)],
+ ),
+ )
+
+ messages = debt_digest.maintainers_messages(_repo(), digest)
+
+ assert messages[0].blocks[0]["text"]["text"] == "Unowned visual review debt in PostHog/posthog"
+ assert messages[0].blocks[1]["elements"][0]["text"].startswith("2 items nobody owns yet")
+ assert [(button["text"]["text"], button["url"]) for button in _all_buttons(messages)] == [
+ ("Open file", f"https://github.com/PostHog/posthog/blob/HEAD/{_SOURCE_PATH}"),
+ (
+ "Open snapshot",
+ f"{settings.SITE_URL}/project/7/visual_review/repos/abc/storybook/snapshots/{_ABSENT_IDENTIFIER}",
+ ),
+ ]
+ # The path stays readable in the message, because it is what somebody types into owners.yaml.
+ assert f"`{_SOURCE_PATH}`" in _section_texts(messages[0])[1]
+
+ @pytest.mark.parametrize("kinds", [(), (debt_digest.AttributionKind.UNAVAILABLE,)])
+ def test_nothing_is_sent_when_no_item_asks_anybody_to_act(self, kinds: tuple) -> None:
+ digest = _maintainers_digest(
+ *(debt_digest.TriageGroup(kind=kind, items=[_item(_UNAVAILABLE)]) for kind in kinds)
+ )
+
+ assert debt_digest.maintainers_messages(_repo(), digest) == []
+
+ def test_a_file_button_too_long_for_slack_is_left_out(self) -> None:
+ # Each of these percent-encodes to nine characters, so the file URL outgrows the button cap
+ # on its own, and Slack refuses a whole message over one oversized button.
+ path = f"frontend/src/scenes/{'界' * 400}.stories.tsx"
+ item = _item(debt_digest.Attribution(kind=debt_digest.AttributionKind.PLACED, source_path=path))
+ digest = _maintainers_digest(debt_digest.TriageGroup(kind=debt_digest.AttributionKind.PLACED, items=[item]))
+
+ messages = debt_digest.maintainers_messages(_repo(), digest)
+
+ assert _all_buttons(messages) == []
+ # The path is what somebody types into owners.yaml, so losing the link costs nothing else.
+ assert path in _section_texts(messages[0])[1]
+
+ def test_an_unreadable_index_is_counted_in_the_footer_and_never_listed(self) -> None:
+ digest = _maintainers_digest(
+ debt_digest.TriageGroup(kind=debt_digest.AttributionKind.PLACED, items=[_item(_PLACED)]),
+ debt_digest.TriageGroup(
+ kind=debt_digest.AttributionKind.UNAVAILABLE,
+ items=[_item(_UNAVAILABLE, identifier="scenes-app-unreadable--light")],
+ ),
+ )
+
+ messages = debt_digest.maintainers_messages(_repo(), digest)
+
+ assert messages[-1].blocks[-1]["elements"][0]["text"] == (
+ "1 item with no readable Storybook index this week is not listed. Ownership is read again next Monday."
+ )
+ assert all("scenes-app-unreadable--light" not in str(message.blocks) for message in messages)
class TestRendering:
@@ -79,24 +273,38 @@ class TestRendering:
identifier="Button<!channel>",
run_type=run_type,
reason="flaky & <!here>",
- expires_at=timezone.now() + timedelta(days=3),
+ expires_at=_MONDAY + timedelta(days=3),
created_by_id=None,
)
- repo = MagicMock(id="00000000-0000-0000-0000-000000000001", team_id=7, repo_full_name="PostHog/posthog")
+ repo = _repo()
- line = debt_digest._quarantine_line(repo, entry, {}, timezone.now())
- pileup = debt_digest._pileup_line(repo, run_type, "Button", 4)
+ line = debt_digest._quarantine_line(repo, entry, {}, _MONDAY)
+ facts = debt_digest._quarantine_facts(entry, {}, _MONDAY)
+ item = _item(_PLACED, identifier="Button<!channel>", line=line, facts=facts)
+ digest = debt_digest.TeamDigest(team_slug="team-devex", expiring_quarantines=[item], variant_pileups=[])
+ rendered = str(debt_digest.thread_messages(repo, digest, _MONDAY)[0])
- assert "<!channel>" not in line
- assert "<!channel>" not in pileup
- assert "<!here>" not in line
- assert "&lt;!channel&gt;" in line
- assert "flaky &amp; &lt;!here&gt;" in line
+ assert "<!channel>" not in rendered
+ assert "<!here>" not in rendered
+ assert "&lt;!channel&gt;" in rendered
+ assert "flaky &amp; &lt;!here&gt;" in rendered
- def test_links_to_the_snapshot_page_with_encoded_segments(self) -> None:
- repo = MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")
+ @pytest.mark.parametrize(
+ "expires_in,expected",
+ [
+ (timedelta(hours=2), "today"),
+ (timedelta(days=2), "Wednesday"),
+ (timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS), "Sep 21"),
+ ],
+ )
+ def test_an_expiry_reads_as_a_day_the_reader_can_plan_around(self, expires_in: timedelta, expected: str) -> None:
+ # A weekday name seven days out names the day the reader is reading on, so that one dates itself.
+ entry = MagicMock(reason="flaky", expires_at=_MONDAY + expires_in, created_by_id=None)
- line = debt_digest._pileup_line(repo, "storybook", "scenes/Button--dark", 4)
+ assert debt_digest._quarantine_facts(entry, {}, _MONDAY).startswith(f"Expires *{expected}*")
+
+ def test_links_to_the_snapshot_page_with_encoded_segments(self) -> None:
+ line = debt_digest._pileup_line(_repo(), "storybook", "scenes/Button--dark", 4)
assert line.startswith("4 accepted variants of the current baseline · scenes/Button--dark (storybook)")
assert line.endswith("/project/7/visual_review/repos/abc/storybook/snapshots/scenes%2FButton--dark")
@@ -113,60 +321,24 @@ class TestRendering:
def test_one_oversized_item_still_fits_a_slack_block(
self, identifier: str, reason: str, links_to_the_snapshot: bool
) -> None:
- repo = MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")
+ repo = _repo()
entry = MagicMock(
identifier=identifier,
run_type="storybook",
reason=reason,
- expires_at=timezone.now() + timedelta(days=3),
+ expires_at=_MONDAY + timedelta(days=3),
created_by_id=None,
)
+ line = debt_digest._quarantine_line(repo, entry, {}, _MONDAY)
+ item = _item(_PLACED, identifier=identifier, line=line, facts=debt_digest._quarantine_facts(entry, {}, _MONDAY))
+ digest = debt_digest.TeamDigest(team_slug="team-devex", expiring_quarantines=[item] * 2, variant_pileups=[])
- line = debt_digest._quarantine_line(repo, entry, {}, timezone.now())
- texts = debt_digest.thread_texts(
- debt_digest.TeamDigest(
- team_slug="team-devex",
- expiring_quarantines=[_item(_PLACED, identifier=identifier, line=line)] * 2,
- variant_pileups=[],
- )
- )
+ messages = debt_digest.thread_messages(repo, digest, _MONDAY)
assert len(line) <= debt_digest._MAX_LINE_CHARS
assert settings.SITE_URL in line
assert ("/snapshots/" in line) == links_to_the_snapshot
- assert all(len(text) <= MAX_SECTION_CHARS for text in texts)
-
- def test_splits_the_thread_when_one_group_runs_long(self) -> None:
- long_item = _item(_PLACED, line="x" * 2000)
- digest = debt_digest.TeamDigest(
- team_slug="team-devex", expiring_quarantines=[long_item, long_item], variant_pileups=[]
- )
-
- texts = debt_digest.thread_texts(digest)
-
- assert len(texts) > 1
- assert all(len(text) <= MAX_SECTION_CHARS for text in texts)
- assert texts[-1].endswith(debt_digest._FOOTER)
-
- def test_the_lead_holds_triage_apart_from_what_the_team_owns(self) -> None:
- repo = MagicMock(id="abc", team_id=7, repo_full_name="PostHog/posthog")
-
- lead = debt_digest.lead_text(_triage_digest(), repo)
-
- assert "nothing this team owns today" in lead
- assert "2 in triage that nobody owns yet" in lead
- # An artifact that could not be read must never read as "nobody owns this".
- assert f"the Storybook build artifact for run {_GITHUB_RUN_ID} was not read" in lead
- assert "tries again tomorrow" in lead
-
- def test_the_thread_groups_triage_under_one_header_per_reason(self) -> None:
- thread = "\n".join(debt_digest.thread_texts(_triage_digest()))
-
- assert debt_digest._TRIAGE_HEADERS[debt_digest.AttributionKind.PLACED] in thread
- assert debt_digest._TRIAGE_HEADERS[debt_digest.AttributionKind.UNAVAILABLE] in thread
- # The path stays on the line, because it is what an owners entry is written for.
- assert f"a line · {_SOURCE_PATH}" in thread
- assert f"a line · the Storybook build artifact for run {_GITHUB_RUN_ID} was not read" in thread
+ assert all(len(text) <= MAX_SECTION_CHARS for message in messages for text in _section_texts(message))
class TestSplitByTeam:
@@ -179,14 +351,14 @@ class TestSplitByTeam:
debt, _ownership({_SOURCE_PATH: "team-product-analytics", _PRODUCT_PATH: "team-devex"})
)
- by_slug = {d.team_slug: d for d in digests}
- assert set(by_slug) == {"team-product-analytics", "team-devex"}
- assert by_slug["team-product-analytics"].expiring_quarantines == [placed]
- # The maintainers hold the other item without it counting as debt of their own.
- assert by_slug["team-devex"].variant_pileups == []
- assert by_slug["team-devex"].triage == [
- debt_digest.TriageGroup(kind=debt_digest.AttributionKind.STORY_ABSENT, items=[absent])
- ]
+ # The maintainers hold the other item without it counting as debt of their own, so they get
+ # no digest of their own here.
+ assert [digest.team_slug for digest in digests.teams] == ["team-product-analytics"]
+ assert digests.teams[0].expiring_quarantines == [placed]
+ assert digests.maintainers == debt_digest.MaintainersDigest(
+ team_slug="team-devex",
+ groups=[debt_digest.TriageGroup(kind=debt_digest.AttributionKind.STORY_ABSENT, items=[absent])],
+ )
@pytest.mark.parametrize("attribution", [_PLACED, _STORY_ABSENT, _UNAVAILABLE])
def test_keeps_the_three_unowned_outcomes_apart(self, attribution: debt_digest.Attribution) -> None:
@@ -195,14 +367,14 @@ class TestSplitByTeam:
digests = debt_digest.split_by_team(debt, _ownership({_PRODUCT_PATH: "team-devex"}))
- assert [d.team_slug for d in digests] == ["team-devex"]
- assert digests[0].expiring_quarantines == []
- assert digests[0].triage == [debt_digest.TriageGroup(kind=attribution.kind, items=[item])]
+ assert digests.teams == []
+ assert digests.maintainers is not None
+ assert digests.maintainers.groups == [debt_digest.TriageGroup(kind=attribution.kind, items=[item])]
def test_drops_an_item_nobody_owns(self) -> None:
debt = debt_digest.RepoDebt(expiring_quarantines=[_item(_STORY_ABSENT)], variant_pileups=[])
- assert debt_digest.split_by_team(debt, _ownership({})) == []
+ assert debt_digest.split_by_team(debt, _ownership({})) == debt_digest.RepoDigests(teams=[], maintainers=None)
class TestRouting:
@@ -214,11 +386,11 @@ class TestRouting:
def test_a_team_that_opted_out_is_skipped(self) -> None:
registry = {"team-devex": TeamEntry(notifications={"visual_review": False})}
- assert debt_digest.resolve_channel(_digest(), registry, self._CHANNELS) is None
+ assert debt_digest.resolve_channel("team-devex", registry, self._CHANNELS) is None
def test_a_shared_channel_is_refused(self) -> None:
# A name match onto a shared channel would send an internal reminder out of the workspace.
- assert debt_digest.resolve_channel(_digest("team-shared"), {}, self._CHANNELS) is None
+ assert debt_digest.resolve_channel("team-shared", {}, self._CHANNELS) is None
@pytest.mark.parametrize("mode", ["preveiw", "shadow", ""])
def test_an_unknown_mode_evaluates_nothing_and_posts_nothing(self, mode: str) -> None:
@@ -356,6 +528,33 @@ class TestCollectAndSend:
assert [item.identifier for item in debt.expiring_quarantines] == expected_expiring
assert debt.variant_pileups == []
+ @pytest.mark.parametrize(
+ "expires_in,expected",
+ [
+ (timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS, hours=1), [_ABSENT_IDENTIFIER]),
+ (timedelta(days=FLAKINESS_EXPIRY_SOON_DAYS + 2), []),
+ ],
+ )
+ def test_the_expiry_window_overlaps_so_two_weekly_runs_cannot_skip_one(
+ self, repo, team, user, expires_in, expected
+ ):
+ # Two runs a week apart can fall slightly more than seven days apart, and a quarantine
+ # expiring in that gap would lapse without anybody being told.
+ now = timezone.now()
+ quarantine.quarantine_identifier(
+ repo_id=repo.id,
+ identifier=_ABSENT_IDENTIFIER,
+ run_type=RunType.STORYBOOK,
+ reason="non-deterministic",
+ user_id=user.id,
+ team_id=team.id,
+ expires_at=now + expires_in,
+ )
+
+ debt = debt_digest.collect_debt(repo, now)
+
+ assert [item.identifier for item in debt.expiring_quarantines] == expected
+
def test_preview_renders_every_team_and_posts_nothing(self, repo, mocker):
self._completed_run(repo, mocker)
self._pile_up(repo)
@@ -373,7 +572,10 @@ class TestCollectAndSend:
assert post.call_count == 0
assert channel_map.call_count == 0
assert len(rendered) == 1
+ # Preview prints the plain text behind every message, so a by-hand run reads without Slack.
assert rendered[0].startswith("Visual review debt for team-devex in org/test-debt: ")
+ assert "3 accepted variants of the current baseline" in rendered[0]
+ assert rendered[0].rstrip().endswith("under your team in owners.yaml.")
def test_an_unreadable_owners_file_sends_nothing(self, repo, mocker):
self._completed_run(repo, mocker)
@@ -393,14 +595,15 @@ class TestCollectAndSend:
assert post.call_count == 0
def test_one_team_failing_does_not_stop_the_next(self, repo, mocker):
- self._completed_run(repo, mocker, (_IDENTIFIER, _ABSENT_IDENTIFIER))
+ self._completed_run(repo, mocker, (_IDENTIFIER, _OTHER_IDENTIFIER))
self._pile_up(repo)
- self._pile_up(repo, identifier=_ABSENT_IDENTIFIER)
+ self._pile_up(repo, identifier=_OTHER_IDENTIFIER)
+ index = story_index.StoryIndex(path_by_story_id={_STORY_ID: _SOURCE_PATH, _OTHER_STORY_ID: _OTHER_PATH})
with (
- _with_index(_INDEX),
+ _with_index(index),
patch(
"products.visual_review.backend.logic.debt_digest.resolve_path_owners",
- return_value=_ownership({_SOURCE_PATH: "team-one", _PRODUCT_PATH: "team-two"}),
+ return_value=_ownership({_SOURCE_PATH: "team-one", _OTHER_PATH: "team-two", _PRODUCT_PATH: "team-two"}),
),
patch("products.visual_review.backend.logic.debt_digest.Integration") as integration,
patch("products.visual_review.backend.logic.debt_digest.SlackIntegration"),
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 b5f334a2f3c0..7f4e9a6ce932 100644
--- a/products/visual_review/backend/tests/logic/test_story_index.py
+++ b/products/visual_review/backend/tests/logic/test_story_index.py
@@ -3,9 +3,11 @@
import io
import json
import zipfile
+from datetime import UTC, datetime, timedelta
from uuid import uuid4
import pytest
+import time_machine
from unittest.mock import MagicMock, patch
import requests
@@ -110,6 +112,31 @@ class TestFetchStoryIndex:
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"}})}
+ )
+ 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
+ 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,
+ ):
+ 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")
+
+ assert index is not None
+ assert request.call_count == 2
+
@pytest.mark.parametrize(
"responses",
[
diff --git a/products/visual_review/backend/tests/test_tasks.py b/products/visual_review/backend/tests/test_tasks.py
index 316e5064f94e..94f32f73f33b 100644
--- a/products/visual_review/backend/tests/test_tasks.py
+++ b/products/visual_review/backend/tests/test_tasks.py
@@ -2,8 +2,10 @@
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
@@ -584,12 +586,29 @@ 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}
- def test_the_scheduled_run_posts_rather_than_previews(self) -> None:
+ @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:
repo = Repo.objects.create(team_id=self.team.id, repo_external_id=55512, repo_full_name="org/scheduled")
try:
- with patch("products.visual_review.backend.logic.debt_digest.send_debt_digest") as send:
+ 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,
+ ):
send_visual_review_debt_digest(self.team.id, str(repo.id))
finally:
cache.delete(f"visual_review_debt_digest:{repo.id}")
- assert send.call_args.kwargs["mode"] == debt_digest.MODE_LIVE
+ 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
diff --git a/products/visual_review/frontend/generated/api.schemas.ts b/products/visual_review/frontend/generated/api.schemas.ts
index ac77f581bcc2..11dc5d94f5b5 100644
--- a/products/visual_review/frontend/generated/api.schemas.ts
+++ b/products/visual_review/frontend/generated/api.schemas.ts
@@ -49,7 +49,7 @@ export interface PatchedUpdateRepoRequestInputApi {
*/
enable_pr_comments?: boolean | null
/**
- * Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest runs each weekday morning.
+ * Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest goes out every Monday morning.
* @nullable
*/
debt_digest_enabled?: boolean | null
diff --git a/products/visual_review/frontend/generated/api.zod.ts b/products/visual_review/frontend/generated/api.zod.ts
index 9b3eedbe3068..70383d4385ac 100644
--- a/products/visual_review/frontend/generated/api.zod.ts
+++ b/products/visual_review/frontend/generated/api.zod.ts
@@ -30,7 +30,7 @@ export const VisualReviewReposPartialUpdateBody = /* @__PURE__ */ zod.object({
.boolean()
.nullish()
.describe(
- 'Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest runs each weekday morning.'
+ 'Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest goes out every Monday morning.'
),
})
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 32ef58c141c1..0d78bed79b29 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -70970,7 +70970,7 @@ export namespace Schemas {
*/
enable_pr_comments?: boolean | null;
/**
- * Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest runs each weekday morning.
+ * Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest goes out every Monday morning.
* @nullable
*/
debt_digest_enabled?: boolean | null;
diff --git a/services/mcp/src/generated/visual_review/api.ts b/services/mcp/src/generated/visual_review/api.ts
index 4525871eb812..3b56956ee3f3 100644
--- a/services/mcp/src/generated/visual_review/api.ts
+++ b/services/mcp/src/generated/visual_review/api.ts
@@ -58,7 +58,7 @@ export const VisualReviewReposPartialUpdateBody = () => zod.object({
.boolean()
.nullish()
.describe(
- 'Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest runs each weekday morning.'
+ 'Post the visual review debt digest to the Slack channels of the teams that own the snapshots. Off by default. The digest goes out every Monday morning.'
),
})