:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(signals): render report charts as images in Slack delivery (#84071)
Andrew Maguire0ac72c63cddb
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.pyindex a4132cf96275..bd5a0f3f8eeb 100644--- a/posthog/settings/__init__.py+++ b/posthog/settings/__init__.py@@ -49,6 +49,7 @@ from posthog.settings.data_warehouse import *from posthog.settings.managed_migrations import *from posthog.settings.session_replay import *from posthog.settings.session_replay_v2 import *+from posthog.settings.signals import *from posthog.settings.integrations import *from posthog.settings.payments import *from posthog.settings.personhog import *diff --git a/posthog/settings/signals.py b/posthog/settings/signals.pynew file mode 100644index 000000000000..3d8dca459145--- /dev/null+++ b/posthog/settings/signals.py@@ -0,0 +1,13 @@+import os++from posthog.settings.base_variables import DEBUG, TEST+from posthog.settings.utils import get_list++# Signs the per-delivery map of already-rendered chart assets that scout Slack delivery keeps in the+# shared Redis, so a process able to write that Redis cannot swap in another asset id. Dedicated and+# rotatable rather than SECRET_KEY, which is fleet-wide and backs session/CSRF signing: give this+# comma-separated `new_key,old_key`, and the first key signs while every key verifies. Unset outside+# dev/test means no reuse — a retry re-renders the charts rather than trusting an unverifiable entry.+SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS: list[str] = get_list(os.getenv("SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS", ""))+if (TEST or DEBUG) and not SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS:+ SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS = ["signals-slack-chart-cache-development-key"]diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.pyindex dbdc22d8cb96..523700308bdb 100644--- a/products/exports/backend/facade/api.py+++ b/products/exports/backend/facade/api.py@@ -160,7 +160,9 @@ def _validate_adhoc_export_context(export_context: dict) -> None:raise ValueError("export_context.source must be an InsightVizNode- or DataVisualizationNode-wrapped query")-def get_delivery_image_url(*, team_id: int, asset_id: int, expiry_delta: timedelta) -> str | None:+def get_delivery_image_url(+ *, team_id: int, asset_id: int, expiry_delta: timedelta, created_by_id: int | None = None+) -> str | None:"""Mint a delivery-purposed url for one of the team's own rendered images.The token authenticates anonymously and bypasses the org's publicly-shared-resources@@ -169,10 +171,15 @@ def get_delivery_image_url(*, team_id: int, asset_id: int, expiry_delta: timedelestablished server-side; the format and team filters bound the damage if one leaks —an image url can never be turned into a CSV or XLSX download. The manager alsoexcludes assets past their TTL.++ Pass ``created_by_id`` when the ``asset_id`` comes from a store a caller cannot fully+ trust (e.g. an id read back from a shared cache): it pins the asset to the user that+ rendered it, so a substituted id belonging to another same-team user mints nothing."""- asset = ExportedAsset.objects.filter(- team_id=team_id, id=asset_id, export_format=ExportedAsset.ExportFormat.PNG- ).first()+ asset_filter = {"team_id": team_id, "id": asset_id, "export_format": ExportedAsset.ExportFormat.PNG}+ if created_by_id is not None:+ asset_filter["created_by_id"] = created_by_id+ asset = ExportedAsset.objects.filter(**asset_filter).first()if asset is None:return Nonereturn asset.get_subscription_delivery_content_url(expiry_delta=expiry_delta)@@ -184,6 +191,7 @@ def render_png_export(created_by: User,export_context: dict | None = None,insight_id: int | None = None,+ insight_short_id: str | None = None,is_system: bool = False,expires_after: datetime | None = None,) -> tuple[ExportedAsset, bytes | None]:@@ -201,19 +209,23 @@ def render_png_export(# Access control below resolves against created_by; a principal-less render would# silently skip it, so service callers must attribute the render to a real user.raise ValueError("created_by is required")- if (export_context is None) == (insight_id is None):- raise ValueError("Provide exactly one of export_context or insight_id")+ if sum(value is not None for value in (export_context, insight_id, insight_short_id)) != 1:+ raise ValueError("Provide exactly one of export_context, insight_id or insight_short_id")if export_context is not None:_validate_adhoc_export_context(export_context)+ # An ad-hoc render runs whatever query the caller supplies, so it needs the same gate as+ # running that query directly; the object-level check below covers only saved insights.if not UserAccessControl(user=created_by, team=team).check_access_level_for_resource("query", "viewer"):raise ValueError("You need query access to render this export")- if insight_id is not None:- insight = Insight.objects.filter(id=insight_id, team_id=team.id, deleted=False).first()+ if insight_id is not None or insight_short_id is not None:+ insight_filter = {"id": insight_id} if insight_id is not None else {"short_id": insight_short_id}+ insight = Insight.objects.filter(team_id=team.id, deleted=False, **insight_filter).first()# Object-level access matters here: created_by may not be allowed to view the insight.if insight is None or not UserAccessControl(user=created_by, team=team).check_access_level_for_object(insight, "viewer"):raise ValueError("Insight not found")+ insight_id = insight.idasset = ExportedAsset.objects.create(team=team,diff --git a/products/exports/backend/tests/test_facade.py b/products/exports/backend/tests/test_facade.pyindex 541c22b86628..eef22dcc1dfa 100644--- a/products/exports/backend/tests/test_facade.py+++ b/products/exports/backend/tests/test_facade.py@@ -1,10 +1,21 @@+from datetime import timedelta++from posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patchfrom django.test import SimpleTestCasefrom parameterized import parameterized-from products.exports.backend.facade.api import _validate_adhoc_export_context, render_png_export+from posthog.models.user import User++from products.exports.backend.facade.api import (+ _validate_adhoc_export_context,+ get_delivery_image_url,+ render_png_export,+)+from products.exports.backend.models.exported_asset import ExportedAsset+from products.product_analytics.backend.models.insight import Insightclass TestValidateAdhocExportContext(SimpleTestCase):@@ -42,6 +53,63 @@ class TestValidateAdhocExportContext(SimpleTestCase):_validate_adhoc_export_context(export_context)+class TestRenderPngExportInsightLookup(BaseTest):+ def _render(self, **kwargs):+ with patch("products.exports.backend.facade.api.async_to_sync") as async_to_sync:++ def _stash_content(_coro):+ def _run():+ asset = ExportedAsset.objects.get(team=self.team)+ asset.content = b"png"+ asset.save(update_fields=["content"])++ return _run++ async_to_sync.side_effect = _stash_content+ return render_png_export(team=self.team, created_by=self.user, **kwargs)++ def test_short_id_resolves_to_the_teams_insight(self):+ insight = Insight.objects.create(team=self.team, short_id="abc123xy", query={"kind": "InsightVizNode"})++ asset, png = self._render(insight_short_id=insight.short_id)++ assert asset.insight_id == insight.id+ assert png == b"png"++ @parameterized.expand(+ [+ ("unknown_short_id", {"insight_short_id": "nope0000"}),+ ("short_id_and_id", {"insight_short_id": "abc123xy", "insight_id": 1}),+ ]+ )+ def test_rejects_unresolvable_or_ambiguous_insight_selectors(self, _name, kwargs):+ with self.assertRaises(ValueError):+ render_png_export(team=self.team, created_by=self.user, **kwargs)+++class TestGetDeliveryImageUrl(BaseTest):+ def test_created_by_filter_pins_the_asset_to_its_renderer(self):+ other = User.objects.create(email="[email protected]")+ asset = ExportedAsset.objects.create(+ team=self.team,+ created_by=self.user,+ export_format=ExportedAsset.ExportFormat.PNG,+ content=b"png",+ )+ # No filter, or the matching renderer, mints a url. A mismatched renderer mints nothing, so a+ # cache id swapped for another same-team user's export can't be turned into a delivery url.+ assert get_delivery_image_url(team_id=self.team.id, asset_id=asset.id, expiry_delta=timedelta(days=1))+ assert get_delivery_image_url(+ team_id=self.team.id, asset_id=asset.id, expiry_delta=timedelta(days=1), created_by_id=self.user.id+ )+ assert (+ get_delivery_image_url(+ team_id=self.team.id, asset_id=asset.id, expiry_delta=timedelta(days=1), created_by_id=other.id+ )+ is None+ )++class TestAdhocRenderRequiresQueryAccess(SimpleTestCase):def test_a_user_without_query_access_cannot_render_an_ad_hoc_query(self):context = {diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.mdindex 4f4266e7dd2b..6d401fed5e82 100644--- a/products/signals/backend/scout_harness/AGENTS.md+++ b/products/signals/backend/scout_harness/AGENTS.md@@ -22,8 +22,12 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick eCanonical skill sync. Reads `products/signals/skills/signals-scout-*/` from disk and reconciles them against the team's `LLMSkill` rows: creates missing rows, updates ones the team hasn't edited, leaves diverged / hand-authored rows alone, tombstones rows whose canonical skill was deleted. Only rows tagged `metadata.seeded_by="signals_scout_harness"` are ever updated. Called both lazily (coordinator tick, runner cold-start) and explicitly via the `sync_signals_scout_skills` management command.- `config_registry.py``register_missing_configs(team_id)` — auto-creates an enabled, default-schedule `SignalScoutConfig` for any `signals-scout-*` skill lacking one ("author a skill, get a scout"). Called by the coordinator tick; the HTTP surface registers explicitly via the write-scoped config `create` endpoint instead (reads stay side-effect free). A canonical scout's `scout-tags` frontmatter (read through `lazy_seed.canonical_config_tags_for`) is stamped on the row it creates, which is how a product surface claims its scouts by tag instead of by hardcoded skill name — AI observability's self-driving tab lists the `ai-observability`-tagged configs. Forward-only like the rest of the seed posture: adding the key to an already-seeded scout leaves that team's existing config untagged until someone tags it through the config API.-- `slack_delivery.py` / `slack_delivery_queue.py`+- `slack_delivery.py` / `slack_delivery_queue.py` / `slack_charts.py`Best-effort direct Slack delivery for configured scout outputs. Finding emissions and surfaced report emits/edits snapshot the run config's destination after their database write commits, then enqueue the shared retrying Celery worker. Integrations are project-scoped, so a workspace connected from any environment in the project can receive the canonical parent team's scout output.+ A report message renders its `charts` through the exports facade (`render_png_export`, attributed to the run's acting user, so the insight access check applies; a system render that expires with its delivery url, so it stays out of the user's export quota and does not outlive its only reference) and appends them as `image` blocks pointing at a signed delivery url; chart links in the prose still reduce to their label. A threaded report carries its charts on the lead message, since the replies only hold the summary's tail. Only `InsightVizNode` / `SavedInsightNode` charts render, capped per report and by a render-time budget (a render only starts if it can finish inside the budget), with rendered assets remembered per delivery so a Slack retry does not re-render, and every failure is skipped rather than failing the delivery — the whole chart build is best effort, not only the render. The Slack integration row is resolved again after the build, since a workspace reconnected during the render window replaces the token on the same row.+ Slack fetches each image url itself and rejects the whole message when it cannot reach one, so a rejected message is posted again without its charts, which carry `CHART_BLOCK_ID_PREFIX` block ids to be dropped as whole units; a deployment Slack cannot reach still gets the prose and the report link.+ This path bypasses the HTTP chart-render throttle, so the cap is the guard.+ One `ChartRenderBudget` spans a delivery's initial build and any rebuild, so an edit landing mid-render cannot buy a second set of renders; only a cache miss spends one. The budget also holds the assets the delivery has rendered, so a rebuild keeps them even where the retry cache is off. That cache is written after every render (the task acks late, so a worker lost mid-delivery leaves finished renders for the retry) and signs each entry with `SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS` (comma-separated `new,old`; first signs, all verify) rather than `SECRET_KEY`; reuse is off wherever that setting is unprovisioned. A content edit made through the scout's edit tool enqueues a fresh full delivery and claims the report's latest-delivery marker before publishing to the broker, giving the claim up again if the publish fails (a claim naming a task that never runs would silence the report for the marker's whole TTL). Every full delivery yields to a marker naming another delivery, not only one that rebuilt mid-render: an edit landing before a delivery starts leaves its build nothing to rebuild, so the content is already current and it would otherwise post the edited report a second time. The marker is scoped to the destination as well as the report, since two scouts editing one report into different channels are not competing. A note-only delivery carries its own note rather than report content and is never marked, so it never yields.- `tools/`Implementations of the four harness-internal tools the agent calls during a run.The effective toolset for a run is the intersection of the skill's `allowed_tools` list with what `tools/__init__.py` re-exports — there is no separate registry module today.diff --git a/products/signals/backend/scout_harness/slack_charts.py b/products/signals/backend/scout_harness/slack_charts.pynew file mode 100644index 000000000000..423dbb4f8273--- /dev/null+++ b/products/signals/backend/scout_harness/slack_charts.py@@ -0,0 +1,357 @@+from __future__ import annotations++import re+import hmac+import json+import hashlib+from collections.abc import Callable+from dataclasses import field+from datetime import timedelta+from time import monotonic++from django.conf import settings+from django.utils import timezone++import structlog++from posthog.dataclasses import frozen+from posthog.models import Team, User+from posthog.query_creator_access import creator_access_revoked+from posthog.redis import get_client++from products.signals.backend.models import SignalReport, SignalScoutRun+from products.signals.backend.slack_formatting import escape_slack_mrkdwn++logger = structlog.get_logger(__name__)++# Each render can hold the Celery worker for the facade's RENDER_TIMEOUT, and the delivery task+# retries the whole message on transient failure, so both the count and the total time are bounded.+# A render only starts if it can finish inside the budget, so the budget is the worst case, not the+# point after which no more start. Charts past either bound still show in the inbox; the Slack+# message just links there.+MAX_SLACK_REPORT_CHARTS = 3+SLACK_REPORT_CHART_RENDER_BUDGET_SECONDS = 240++# Slack re-fetches image_url after the message is posted, so the token has to outlive the post+# by a comfortable margin; matches what task-run chart delivery uses.+SLACK_REPORT_CHART_URL_TTL = timedelta(days=30)++# The delivery task retries the whole message when Slack fails, and its backoff can span hours.+# Rendered asset ids are remembered per delivery for longer than that, so a retry re-posts the+# same PNGs instead of launching every export workflow again. Entries are keyed by chart id plus a+# fingerprint of the query, since an edit may swap a chart's query under the same id.+_RENDERED_ASSETS_CACHE_TTL_SECONDS = 24 * 60 * 60++# The exporter renders an InsightVizNode-wrapped query; a SavedInsightNode is rendered through the+# insight it points at. DataVisualizationNode (SQL) has no PNG render path yet, so it is left to+# the inbox.+_RENDERABLE_CHART_KINDS = frozenset({"InsightVizNode", "SavedInsightNode"})++# Every block a chart contributes carries a block id under this prefix, so a delivery Slack rejects+# can drop the charts as whole units — title, image, and caption — and post the prose it can accept.+CHART_BLOCK_ID_PREFIX = "signals-scout-chart:"++# The chart ids the summary points at, in the order the prose reaches them. Deliberately looser+# than the inbox's link parse: this only decides which charts go first when the cap bites, and+# a false positive costs nothing more than ordering.+_CHART_REF_ID_RE = re.compile(r"chart:([a-z0-9][a-z0-9_-]*)")+++def _referenced_chart_ids(summary: str) -> list[str]:+ seen: dict[str, None] = {}+ for match in _CHART_REF_ID_RE.finditer(summary):+ seen.setdefault(match.group(1), None)+ return list(seen)+++def _ordered_charts(report: SignalReport) -> list[dict]:+ charts = [chart for chart in (report.charts or []) if isinstance(chart, dict)]+ by_id = {chart.get("chart_id"): chart for chart in charts if isinstance(chart.get("chart_id"), str)}+ referenced = [by_id[chart_id] for chart_id in _referenced_chart_ids(report.summary or "") if chart_id in by_id]+ referenced_ids = {chart["chart_id"] for chart in referenced}+ unreferenced = [chart for chart in charts if chart.get("chart_id") not in referenced_ids]+ return referenced + unreferenced+++def _render_chart_asset_id(*, team: Team, created_by: User, query: dict) -> int | None:+ # The exports facade drags temporalio and the query schema in with it, and the signals app's+ # startup wiring reaches this module, so the facade stays off the django.setup() path.+ from products.exports.backend.facade.api import render_png_export # noqa: PLC0415++ # A system render stays out of the acting user's export quota and the stuck-export sweep, and it+ # expires with the delivery url, its only reference; the format default would keep the PNG for+ # months after the url stopped working.+ render_kwargs: dict = {+ "team": team,+ "created_by": created_by,+ "is_system": True,+ "expires_after": timezone.now() + SLACK_REPORT_CHART_URL_TTL,+ }+ kind = query.get("kind")+ if kind == "SavedInsightNode":+ short_id = query.get("shortId")+ if not isinstance(short_id, str) or not short_id:+ return None+ asset, png = render_png_export(insight_short_id=short_id, **render_kwargs)+ else:+ asset, png = render_png_export(export_context={"source": query}, **render_kwargs)+ if png is None:+ logger.warning("signals_scout.slack_report_chart_render_failed", asset_id=asset.id, error=asset.exception)+ return None+ return asset.id+++def _chart_blocks(chart: dict, image_url: str, position: int) -> list[dict]:+ title = " ".join(str(chart.get("title") or "Chart").split())+ blocks: list[dict] = [+ {"type": "section", "text": {"type": "mrkdwn", "text": f"*{escape_slack_mrkdwn(title)}*"}},+ {"type": "image", "image_url": image_url, "alt_text": title[:2000]},+ ]+ caption = chart.get("caption")+ if isinstance(caption, str) and caption.strip():+ blocks.append(+ {"type": "context", "elements": [{"type": "mrkdwn", "text": escape_slack_mrkdwn(caption.strip())}]}+ )+ for index, block in enumerate(blocks):+ block["block_id"] = f"{CHART_BLOCK_ID_PREFIX}{position}:{index}"+ return blocks+++def _is_chart_block(block: dict) -> bool:+ return str(block.get("block_id") or "").startswith(CHART_BLOCK_ID_PREFIX)+++def strip_chart_blocks(blocks: list[dict]) -> list[dict]:+ """Drop every chart block, leaving the prose and the report link.++ Slack fetches each `image_url` itself and rejects the whole message when it cannot reach one, so+ a delivery Slack refuses can post this instead of losing the report."""+ return [block for block in blocks if not _is_chart_block(block)]+++def has_chart_blocks(blocks: list[dict]) -> bool:+ return any(_is_chart_block(block) for block in blocks)+++def _acting_user(run: SignalScoutRun, team: Team) -> User | None:+ """The user the scout ran as; the render is attributed to and access-checked against them.++ Delivery runs in a worker with no request to authenticate that user, so a creator who has since+ been deactivated, left the org, or lost access to a private project yields no principal. The+ membership test is the same one the runner uses to pick the acting user in the first place."""+ task_run = getattr(run, "task_run", None)+ task = getattr(task_run, "task", None)+ user = getattr(task, "created_by", None)+ if user is None or creator_access_revoked(user, team):+ return None+ if not team.all_users_with_access().filter(id=user.id).exists():+ return None+ return user+++def _rendered_assets_cache_key(delivery_id: str) -> str:+ return f"signals_scout:slack_report_chart_assets:{delivery_id}"+++def _rendered_asset_entry_key(chart_id: str, query: dict) -> str:+ fingerprint = hashlib.sha256(json.dumps(query, sort_keys=True, default=str).encode()).hexdigest()[:16]+ return f"{chart_id}:{fingerprint}"+++def _cache_signing_keys() -> list[str]:+ """Keys for the retry cache's entry signatures, newest first; empty means the cache is off.++ Its own rotatable setting rather than `SECRET_KEY`, so this domain can be rotated without+ disturbing Django's session and CSRF signing. Unprovisioned fails closed: no reuse."""+ return [key for key in settings.SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS if key]+++def _sign_cached_asset(signing_key: str, cache_key: str, entry_key: str, asset_id: int) -> str:+ # HMAC over the delivery-scoped cache key, the chart entry key, and the asset id, so the cached+ # mapping is tamper-evident: a process with write access to the shared Redis can't forge or swap+ # an entry (even for another of the acting user's own assets) without a signing key.+ message = f"{cache_key}\x00{entry_key}\x00{asset_id}".encode()+ return hmac.new(signing_key.encode(), message, hashlib.sha256).hexdigest()[:32]+++# Stored as JSON through the raw Redis client rather than Django's cache: the default cache backend+# pickles values, and a `cache.get` unpickles whatever bytes sit at the key, so a process that can+# write this shared Redis could plant a pickle payload that executes on read. A JSON round-trip has+# no such deserialization path, and each entry carries an HMAC so a substituted asset id is rejected+# on read. The cache only saves re-renders on retry; if it is down the message must still go out, so+# both sides degrade to "no reuse" rather than raising into the delivery task.+def _load_rendered_assets(cache_key: str | None) -> dict[str, int]:+ signing_keys = _cache_signing_keys()+ if cache_key is None or not signing_keys:+ return {}+ try:+ raw = get_client().get(cache_key)+ except Exception:+ logger.warning("signals_scout.slack_report_chart_cache_read_failed", exc_info=True)+ return {}+ if raw is None:+ return {}+ try:+ cached = json.loads(raw)+ except (ValueError, TypeError):+ return {}+ if not isinstance(cached, dict):+ return {}+ verified: dict[str, int] = {}+ for key, value in cached.items():+ # Each entry is [asset_id, signature]; keep only those whose signature we can reproduce, so a+ # tampered or forged entry (a swapped asset id, an unsigned int) is treated as a cache miss.+ if not (isinstance(value, list) and len(value) == 2):+ continue+ asset_id, signature = value+ if not (isinstance(asset_id, int) and not isinstance(asset_id, bool) and isinstance(signature, str)):+ continue+ # Every key verifies, so an entry signed before a rotation is still reusable.+ if any(+ hmac.compare_digest(signature, _sign_cached_asset(signing_key, cache_key, str(key), asset_id))+ for signing_key in signing_keys+ ):+ verified[str(key)] = asset_id+ return verified+++def _store_rendered_assets(cache_key: str | None, rendered_assets: dict[str, int]) -> None:+ signing_keys = _cache_signing_keys()+ if cache_key is None or not signing_keys or not rendered_assets:+ return+ signed = {+ key: [asset_id, _sign_cached_asset(signing_keys[0], cache_key, key, asset_id)]+ for key, asset_id in rendered_assets.items()+ }+ try:+ get_client().set(cache_key, json.dumps(signed), ex=_RENDERED_ASSETS_CACHE_TTL_SECONDS)+ except Exception:+ logger.warning("signals_scout.slack_report_chart_cache_write_failed", exc_info=True)+++@frozen(frozen=False)+class ChartRenderBudget:+ """What one Slack delivery may spend on chart renders, and what it has rendered so far.++ Mutable and shared across a delivery's initial build and any rebuild, so a report edited+ mid-render cannot hand the rebuild a fresh clock and a fresh set of export workflows. Only a+ cache miss spends a render; reusing an asset the delivery already rendered costs nothing here,+ so a rebuild whose charts are unchanged still shows them all. The rendered assets live here+ rather than only in the retry cache, so a rebuild keeps them even where that cache is off."""++ started: float+ renders_remaining: int = MAX_SLACK_REPORT_CHARTS+ rendered_assets: dict[str, int] = field(default_factory=dict)+++def new_chart_render_budget(clock: Callable[[], float] = monotonic) -> ChartRenderBudget:+ return ChartRenderBudget(started=clock())+++def build_scout_report_chart_blocks(+ report: SignalReport,+ run: SignalScoutRun,+ *,+ delivery_id: str | None = None,+ clock: Callable[[], float] = monotonic,+ budget: ChartRenderBudget | None = None,+) -> list[dict]:+ """Render the report's charts to PNGs and return Slack blocks that show them.++ Best effort by design: any chart that cannot be rendered — an unsupported query kind, a+ render failure, no acting user, the cap or the time budget — is skipped rather than failing the+ delivery, since the message still links to the report where the inbox draws every chart. That+ holds for the whole build, not only the render: a chart is a nice-to-have on a message the+ report needs, so anything unexpected here costs the charts rather than the delivery.++ The cap counts attempts, not successes: a report full of failing charts must not launch an+ export workflow per chart. With a `delivery_id`, successful renders are remembered so a retry+ of the same delivery reuses them. Pass a `budget` to spend a render allowance opened before+ this call — a delivery that rebuilds shares one budget across both builds instead of handing+ the rebuild a fresh clock and a fresh set of renders."""+ try:+ return _build_scout_report_chart_blocks(report, run, delivery_id=delivery_id, clock=clock, budget=budget)+ except Exception:+ logger.warning("signals_scout.slack_report_chart_build_error", report_id=str(report.id), exc_info=True)+ return []+++def _build_scout_report_chart_blocks(+ report: SignalReport,+ run: SignalScoutRun,+ *,+ delivery_id: str | None,+ clock: Callable[[], float],+ budget: ChartRenderBudget | None,+) -> list[dict]:+ from products.exports.backend.facade.api import RENDER_TIMEOUT, get_delivery_image_url # noqa: PLC0415++ charts = _ordered_charts(report)+ if not charts:+ return []+ created_by = _acting_user(run, report.team)+ if created_by is None:+ logger.info("signals_scout.slack_report_chart_no_acting_user", report_id=str(report.id), run_id=str(run.id))+ return []++ cache_key = _rendered_assets_cache_key(delivery_id) if delivery_id else None+ budget = new_chart_render_budget(clock) if budget is None else budget+ # This delivery's own renders are authoritative; the retry cache only fills in what an earlier+ # attempt of the same delivery rendered.+ rendered_assets = budget.rendered_assets+ for entry_key, cached_asset_id in _load_rendered_assets(cache_key).items():+ rendered_assets.setdefault(entry_key, cached_asset_id)+ blocks: list[dict] = []+ shown = 0+ for chart in charts:+ if shown >= MAX_SLACK_REPORT_CHARTS:+ break+ query = chart.get("query")+ if not isinstance(query, dict) or query.get("kind") not in _RENDERABLE_CHART_KINDS:+ continue+ chart_id = str(chart.get("chart_id"))+ entry_key = _rendered_asset_entry_key(chart_id, query)+ asset_id = rendered_assets.get(entry_key)+ if asset_id is None:+ if (+ budget.renders_remaining > 0+ and clock() - budget.started + RENDER_TIMEOUT.total_seconds() > SLACK_REPORT_CHART_RENDER_BUDGET_SECONDS+ ):+ logger.info("signals_scout.slack_report_chart_budget_exhausted", report_id=str(report.id))+ budget.renders_remaining = 0+ # Out of renders or out of time, but a later chart may still be in the delivery's cache+ # from an earlier build, so keep looking rather than dropping the rest of the message's+ # charts.+ if budget.renders_remaining <= 0:+ continue+ budget.renders_remaining -= 1+ shown += 1+ try:+ if asset_id is None:+ asset_id = _render_chart_asset_id(team=report.team, created_by=created_by, query=query)+ if asset_id is None:+ continue+ rendered_assets[entry_key] = asset_id+ # Persist each render as it lands: the delivery task acks late, so a retry after a+ # worker loss mid-delivery must find the renders that had already finished.+ _store_rendered_assets(cache_key, rendered_assets)+ # A cache-hit asset_id comes from the shared retry cache, so pin the URL mint to the+ # acting user: a tampered entry pointing at another same-team user's PNG mints nothing.+ image_url = get_delivery_image_url(+ team_id=report.team_id,+ asset_id=asset_id,+ expiry_delta=SLACK_REPORT_CHART_URL_TTL,+ created_by_id=created_by.id,+ )+ except Exception:+ logger.warning(+ "signals_scout.slack_report_chart_render_error",+ report_id=str(report.id),+ chart_id=chart_id,+ exc_info=True,+ )+ continue+ if image_url is None:+ continue+ blocks.extend(_chart_blocks(chart, image_url, shown))+ return blocksdiff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.pyindex 4450f604a9c5..9e28e9e68498 100644--- a/products/signals/backend/scout_harness/slack_delivery.py+++ b/products/signals/backend/scout_harness/slack_delivery.py@@ -8,11 +8,20 @@ from django.conf import settingsimport structlogfrom slack_sdk.errors import SlackApiError+from slack_sdk.web import SlackResponse, WebClientfrom posthog.dataclasses import frozenfrom posthog.models.integration import Integration, SlackIntegration+from posthog.redis import get_clientfrom products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun+from products.signals.backend.scout_harness.slack_charts import (+ ChartRenderBudget,+ build_scout_report_chart_blocks,+ has_chart_blocks,+ new_chart_render_budget,+ strip_chart_blocks,+)from products.signals.backend.slack_formatting import (SLACK_SECTION_TEXT_MAX_LEN,chunk_slack_mrkdwn,@@ -42,8 +51,17 @@ _PERMANENT_SLACK_ERROR_CODES = frozenset(})+# Slack fetches every `image_url` itself while it renders the message, and rejects the whole message+# with one of these when it cannot reach one. Neither code is permanent, so a chart Slack cannot+# fetch would otherwise retry and then drop a report that used to post as text.+_BLOCK_REJECTION_ERROR_CODES = frozenset({"invalid_blocks", "invalid_blocks_format"})+ScoutSlackOutputType = Literal["finding", "report"]+# A report only reaches Slack while it is surfaced. Checked both before enqueue and again just+# before posting, since chart rendering can hold the worker long enough for the report to change.+DELIVERABLE_REPORT_STATUSES = frozenset((SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT))+# Bound on the note snapshot a note-only edit carries through the Celery payload. Slack shows at# most SLACK_SECTION_TEXT_MAX_LEN characters after conversion, so anything past this headroom is# never rendered; the report keeps the full note either way.@@ -264,7 +282,13 @@ def _report_link_block(report: SignalReport) -> dict:}-def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun) -> tuple[list[dict], str]:+def build_scout_report_slack_message(+ report: SignalReport,+ run: SignalScoutRun,+ *,+ delivery_id: str | None = None,+ render_budget: ChartRenderBudget | None = None,+) -> tuple[list[dict], str]:scout_name = _prettify_scout_name(run.skill_name)header = _report_header(report)blocks: list[dict] = [@@ -275,11 +299,15 @@ def build_scout_report_slack_message(report: SignalReport, run: SignalScoutRun){"type": "header", "text": {"type": "plain_text", "text": header}},]+ # Chart links in the prose still reduce to their label; the charts themselves follow the prose+ # as image blocks, the way the inbox places charts the summary doesn't reference inline.summary_text = strip_chart_references((report.summary or "").strip())rendered_summary = truncate_slack_section(markdown_to_slack_mrkdwn(summary_text))if rendered_summary:blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": rendered_summary}})+ # `render_budget` shares one render allowance across a delivery's initial build and any rebuild.+ blocks.extend(build_scout_report_chart_blocks(report, run, delivery_id=delivery_id, budget=render_budget))blocks.append(_report_link_block(report))fallback = f"Scout · {escape_slack_mrkdwn(scout_name)}: {escape_slack_mrkdwn(header[:200])}"return blocks, fallback@@ -319,21 +347,90 @@ def _report_summary_chunks(report: SignalReport) -> list[str]:return chunks+# A content edit made through the scout's edit tool enqueues a fresh full delivery of the report.+# The latest such delivery is recorded so an older one can yield to it, instead of both posting the+# same edited report. Scoped to the destination as well as the report: two scouts editing one report+# into different channels are not competing, and a report-only marker would let either silence the+# other's channel entirely.+_LATEST_REPORT_DELIVERY_TTL_SECONDS = 24 * 60 * 60+++def _latest_report_delivery_key(report_id: str, integration_id: int, channel: str) -> str:+ # The resolved channel id, so two configs naming one channel differently share a marker.+ channel_id = slack_channel_id_from_target(channel)+ return f"signals_scout:slack_report_latest_delivery:{report_id}:{integration_id}:{channel_id}"+++def _decoded_marker(latest: object) -> str | None:+ if latest is None:+ return None+ return latest.decode() if isinstance(latest, bytes) else str(latest)+++def mark_latest_scout_report_delivery(report_id: str, delivery_id: str, integration_id: int, channel: str) -> None:+ try:+ get_client().set(+ _latest_report_delivery_key(report_id, integration_id, channel),+ delivery_id,+ ex=_LATEST_REPORT_DELIVERY_TTL_SECONDS,+ )+ except Exception:+ logger.warning("signals_scout.slack_report_latest_delivery_mark_failed", report_id=report_id, exc_info=True)+++def clear_latest_scout_report_delivery(report_id: str, delivery_id: str, integration_id: int, channel: str) -> None:+ """Drop this delivery's claim on the report, for an enqueue that never reached the broker.++ A marker naming a task that will never run would silence every later delivery of the report for+ the marker's whole TTL. Only clears a marker still holding this delivery's id, so a newer claim+ written in between survives; losing that race costs a duplicate message, never the report."""+ try:+ client = get_client()+ key = _latest_report_delivery_key(report_id, integration_id, channel)+ if _decoded_marker(client.get(key)) == delivery_id:+ client.delete(key)+ except Exception:+ logger.warning("signals_scout.slack_report_latest_delivery_clear_failed", report_id=report_id, exc_info=True)+++def _newer_report_delivery_queued(report_id: str, delivery_id: str, integration_id: int, channel: str) -> bool:+ """Fails open: an unreadable marker means post, since a duplicate message beats a lost report.++ The decode is inside the guard on purpose: a marker holding bytes that are not UTF-8 must read as+ absent, not raise into the delivery task, which would retry and then drop the report."""+ try:+ latest_id = _decoded_marker(get_client().get(_latest_report_delivery_key(report_id, integration_id, channel)))+ except Exception:+ logger.warning("signals_scout.slack_report_latest_delivery_read_failed", report_id=report_id, exc_info=True)+ return False+ if latest_id is None:+ return False+ return latest_id != delivery_id++@frozenclass ScoutReportThreadMessages:- """A threaded report delivery: the channel lead message plus its ordered thread replies."""+ """A report delivery's Slack messages: the channel lead plus its ordered thread replies.++ An unthreaded delivery has no replies."""lead_blocks: list[dict]fallback: strreply_blocks: list[list[dict]]-def build_scout_report_thread_slack_messages(report: SignalReport, run: SignalScoutRun) -> ScoutReportThreadMessages:+def build_scout_report_thread_slack_messages(+ report: SignalReport,+ run: SignalScoutRun,+ *,+ delivery_id: str | None = None,+ render_budget: ChartRenderBudget | None = None,+) -> ScoutReportThreadMessages:"""Render a report as a channel lead plus one reply per remaining summary chunk.- The lead carries the scout name, the report title, the first summary chunk, and the report link.- Every later chunk becomes a threaded reply, so a long summary keeps its full tail in the channel- instead of being clipped at the section cap."""+ The lead carries the scout name, the report title, the first summary chunk, the charts, and the+ report link. Every later chunk becomes a threaded reply, so a long summary keeps its full tail+ in the channel instead of being clipped at the section cap."""scout_name = _prettify_scout_name(run.skill_name)header = _report_header(report)lead_blocks: list[dict] = [@@ -347,6 +444,9 @@ def build_scout_report_thread_slack_messages(report: SignalReport, run: SignalScchunks = _report_summary_chunks(report)if chunks:lead_blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": chunks[0]}})+ # Charts ride the lead rather than a reply: the lead is the message the channel sees, and the+ # replies only carry the summary's tail for anyone who opens the thread.+ lead_blocks.extend(build_scout_report_chart_blocks(report, run, delivery_id=delivery_id, budget=render_budget))lead_blocks.append(_report_link_block(report))reply_blocks = [[{"type": "section", "text": {"type": "mrkdwn", "text": chunk}}] for chunk in chunks[1:]]@@ -423,6 +523,45 @@ def _post_scout_report_thread_replies()+def _post_scout_report_lead_message(+ client: WebClient,+ *,+ channel_id: str,+ delivery_id: str,+ blocks: list[dict],+ fallback: str,+) -> SlackResponse:+ """Post the report's channel message, and post it again without the charts if Slack refuses them.++ A chart Slack cannot fetch takes the whole message down, so on any deployment Slack cannot reach+ a chart-bearing report would never arrive. The prose and the report link are the message; the+ charts are the extra, and the report still draws every one of them in the inbox."""++ def _post(message_blocks: list[dict]) -> SlackResponse:+ return client.chat_postMessage(+ channel=channel_id,+ blocks=message_blocks,+ text=fallback,+ client_msg_id=delivery_id,+ unfurl_links=False,+ unfurl_media=False,+ )++ try:+ return _post(blocks)+ except SlackApiError as exc:+ error_code = slack_api_error_code(exc)+ if error_code not in _BLOCK_REJECTION_ERROR_CODES or not has_chart_blocks(blocks):+ raise+ logger.warning(+ "signals_scout.slack_report_charts_rejected",+ channel=channel_id,+ delivery_id=delivery_id,+ error_code=error_code,+ )+ return _post(strip_chart_blocks(blocks))++def post_scout_report_to_slack(report: SignalReport,run: SignalScoutRun,@@ -444,29 +583,87 @@ def post_scout_report_to_slack(project_id=report.team.project_id,)channel_id = _slack_channel_id(channel)+# Threading applies to a full report only: a note edit is short and posts as a single update.threaded = thread_reports and edit_note is None- reply_blocks: list[list[dict]] = []- if edit_note is not None:- blocks, fallback = build_scout_report_note_slack_message(report, run, edit_note)- elif threaded:- thread_messages = build_scout_report_thread_slack_messages(report, run)- blocks, fallback, reply_blocks = (- thread_messages.lead_blocks,- thread_messages.fallback,- thread_messages.reply_blocks,++ # Shared across the initial build and any rebuild so both draw from one render allowance, rather+ # than the rebuild getting a fresh one (which would let one delivery spend two budgets).+ render_budget = new_chart_render_budget()++ def _build_report_message() -> ScoutReportThreadMessages:+ # A note-only edit renders the passed-in note; every other delivery renders live report content.+ if edit_note is not None:+ note_blocks, note_fallback = build_scout_report_note_slack_message(report, run, edit_note)+ return ScoutReportThreadMessages(lead_blocks=note_blocks, fallback=note_fallback, reply_blocks=[])+ if threaded:+ return build_scout_report_thread_slack_messages(+ report, run, delivery_id=delivery_id, render_budget=render_budget+ )+ report_blocks, report_fallback = build_scout_report_slack_message(+ report, run, delivery_id=delivery_id, render_budget=render_budget)- else:- blocks, fallback = build_scout_report_slack_message(report, run)+ return ScoutReportThreadMessages(lead_blocks=report_blocks, fallback=report_fallback, reply_blocks=[])++ # Building the message renders the report's charts, which can hold the worker for the render+ # budget. Re-read the report after every build and before posting, since an edit in that window+ # can unsurface it (must not post at all) or change its content (the built blocks no longer match+ # the report). On a content change, rebuild from the current report and re-check again — not+ # every edit path enqueues a replacement delivery (the inbox PATCH,+ # `SignalReportViewSet.partial_update`, doesn't), so dropping the message would lose it. The+ # loop is bounded to one rebuild: a further edit racing the rebuild is ordinary last-writer+ # timing, and unchanged charts are reused from the render cache, so a rebuild only re-renders+ # charts the edit actually changed. A note-only message renders the passed-in note, not live+ # content, so it has no revision to guard and never rebuilds.+ messages = ScoutReportThreadMessages(lead_blocks=[], fallback="", reply_blocks=[])+ for _ in range(2):+ content_revision = None if edit_note is not None else report.updated_at+ messages = _build_report_message()+ try:+ report.refresh_from_db()+ except SignalReport.DoesNotExist:+ logger.info("signals_scout.slack_delivery_report_deleted_after_render", report_id=str(report.id))+ return+ if report.status not in DELIVERABLE_REPORT_STATUSES:+ logger.info(+ "signals_scout.slack_delivery_report_not_surfaced_after_render",+ report_id=str(report.id),+ report_status=report.status,+ )+ return+ if content_revision is None or report.updated_at == content_revision:+ break+ logger.info("signals_scout.slack_delivery_report_rebuilt_after_content_change", report_id=str(report.id))++ # An edit path that enqueued a replacement delivery marked it as the report's latest, so yield to+ # it and let that one post. Checked for every full delivery, not only one that rebuilt: an edit+ # landing before this delivery starts leaves nothing to rebuild, so the content is already+ # current and a rebuild-only check would post it here and again under the replacement. A+ # note-only delivery carries its own note rather than report content, and is never marked as a+ # latest delivery, so it has no claim to yield and must always post.+ if edit_note is None and _newer_report_delivery_queued(str(report.id), delivery_id, integration_id, channel):+ logger.info(+ "signals_scout.slack_delivery_yielded_to_newer_delivery",+ report_id=str(report.id),+ delivery_id=delivery_id,+ )+ return++ # The build can hold the worker for the whole render budget, long enough for the workspace to be+ # reconnected, which writes a new token to the same row and revokes the one loaded above. Posting+ # with the stale token fails as permanent, so resolve the row again before the post.+ integration = _slack_integration_for_project(+ integration_id=integration_id,+ project_id=report.team.project_id,+ )client = SlackIntegration(integration).clienttry:- response = client.chat_postMessage(- channel=channel_id,- blocks=blocks,- text=fallback,- client_msg_id=delivery_id,- unfurl_links=False,- unfurl_media=False,+ response = _post_scout_report_lead_message(+ client,+ channel_id=channel_id,+ delivery_id=delivery_id,+ blocks=messages.lead_blocks,+ fallback=messages.fallback,)except SlackApiError as exc:error_code = slack_api_error_code(exc)@@ -484,8 +681,8 @@ def post_scout_report_to_slack(channel_id=channel_id,thread_ts=thread_ts,delivery_id=delivery_id,- reply_blocks=reply_blocks,- fallback=fallback,+ reply_blocks=messages.reply_blocks,+ fallback=messages.fallback,)_post_scout_slack_reply(diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.pyindex fd137122e48f..b48f05751975 100644--- a/products/signals/backend/scout_harness/tools/report.py+++ b/products/signals/backend/scout_harness/tools/report.py@@ -1462,15 +1462,16 @@ def _do_edit_report(updated_fields or note_appended or reviewers_set or charts_set is not None)if report_status is not None and _surfaced(report_status) and not prompts_only:- # A note-only edit leaves the title and summary the Slack report message shows+ # A note-only edit leaves the title, summary and charts the Slack report message shows# unchanged, so re-posting it would duplicate the message already in the channel.# Deliver the note itself instead; any edit that rewrote the content re-posts the# report as before.+ note_only = note_appended and not updated_fields and not charts_changedqueue_configured_scout_slack_delivery(run_id=run.id,output_type="report",output_id=report_id,- edit_note=append_note if note_appended and not updated_fields else None,+ edit_note=append_note if note_only else None,)return resultdiff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.pyindex 6999674b9d31..2facfe6cc348 100644--- a/products/signals/backend/slack_formatting.py+++ b/products/signals/backend/slack_formatting.py@@ -13,10 +13,11 @@ SLACK_SECTION_TEXT_MAX_LEN = 2900# are escaped before conversion, so any literal angle bracket here was produced by the converter._SLACK_ANGLE_TOKEN_RE = re.compile(r"<([^<>|]*)(\|[^<>]*)?>")-# A summary places a chart inline with a markdown link targeting `chart:<chart_id>`. Slack has no-# chart to render and degrades it badly either way: the mrkdwn converter emits a `<chart:id|label>`-# token that `_defang_unsafe_slack_tokens` escapes into visible `<…>`, and the excerpt path-# shows the raw `[label](chart:id)` syntax. So the link is reduced to its label first.+# A summary places a chart inline with a markdown link targeting `chart:<chart_id>`. Slack cannot+# place an image mid-sentence and degrades the link badly either way: the mrkdwn converter emits a+# `<chart:id|label>` token that `_defang_unsafe_slack_tokens` escapes into visible `<…>`, and+# the excerpt path shows the raw `[label](chart:id)` syntax. So the link is reduced to its label+# first; report delivery renders the charts as image blocks after the prose instead.## The shapes matched are the ones the inbox's markdown parse resolves and therefore draws a chart# for: any target rather than the id charset (a typo is just as unrenderable), all three CommonMarkdiff --git a/products/signals/backend/tasks.py b/products/signals/backend/tasks.pyindex 38eb19097c80..a28fa47ad880 100644--- a/products/signals/backend/tasks.py+++ b/products/signals/backend/tasks.py@@ -34,8 +34,11 @@ from products.signals.backend.report_generation.repo_activity import ()from products.signals.backend.scout_harness.inactivity import sweep_inactive_scoutsfrom products.signals.backend.scout_harness.slack_delivery import (+ DELIVERABLE_REPORT_STATUSES,ScoutSlackOutputType,ScoutSlackPermanentDeliveryError,+ clear_latest_scout_report_delivery,+ mark_latest_scout_report_delivery,post_scout_emission_to_slack,post_scout_report_to_slack,slack_api_error_code,@@ -70,7 +73,6 @@ _OUT_OF_PERIOD_SYNC_ERROR = "billing: refund period no longer creditable at sync_SCOUT_SLACK_MAX_RETRIES = 5_SCOUT_SLACK_RETRY_BASE_SECONDS = 60_SCOUT_SLACK_RETRY_MAX_SECONDS = 3600-_SCOUT_SLACK_DELIVERABLE_REPORT_STATUSES = frozenset((SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT))@shared_task(@@ -150,7 +152,7 @@ def deliver_scout_slack_output(if report is None or run is None:logger.warning("signals_scout.slack_delivery_output_missing", **context)return- if report.status not in _SCOUT_SLACK_DELIVERABLE_REPORT_STATUSES:+ if report.status not in DELIVERABLE_REPORT_STATUSES:logger.info("signals_scout.slack_delivery_report_not_surfaced",**context,@@ -220,7 +222,15 @@ def enqueue_scout_slack_delivery(thread_reports: bool = False,) -> None:"""Publish after commit, capturing broker failures without affecting the completed emit."""+ # Only a full report delivery supersedes an earlier one: a note-only update leaves the+ # report message to the delivery that is still building it.+ supersedes = output_type == "report" and edit_note is Nonetry:+ # Claim before publishing: an earlier delivery of the same report reads this marker to decide+ # whether to yield, and between the two calls it would see no claim and post the report that+ # this delivery is about to post again.+ if supersedes:+ mark_latest_scout_report_delivery(output_id, delivery_id, integration_id, channel)# Each optional arg rides as a kwarg only when set, so a delivery without one keeps the# payload shape workers running the previous task signature still accept.extra_kwargs: dict[str, str | bool] = {}@@ -239,6 +249,10 @@ def enqueue_scout_slack_delivery(**extra_kwargs,)except Exception as exc:+ # The claim now names a delivery that will never run, and would silence every later delivery+ # of this report until it expired, so give it up before reporting the failure.+ if supersedes:+ clear_latest_scout_report_delivery(output_id, delivery_id, integration_id, channel)capture_exception(exc,{diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.pyindex a5bcafe5fea2..2f8651424523 100644--- a/products/signals/backend/test/test_scout_report_api.py+++ b/products/signals/backend/test/test_scout_report_api.py@@ -152,6 +152,21 @@ class TestScoutReportAPI(APIBaseTest):data={"report_id": report_id, "summary": "Rewritten summary", "append_note": "And a note"},format="json",)+ charted = self.client.post(+ self._edit_url(str(run.id)),+ data={+ "report_id": report_id,+ "append_note": "Added a chart",+ "charts": [+ {+ "chart_id": "signups",+ "title": "Daily signups",+ "query": {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": []}},+ }+ ],+ },+ format="json",+ )prompted = self.client.post(self._edit_url(str(run.id)),data={"report_id": report_id, "suggested_prompts": ["Which teams are affected?"]},@@ -161,10 +176,11 @@ class TestScoutReportAPI(APIBaseTest):assert emitted.status_code == status.HTTP_200_OK, emitted.json()assert edited.status_code == status.HTTP_200_OK, edited.json()assert rewritten.status_code == status.HTTP_200_OK, rewritten.json()+ assert charted.status_code == status.HTTP_200_OK, charted.json()assert prompted.status_code == status.HTTP_200_OK, prompted.json()# The prompt-only edit delivers nothing: the questions render in the inbox and nowhere in the# Slack message, so posting it would repeat the report the channel already has, byte for byte.- assert enqueue.call_count == 3+ assert enqueue.call_count == 4for call in enqueue.call_args_list:assert call.kwargs["team_id"] == self.team.idassert call.kwargs["output_type"] == "report"@@ -176,10 +192,12 @@ class TestScoutReportAPI(APIBaseTest):assert enqueue.call_args_list[0].kwargs["delivery_id"] == report_idassert enqueue.call_args_list[1].kwargs["delivery_id"] != report_id# Only the note-only edit delivers as a note; an emit and a content rewrite post the report- # message, even when the rewrite also appended a note.+ # message, even when the rewrite also appended a note. Charts are content the message shows,+ # so a chart change with a note re-posts the report too.assert enqueue.call_args_list[0].kwargs["edit_note"] is Noneassert enqueue.call_args_list[1].kwargs["edit_note"] == "Re-validated on the next run"assert enqueue.call_args_list[2].kwargs["edit_note"] is None+ assert enqueue.call_args_list[3].kwargs["edit_note"] is Nonedef test_emit_report_unsafe_suppresses_but_returns_id(self) -> None:run = _make_run(self.team)diff --git a/products/signals/backend/test/test_scout_slack_charts.py b/products/signals/backend/test/test_scout_slack_charts.pynew file mode 100644index 000000000000..72535db50d52--- /dev/null+++ b/products/signals/backend/test/test_scout_slack_charts.py@@ -0,0 +1,384 @@+import json+from contextlib import nullcontext+from datetime import timedelta++from posthog.test.base import BaseTest+from unittest.mock import MagicMock, patch++from django.apps import apps+from django.utils import timezone++from parameterized import parameterized++from posthog.redis import get_client++from products.exports.backend.facade.api import RENDER_TIMEOUT+from products.signals.backend.models import SignalReport, SignalScoutRun+from products.signals.backend.scout_harness.slack_charts import (+ CHART_BLOCK_ID_PREFIX,+ MAX_SLACK_REPORT_CHARTS,+ SLACK_REPORT_CHART_RENDER_BUDGET_SECONDS,+ SLACK_REPORT_CHART_URL_TTL,+ ChartRenderBudget,+ _rendered_asset_entry_key,+ _rendered_assets_cache_key,+ build_scout_report_chart_blocks,+)+from products.signals.backend.scout_harness.slack_delivery import build_scout_report_slack_message++_TRENDS = {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [{"event": "$pageview"}]}}+_SAVED = {"kind": "SavedInsightNode", "shortId": "abc123xy"}+_SQL = {"kind": "DataVisualizationNode", "source": {"kind": "HogQLQuery", "query": "select 1"}}+++def _chart(chart_id: str, query: dict, **extra: object) -> dict:+ return {"chart_id": chart_id, "title": f"Chart {chart_id}", "query": query, **extra}+++class TestScoutSlackReportCharts(BaseTest):+ def _make_run(self, *, created_by=None) -> SignalScoutRun:+ Task = apps.get_model("tasks", "Task")+ TaskRun = apps.get_model("tasks", "TaskRun")+ task = Task.objects.create(+ team=self.team,+ created_by=created_by,+ title="scout run",+ description="scout run",+ origin_product=Task.OriginProduct.SIGNALS_SCOUT,+ )+ task_run = TaskRun.objects.create(task=task, team=self.team)+ return SignalScoutRun.all_teams.create(+ task_run=task_run, team=self.team, skill_name="signals-scout-product-analytics", skill_version=1+ )++ def _make_report(self, charts: list[dict], summary: str = "Signups dropped.") -> SignalReport:+ return SignalReport.objects.create(+ team=self.team, status=SignalReport.Status.READY, title="Signups", summary=summary, charts=charts+ )++ def _patched_render(self):+ render = patch("products.exports.backend.facade.api.render_png_export")+ url = patch("products.exports.backend.facade.api.get_delivery_image_url")+ return render, url++ def test_renders_supported_charts_and_skips_the_rest_without_failing(self) -> None:+ run = self._make_run(created_by=self.user)+ report = self._make_report(+ [+ _chart("trend", _TRENDS, caption="Daily signups, last 30 days"),+ _chart("sql", _SQL),+ _chart("saved", _SAVED),+ _chart("broken", _TRENDS),+ ]+ )+ assets = iter(+ [(MagicMock(id=11), b"png"), (MagicMock(id=12), b"png"), (MagicMock(id=13, exception="boom"), None)]+ )+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.side_effect = lambda **_: next(assets)+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ blocks = build_scout_report_chart_blocks(report, run)++ assert [call.kwargs.get("insight_short_id") for call in render_mock.call_args_list] == [None, "abc123xy", None]+ assert render_mock.call_args_list[0].kwargs["export_context"] == {"source": _TRENDS}+ assert render_mock.call_args_list[0].kwargs["created_by"] == self.user+ # A delivery render is a system asset that expires with its url, not a user export kept for months.+ for call in render_mock.call_args_list:+ assert call.kwargs["is_system"] is True+ assert abs(call.kwargs["expires_after"] - timezone.now() - SLACK_REPORT_CHART_URL_TTL) < timedelta(+ minutes=1+ )+ # Every URL mint is pinned to the acting user, so a substituted cache id can't be published.+ assert all(call.kwargs["created_by_id"] == self.user.id for call in url_mock.call_args_list)+ assert [{k: v for k, v in b.items() if k != "block_id"} for b in blocks if b["type"] == "image"] == [+ {"type": "image", "image_url": "https://img/11", "alt_text": "Chart trend"},+ {"type": "image", "image_url": "https://img/12", "alt_text": "Chart saved"},+ ]+ assert blocks[2]["elements"] == [{"type": "mrkdwn", "text": "Daily signups, last 30 days"}]+ # Every block a chart contributes is tagged, so a message Slack refuses can drop them whole.+ assert all(b["block_id"].startswith(CHART_BLOCK_ID_PREFIX) for b in blocks)++ def test_referenced_charts_render_first_and_the_cap_holds(self) -> None:+ run = self._make_run(created_by=self.user)+ charts = [_chart(f"c{i}", _TRENDS) for i in range(MAX_SLACK_REPORT_CHARTS + 2)]+ report = self._make_report(charts, summary="See [the last one](chart:c4) and [c1](chart:c1).")+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.return_value = "https://img/1"+ blocks = build_scout_report_chart_blocks(report, run)++ titles = [b["text"]["text"] for b in blocks if b["type"] == "section"]+ assert titles == ["*Chart c4*", "*Chart c1*", "*Chart c0*"]+ assert render_mock.call_count == MAX_SLACK_REPORT_CHARTS++ @parameterized.expand(+ [+ ("no_acting_user", None),+ ("deactivated_acting_user", "inactive"),+ ("acting_user_without_project_access", "no_project_access"),+ ("no_charts", "user"),+ ]+ )+ def test_returns_nothing_without_a_principal_or_charts(self, _name, actor) -> None:+ if actor == "inactive":+ self.user.is_active = False+ self.user.save(update_fields=["is_active"])+ access_patch = (+ patch("products.signals.backend.scout_harness.slack_charts.Team.all_users_with_access")+ if actor == "no_project_access"+ else nullcontext()+ )+ run = self._make_run(created_by=self.user if actor else None)+ report = self._make_report([_chart("trend", _TRENDS)] if actor != "user" else [])+ render, url = self._patched_render()+ with render as render_mock, url, access_patch as access_mock:+ if access_mock is not None:+ access_mock.return_value.filter.return_value.exists.return_value = False+ assert build_scout_report_chart_blocks(report, run) == []+ render_mock.assert_not_called()++ def test_failed_renders_count_toward_the_cap(self) -> None:+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart(f"c{i}", _TRENDS) for i in range(MAX_SLACK_REPORT_CHARTS + 3)])+ render, url = self._patched_render()+ with render as render_mock, url:+ render_mock.return_value = (MagicMock(id=1, exception="boom"), None)+ assert build_scout_report_chart_blocks(report, run) == []+ assert render_mock.call_count == MAX_SLACK_REPORT_CHARTS++ def test_retry_of_the_same_delivery_reuses_rendered_assets(self) -> None:+ get_client().flushdb()+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS), _chart("b", _TRENDS)])+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.side_effect = [(MagicMock(id=7), b"png"), (MagicMock(id=8, exception="boom"), None)]+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ first = build_scout_report_chart_blocks(report, run, delivery_id="delivery-1")+ render_mock.side_effect = [(MagicMock(id=9), b"png")]+ second = build_scout_report_chart_blocks(report, run, delivery_id="delivery-1")++ assert [b["image_url"] for b in first if b["type"] == "image"] == ["https://img/7"]+ # Only the chart that failed the first time renders again; the other reuses asset 7.+ assert [b["image_url"] for b in second if b["type"] == "image"] == ["https://img/7", "https://img/9"]+ assert render_mock.call_count == 3++ def test_url_mint_failure_skips_the_chart_but_keeps_the_rest(self) -> None:+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS), _chart("b", _TRENDS)])+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.side_effect = [RuntimeError("db down"), "https://img/1"]+ blocks = build_scout_report_chart_blocks(report, run)++ assert [b["image_url"] for b in blocks if b["type"] == "image"] == ["https://img/1"]++ def test_retry_re_renders_a_chart_whose_query_changed(self) -> None:+ get_client().flushdb()+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS)])+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.side_effect = [(MagicMock(id=7), b"png"), (MagicMock(id=8), b"png")]+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ build_scout_report_chart_blocks(report, run, delivery_id="delivery-3")+ report.charts = [_chart("a", {**_TRENDS, "source": {"kind": "TrendsQuery", "series": [{"event": "x"}]}})]+ report.save(update_fields=["charts"])+ second = build_scout_report_chart_blocks(report, run, delivery_id="delivery-3")++ assert [b["image_url"] for b in second if b["type"] == "image"] == ["https://img/8"]++ def test_tampered_cache_entry_is_rejected_and_rerenders(self) -> None:+ get_client().flushdb()+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS)])+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.side_effect = [(MagicMock(id=7), b"png"), (MagicMock(id=9), b"png")]+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ build_scout_report_chart_blocks(report, run, delivery_id="delivery-tamper")+ # Simulate a shared-Redis writer swapping the cached asset id (keeping the old signature).+ key = _rendered_assets_cache_key("delivery-tamper")+ cached = get_client().get(key)+ assert cached is not None+ entry = json.loads(cached)+ (only_key,) = entry.keys()+ entry[only_key][0] = 999+ get_client().set(key, json.dumps(entry))+ second = build_scout_report_chart_blocks(report, run, delivery_id="delivery-tamper")++ # The forged id (999) fails the HMAC check and is treated as a miss, so the chart re-renders.+ assert [b["image_url"] for b in second if b["type"] == "image"] == ["https://img/9"]+ assert render_mock.call_count == 2++ @parameterized.expand(+ [+ # Rotation: the entry was signed with a key that is now the fallback, so reuse survives.+ ("rotated_signing_key", ["new-key", "signing-key"], 1),+ # Unprovisioned: nothing can verify an entry, so the delivery re-renders instead.+ ("no_signing_key", [], 2),+ ]+ )+ def test_cache_reuse_follows_the_signing_keys(self, _name, keys_on_read, expected_renders) -> None:+ get_client().flushdb()+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS)])+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.side_effect = [(MagicMock(id=7), b"png"), (MagicMock(id=9), b"png")]+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ with self.settings(SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS=["signing-key"]):+ build_scout_report_chart_blocks(report, run, delivery_id="delivery-keys")+ with self.settings(SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS=keys_on_read):+ build_scout_report_chart_blocks(report, run, delivery_id="delivery-keys")++ assert render_mock.call_count == expected_renders++ def test_shared_budget_carries_the_render_time_across_builds(self) -> None:+ run = self._make_run(created_by=self.user)+ # The edit a rebuild reacts to placed a new chart ahead of one the first build rendered.+ report = self._make_report([_chart("new", _TRENDS), _chart("kept", _TRENDS)])+ budget = ChartRenderBudget(started=1.0)+ budget.rendered_assets[_rendered_asset_entry_key("kept", _TRENDS)] = 7+ render, url = self._patched_render()+ # The budget started a whole window ago, so a rebuild sharing it has no time left and renders+ # nothing — proving the budget is measured from when it opened, not fresh per build. Reusing+ # an asset it already rendered costs no time, so the chart behind the new one still shows.+ with render as render_mock, url as url_mock:+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ blocks = build_scout_report_chart_blocks(+ report,+ run,+ clock=lambda: SLACK_REPORT_CHART_RENDER_BUDGET_SECONDS,+ budget=budget,+ )++ assert render_mock.call_count == 0+ assert [b["image_url"] for b in blocks if b["type"] == "image"] == ["https://img/7"]++ @parameterized.expand(+ [+ ("retry_cache_on", ["signing-key"]),+ # Unprovisioned key: the rebuild can only keep the unchanged charts from the budget itself.+ ("retry_cache_off", []),+ ]+ )+ def test_shared_budget_carries_the_render_count_across_builds(self, _name, signing_keys) -> None:+ get_client().flushdb()+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart(f"c{i}", _TRENDS) for i in range(MAX_SLACK_REPORT_CHARTS)])+ budget = ChartRenderBudget(started=0.0)+ render, url = self._patched_render()+ with render as render_mock, url as url_mock, self.settings(SIGNALS_SLACK_CHART_CACHE_SIGNING_KEYS=signing_keys):+ render_mock.side_effect = lambda **kw: (MagicMock(id=render_mock.call_count), b"png")+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ build_scout_report_chart_blocks(+ report, run, delivery_id="delivery-rebuild", clock=lambda: 0.0, budget=budget+ )+ # The edit a rebuild reacts to: one chart's query changed, the other two did not.+ report.charts = [+ _chart("c0", {**_TRENDS, "source": {"kind": "TrendsQuery", "series": [{"event": "x"}]}}),+ *report.charts[1:],+ ]+ report.save(update_fields=["charts"])+ rebuilt = build_scout_report_chart_blocks(+ report, run, delivery_id="delivery-rebuild", clock=lambda: 0.0, budget=budget+ )++ # A rebuild shares the delivery's render allowance, so the whole delivery launches at most+ # MAX_SLACK_REPORT_CHARTS export workflows. The changed chart is dropped for want of a render;+ # the unchanged ones still show, reused from the delivery's own renders.+ assert render_mock.call_count == MAX_SLACK_REPORT_CHARTS+ assert [b["image_url"] for b in rebuilt if b["type"] == "image"] == ["https://img/2", "https://img/3"]++ def test_each_render_is_cached_before_the_next_starts(self) -> None:+ # The delivery task acks late, so a worker lost between two renders must leave the first one+ # behind for the retry to reuse, rather than only what a completed loop would have written.+ get_client().flushdb()+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS), _chart("b", _TRENDS)])+ cached_before_second_render: list[int] = []+ render, url = self._patched_render()++ def _render(**kw):+ if render_mock.call_count == 2:+ raw = get_client().get(_rendered_assets_cache_key("delivery-wt"))+ assert raw is not None+ cached_before_second_render.extend(v[0] for v in json.loads(raw).values())+ return (MagicMock(id=render_mock.call_count), b"png")++ with render as render_mock, url as url_mock:+ render_mock.side_effect = _render+ url_mock.side_effect = lambda **kw: f"https://img/{kw['asset_id']}"+ build_scout_report_chart_blocks(report, run, delivery_id="delivery-wt")++ assert cached_before_second_render == [1]++ def test_cache_outage_still_delivers_charts(self) -> None:+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS)])+ render, url = self._patched_render()+ with (+ render as render_mock,+ url as url_mock,+ patch(+ "products.signals.backend.scout_harness.slack_charts.get_client",+ side_effect=ConnectionError("redis down"),+ ),+ ):+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.return_value = "https://img/1"+ blocks = build_scout_report_chart_blocks(report, run, delivery_id="delivery-2")++ assert [b["image_url"] for b in blocks if b["type"] == "image"] == ["https://img/1"]++ def test_render_budget_reserves_time_for_a_whole_render(self) -> None:+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("a", _TRENDS), _chart("b", _TRENDS)])+ # The second chart is checked with less than one RENDER_TIMEOUT of budget left.+ clock = iter([0.0, 0.0, SLACK_REPORT_CHART_RENDER_BUDGET_SECONDS - RENDER_TIMEOUT.total_seconds() + 1])+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.return_value = "https://img/1"+ blocks = build_scout_report_chart_blocks(report, run, clock=lambda: next(clock))++ assert render_mock.call_count == 1+ assert len([b for b in blocks if b["type"] == "image"]) == 1++ @parameterized.expand(["_acting_user", "_chart_blocks"])+ def test_a_failure_outside_the_render_costs_the_charts_not_the_report(self, failing) -> None:+ # Everything the build does is best effort, not only the render itself: an exception escaping+ # here would fail the delivery task, which retries and then drops a report that used to post.+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("trend", _TRENDS)])+ render, url = self._patched_render()+ with (+ render as render_mock,+ url as url_mock,+ patch(+ f"products.signals.backend.scout_harness.slack_charts.{failing}",+ side_effect=RuntimeError("boom"),+ ),+ ):+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.return_value = "https://img/1"+ blocks, _ = build_scout_report_slack_message(report, run)++ assert [b["type"] for b in blocks] == ["context", "header", "section", "actions"]++ def test_report_message_places_charts_between_prose_and_link(self) -> None:+ run = self._make_run(created_by=self.user)+ report = self._make_report([_chart("trend", _TRENDS)], summary="Look at [signups](chart:trend).")+ render, url = self._patched_render()+ with render as render_mock, url as url_mock:+ render_mock.return_value = (MagicMock(id=1), b"png")+ url_mock.return_value = "https://img/1"+ blocks, _ = build_scout_report_slack_message(report, run)++ assert [b["type"] for b in blocks] == ["context", "header", "section", "section", "image", "actions"]+ assert blocks[2]["text"]["text"] == "Look at signups."diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.pyindex 8d436dda85a7..de5a8dd9c421 100644--- a/products/signals/backend/test/test_scout_slack_delivery.py+++ b/products/signals/backend/test/test_scout_slack_delivery.py@@ -12,11 +12,15 @@ from slack_sdk.errors import SlackApiErrorfrom posthog.models import Teamfrom posthog.models.integration import Integration+from posthog.redis import get_clientfrom products.signals.backend.models import SignalReport, SignalScoutEmission, SignalScoutRun+from products.signals.backend.scout_harness.slack_charts import CHART_BLOCK_ID_PREFIX as PREFIXfrom products.signals.backend.scout_harness.slack_delivery import (ScoutSlackPermanentDeliveryError,+ _latest_report_delivery_key,get_scout_slack_destination,+ mark_latest_scout_report_delivery,post_scout_emission_to_slack,)from products.signals.backend.scout_harness.slack_delivery_queue import queue_configured_scout_slack_delivery@@ -222,6 +226,35 @@ class TestScoutSlackDelivery(BaseTest):assert delay.call_args_list[0].kwargs == {}assert delay.call_args_list[1].kwargs == {"edit_note": "Re-validated on the next run"}+ @parameterized.expand(+ [+ ("full_report", "report", None, "b316c1d1-6901-49eb-8223-96d4df69f67f"),+ # A note-only update must not supersede the delivery still building the report message.+ ("note_only", "report", "Re-validated on the next run", None),+ ("finding", "finding", None, None),+ ]+ )+ def test_enqueue_marks_only_a_full_report_delivery_as_the_latest(+ self, _name, output_type, edit_note, expected_marker+ ) -> None:+ get_client().flushdb()+ with patch.object(deliver_scout_slack_output, "delay"):+ enqueue_scout_slack_delivery(+ team_id=self.team.id,+ output_type=output_type,+ output_id="ddab8ee5-2bb8-4226-b145-6732d31dc344",+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",+ delivery_id="b316c1d1-6901-49eb-8223-96d4df69f67f",+ integration_id=9,+ channel="CSCOUTS|#scout-findings",+ edit_note=edit_note,+ )++ marker = get_client().get(+ _latest_report_delivery_key("ddab8ee5-2bb8-4226-b145-6732d31dc344", 9, "CSCOUTS|#scout-findings")+ )+ assert (marker.decode() if marker is not None else None) == expected_marker+def test_enqueue_omits_thread_reports_kwarg_when_off(self) -> None:# Same backward-compat contract as edit_note: the flag rides as a kwarg only when on, so a# worker on the previous task signature never sees an unknown keyword for a default delivery.@@ -451,6 +484,382 @@ class TestScoutSlackDelivery(BaseTest):fake_client.chat_postMessage.assert_not_called()+ def test_task_skips_report_suppressed_during_render(self) -> None:+ # The task's pre-render status check passes, but chart rendering can hold the worker for the+ # render budget. A report suppressed in that window must not be posted with its freshly minted+ # image URLs — post_scout_report_to_slack re-reads the status after building the blocks.+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()++ def _suppress_mid_render(report_arg, run_arg, *, delivery_id=None, render_budget=None):+ SignalReport.objects.filter(id=report_arg.id).update(status=SignalReport.Status.SUPPRESSED)+ return [{"type": "header", "text": {"type": "plain_text", "text": "x"}}], "x"++ with (+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,+ patch(+ "products.signals.backend.scout_harness.slack_delivery.build_scout_report_slack_message",+ side_effect=_suppress_mid_render,+ ),+ ):+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ )++ fake_client.chat_postMessage.assert_not_called()++ def test_task_rebuilds_report_whose_content_changed_during_render(self) -> None:+ # An edit that changes content during the render window leaves the report deliverable but the+ # built blocks stale. Not every edit path enqueues a replacement (the inbox PATCH doesn't), so+ # the delivery must rebuild from the current report and post that, never drop it or post stale.+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = {"ts": "1785418710.000900"}+ builds = {"n": 0}++ def _build(report_arg, run_arg, *, delivery_id=None, render_budget=None):+ builds["n"] += 1+ if builds["n"] == 1:+ # A real edit save() bumps updated_at (auto_now); QuerySet.update() would not.+ edited = SignalReport.objects.get(id=report_arg.id)+ edited.title = "Checkout failures (edited)"+ edited.save()+ return [{"type": "header", "text": {"type": "plain_text", "text": "stale"}}], "stale"+ return [{"type": "header", "text": {"type": "plain_text", "text": "fresh"}}], "fresh"++ with (+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,+ patch(+ "products.signals.backend.scout_harness.slack_delivery.build_scout_report_slack_message",+ side_effect=_build,+ ),+ ):+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ )++ # Rebuilt once, and the posted message carries the rebuilt (fresh) blocks, not the stale ones.+ assert builds["n"] == 2+ posted = fake_client.chat_postMessage.call_args_list[0].kwargs+ assert posted["blocks"][0]["text"]["text"] == "fresh"++ @parameterized.expand(["edit_during_the_build", "edit_before_the_build"])+ def test_delivery_yields_to_a_newer_delivery_of_the_same_report(self, edit_timing) -> None:+ # A scout edit that changes content enqueues its own full delivery, which is marked as the+ # report's latest. This delivery must post nothing either way, so the channel gets the edited+ # report once rather than from both. An edit landing before this delivery even starts leaves+ # its build nothing to rebuild, so the yield cannot be conditional on having rebuilt.+ get_client().flushdb()+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ delivery_id = "01864f4c-6957-7d3f-8d85-1d775e527265"+ newer_delivery_id = "0d1b6f3a-1d3f-4a6f-9d2c-7b3e2f1a9c44"+ channel = "CSCOUTS|#scout-findings"+ mark_latest_scout_report_delivery(str(report.id), delivery_id, integration.id, channel)++ def _edit_and_supersede() -> None:+ edited = SignalReport.objects.get(id=report.id)+ edited.title = "Checkout failures (edited)"+ edited.save()+ mark_latest_scout_report_delivery(str(report.id), newer_delivery_id, integration.id, channel)++ if edit_timing == "edit_before_the_build":+ _edit_and_supersede()++ def _build(report_arg, run_arg, *, delivery_id=None, render_budget=None):+ if edit_timing == "edit_during_the_build":+ _edit_and_supersede()+ return [{"type": "header", "text": {"type": "plain_text", "text": "stale"}}], "stale"++ with (+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,+ patch(+ "products.signals.backend.scout_harness.slack_delivery.build_scout_report_slack_message",+ side_effect=_build,+ ),+ ):+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ delivery_id,+ integration.id,+ channel,+ )++ fake_client.chat_postMessage.assert_not_called()++ @parameterized.expand(+ [+ # A note carries its own content and is never marked as a latest delivery, so a newer+ # full delivery of the report is not a replacement for it.+ ("note_only", "Re-validated on the next run", "same_channel", "01234567-89ab-cdef-0123-456789abcdef"),+ # Another channel's delivery is not competing for this one's channel.+ ("other_destination", None, "other_channel", "01234567-89ab-cdef-0123-456789abcdef"),+ # A marker that cannot be decoded reads as absent rather than raising into the task,+ # which would retry and then drop the report.+ ("unreadable_marker", None, "same_channel", b"\xff\xfe not utf-8"),+ ]+ )+ def test_delivery_posts_when_the_marker_is_not_a_claim_over_it(+ self, _name, edit_note, marker_channel, marker_value+ ) -> None:+ get_client().flushdb()+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = FakeSlackResponse({"ts": "1785418710.000700"})+ channel = "CSCOUTS|#scout-findings"+ marked_channel = channel if marker_channel == "same_channel" else "CELSEWHERE|#other"+ get_client().set(+ _latest_report_delivery_key(str(report.id), integration.id, marked_channel),+ marker_value,+ )++ with patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration:+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ channel,+ edit_note,+ )++ assert fake_client.chat_postMessage.call_args_list[0].kwargs["channel"] == "CSCOUTS"++ def test_delivery_posts_with_the_token_stored_after_the_render(self) -> None:+ # The chart build can hold the worker for minutes, long enough for the workspace to be+ # reconnected. That writes a new token to the same integration row and revokes the old one,+ # and a post with the old token fails as permanent, so the row is read again before the post.+ get_client().flushdb()+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(+ team=self.team, kind=Integration.IntegrationKind.SLACK, sensitive_config={"access_token": "xoxb-old"}+ )+ fake_client = MagicMock()+ fake_client.chat_postMessage.return_value = FakeSlackResponse({"ts": "1785418710.000700"})++ def _build(report_arg, run_arg, *, delivery_id=None, render_budget=None):+ Integration.objects.filter(id=integration.id).update(sensitive_config={"access_token": "xoxb-new"})+ return [{"type": "header", "text": {"type": "plain_text", "text": "Checkout failures"}}], "fallback"++ with (+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,+ patch(+ "products.signals.backend.scout_harness.slack_delivery.build_scout_report_slack_message",+ side_effect=_build,+ ),+ ):+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ )++ posted_with = slack_integration.call_args_list[-1].args[0]+ assert posted_with.sensitive_config == {"access_token": "xoxb-new"}+ assert fake_client.chat_postMessage.call_args_list[0].kwargs["channel"] == "CSCOUTS"++ @parameterized.expand(+ [+ # Nothing else claimed the report, so the claim this enqueue made goes down with it.+ ("own_claim_is_released", None, None),+ # A newer delivery claimed the report between the mark and the failure. That claim names+ # a task that really is queued, so it has to survive this one's cleanup.+ ("newer_claim_survives", "0d1b6f3a-1d3f-4a6f-9d2c-7b3e2f1a9c44", "0d1b6f3a-1d3f-4a6f-9d2c-7b3e2f1a9c44"),+ ]+ )+ def test_enqueue_claims_the_report_before_publishing_and_releases_it_on_failure(+ self, _name, racing_claim, expected_marker+ ) -> None:+ # The claim has to be in place before the broker call: an earlier delivery reading the marker+ # in the gap would see none and post the report this one is about to post again. A publish+ # that then fails has to take the claim back down, since it names a task that will never run+ # and would otherwise silence the report for the marker's whole TTL.+ get_client().flushdb()+ report_id = "ddab8ee5-2bb8-4226-b145-6732d31dc344"+ channel = "CSCOUTS|#scout-findings"+ delivery_id = "b316c1d1-6901-49eb-8223-96d4df69f67f"+ key = _latest_report_delivery_key(report_id, 9, channel)+ observed: dict[str, bytes | None] = {}++ def _fail_to_publish(*args, **kwargs):+ observed["claim_at_publish"] = get_client().get(key)+ if racing_claim is not None:+ mark_latest_scout_report_delivery(report_id, racing_claim, 9, channel)+ raise RuntimeError("broker down")++ with (+ patch.object(deliver_scout_slack_output, "delay", side_effect=_fail_to_publish),+ patch("products.signals.backend.tasks.capture_exception"),+ ):+ enqueue_scout_slack_delivery(+ team_id=self.team.id,+ output_type="report",+ output_id=report_id,+ run_id="e3865391-bc89-44e6-86f7-2d4405627daf",+ delivery_id=delivery_id,+ integration_id=9,+ channel=channel,+ )++ claim_at_publish = observed["claim_at_publish"]+ assert claim_at_publish is not None and claim_at_publish.decode() == delivery_id+ marker = get_client().get(key)+ assert (marker.decode() if marker is not None else None) == expected_marker++ def test_task_skips_report_suppressed_during_rebuild(self) -> None:+ # A content edit triggers a rebuild, and the report is then suppressed during that second+ # render. The status recheck runs after every build, so the now-undeliverable report (and its+ # freshly minted image URLs) is skipped rather than posted.+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ builds = {"n": 0}++ def _build(report_arg, run_arg, *, delivery_id=None, render_budget=None):+ builds["n"] += 1+ if builds["n"] == 1:+ # Bump updated_at so the first build is treated as stale and a rebuild is triggered.+ edited = SignalReport.objects.get(id=report_arg.id)+ edited.title = "Checkout failures (edited)"+ edited.save()+ else:+ # The report is suppressed while the rebuild renders.+ SignalReport.objects.filter(id=report_arg.id).update(status=SignalReport.Status.SUPPRESSED)+ return [{"type": "header", "text": {"type": "plain_text", "text": "x"}}], "x"++ with (+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,+ patch(+ "products.signals.backend.scout_harness.slack_delivery.build_scout_report_slack_message",+ side_effect=_build,+ ),+ ):+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ )++ assert builds["n"] == 2+ fake_client.chat_postMessage.assert_not_called()++ @parameterized.expand(["invalid_blocks", "invalid_blocks_format"])+ def test_report_posts_without_its_charts_when_slack_rejects_them(self, error_code) -> None:+ # Slack fetches every image URL itself, so a chart it cannot reach takes the whole message+ # down with a code that is not permanent — the delivery would retry and then drop a report+ # that used to post as text. The prose and the report link go out instead.+ emission = self._make_emission()+ report = SignalReport.objects.create(+ team=self.team,+ status=SignalReport.Status.READY,+ title="Checkout failures",+ summary="Checkout failed",+ )+ integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)+ fake_client = MagicMock()+ fake_client.chat_postMessage.side_effect = [+ SlackApiError(message="rejected", response=FakeSlackResponse({"error": error_code})),+ FakeSlackResponse({"ts": "1785418710.000500"}),+ FakeSlackResponse({"ts": "1785418710.000600"}),+ ]+ chart_blocks = [+ {"type": "section", "text": {"type": "mrkdwn", "text": "*Signups*"}, "block_id": f"{PREFIX}1:0"},+ {"type": "image", "image_url": "https://img/1", "alt_text": "Signups", "block_id": f"{PREFIX}1:1"},+ ]++ with (+ patch("products.signals.backend.scout_harness.slack_delivery.SlackIntegration") as slack_integration,+ patch(+ "products.signals.backend.scout_harness.slack_delivery.build_scout_report_chart_blocks",+ return_value=chart_blocks,+ ),+ ):+ slack_integration.return_value.client = fake_client+ deliver_scout_slack_output.run(+ self.team.id,+ "report",+ str(report.id),+ str(emission.scout_run_id),+ "01864f4c-6957-7d3f-8d85-1d775e527265",+ integration.id,+ "CSCOUTS|#scout-findings",+ )++ rejected, resent = (call.kwargs["blocks"] for call in fake_client.chat_postMessage.call_args_list[:2])+ assert [b["type"] for b in rejected] == ["context", "header", "section", "section", "image", "actions"]+ assert [b["type"] for b in resent] == ["context", "header", "section", "actions"]+def test_task_retries_transient_delivery_failure(self) -> None:emission = self._make_emission()error = SlackApiError(diff --git a/products/signals/skills/authoring-scouts/references/report-contract.md b/products/signals/skills/authoring-scouts/references/report-contract.mdindex 9ef9eda15fb1..7ff142820ec4 100644--- a/products/signals/skills/authoring-scouts/references/report-contract.md+++ b/products/signals/skills/authoring-scouts/references/report-contract.md@@ -123,7 +123,8 @@ Reference each chart once: a repeated reference reads as pointing back at the chTwo references in one paragraph sit side by side, so put a pair you want compared in a paragraph of their own.A reference inside a code span, a table cell, or a heading has no room to draw — its chart falls to the end of the report instead.-**The summary has to read without the charts.** A report can also be delivered to Slack, where nothing draws and each reference degrades to the plain label it was given.+**The summary has to read without the charts.** A report can also be delivered to Slack, where each reference degrades to the plain label it was given and the charts follow the prose as images rather than sitting inline.+Only `InsightVizNode` and `SavedInsightNode` charts render there, at most three per report with referenced charts first; a `DataVisualizationNode` chart shows only in the inbox."Signups fell 60% over the week" survives that; "the chart below shows the drop" leaves a Slack reader with nothing.**Pin the window** to absolute dates wherever the node supports it, so a reader opening the report days later sees the data you wrote about rather than whatever a relative range resolves to then.diff --git a/tach.toml b/tach.tomlindex 678f58c70224..a41751ed3b6e 100644--- a/tach.toml+++ b/tach.toml@@ -743,6 +743,9 @@ depends_on = ["products.data_warehouse","products.error_tracking","products.experiments",+ # Facade-only: scout report Slack delivery renders report charts to PNG through the+ # exports facade and mints their delivery urls there.+ "products.exports","products.feature_flags",# Facade-only: the scout harness pre-resolves the external MCP servers a run's sandbox will# mount so the run prompt can name them.