: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
fix(alerts): backfill the chart block into older Slack destinations (#90273)
posthog[bot]9667f71a748e
diff --git a/products/alerts/backend/destination_backfill.py b/products/alerts/backend/destination_backfill.pynew file mode 100644index 000000000000..ef39e65e3ecb--- /dev/null+++ b/products/alerts/backend/destination_backfill.py@@ -0,0 +1,164 @@+"""Give older Slack insight-alert destinations the chart block that new ones get.++A destination keeps its own copy of the Slack blocks, taken from the sub-template at the moment+somebody created it. Destinations created before the chart shipped therefore still post the plain+divider that the chart block replaced, and no amount of alert firing changes that on its own.++The rewrite swaps that one divider and leaves everything else as it was. A destination whose+blocks no longer match the shape the sub-template produced is treated as hand-edited and skipped,+so nobody's customized message is overwritten.+"""++import json+from collections.abc import Sequence+from typing import Any+from uuid import UUID++from django.db import transaction+from django.db.models import QuerySet++import structlog++from posthog.cdp.validation import generate_template_bytecode+from posthog.dataclasses import frozen+from posthog.plugins.plugin_server_api import reload_hog_functions_on_workers+from posthog.tasks.alerts.utils import INSIGHT_ALERT_FIRING_EVENT++from products.alerts.backend.destination_configs import DESTINATION_SPECS, DestinationType+from products.cdp.backend.models.hog_functions.hog_function import HogFunction++logger = structlog.get_logger(__name__)++SLACK_TEMPLATE_ID = DESTINATION_SPECS[DestinationType.SLACK].template_id++DIVIDER_BLOCK = {"type": "divider"}++# Byte-for-byte the block the sub-template now writes, so a repaired destination and a freshly+# created one are indistinguishable. Keep it in step with the insight-alert-firing Slack entry in+# frontend/src/scenes/hog-functions/sub-templates/sub-templates.ts.+INSIGHT_CHART_BLOCK = "{event.properties.insight_chart_url ? {'type': 'image', 'image_url': event.properties.insight_chart_url, 'alt_text': 'Insight chart'} : {'type': 'divider'}}"+++@frozen+class ChartBlockBackfill:+ scanned: int+ repaired: int+ already_current: int+ left_alone: int+ uncompilable: int+++def insight_alert_slack_destinations(team_ids: Sequence[int] | None = None) -> QuerySet[HogFunction]:+ destinations = HogFunction.objects.filter(+ deleted=False,+ template_id=SLACK_TEMPLATE_ID,+ filters__events__contains=[{"id": INSIGHT_ALERT_FIRING_EVENT, "type": "events"}],+ ).order_by("team_id", "id")+ if team_ids is not None:+ destinations = destinations.filter(team_id__in=team_ids)+ return destinations+++def mentions_chart(blocks: Any) -> bool:+ """Whether these blocks already do something with the chart, however they came by it."""+ return "insight_chart_url" in json.dumps(blocks, default=str)+++def blocks_with_chart(blocks: Any) -> list[Any] | None:+ """The blocks with the chart in place of the divider, or None when this destination is not one+ the sub-template produced and so is not ours to rewrite."""+ if not isinstance(blocks, list) or mentions_chart(blocks):+ return None+ actions_index = next(+ (index for index, block in enumerate(blocks) if isinstance(block, dict) and block.get("type") == "actions"),+ None,+ )+ # The divider only ever sat directly above the buttons. Anywhere else it is somebody's own.+ if actions_index is None or actions_index == 0 or blocks[actions_index - 1] != DIVIDER_BLOCK:+ return None+ return [*blocks[: actions_index - 1], INSIGHT_CHART_BLOCK, *blocks[actions_index:]]+++def backfill_insight_alert_chart_blocks(+ *,+ team_ids: Sequence[int] | None = None,+ limit: int | None = None,+ batch_size: int = 100,+ apply: bool = False,+) -> ChartBlockBackfill:+ destinations = insight_alert_slack_destinations(team_ids)+ if limit is not None:+ destinations = destinations[:limit]++ scanned = already_current = left_alone = uncompilable = 0+ repaired: list[HogFunction] = []+ ids_by_team: dict[int, list[UUID]] = {}++ for destination in destinations:+ scanned += 1+ raw_blocks_input = (destination.inputs or {}).get("blocks")+ blocks_input: dict[str, Any] = raw_blocks_input if isinstance(raw_blocks_input, dict) else {}+ blocks = blocks_input.get("value")++ if mentions_chart(blocks):+ already_current += 1+ continue++ # Liquid blocks are rendered by the worker rather than compiled, so the hog expression the+ # chart block is written in would reach Slack as literal text.+ is_hog_templated = blocks_input.get("templating", "hog") == "hog"+ upgraded = blocks_with_chart(blocks) if is_hog_templated else None+ if upgraded is None:+ left_alone += 1+ logger.info(+ "Leaving Slack insight-alert blocks alone",+ team_id=destination.team_id,+ hog_function_id=str(destination.id),+ templating=blocks_input.get("templating"),+ )+ continue++ try:+ # The worker renders the stored bytecode, not the value, so a value written without a+ # matching recompile would keep posting the old blocks.+ bytecode = generate_template_bytecode(upgraded, set(), function_type=destination.type)+ except Exception:+ # Recompiling covers the whole block list, so an edit elsewhere in it that the compiler+ # now rejects lands here. One destination must not stop the sweep.+ uncompilable += 1+ logger.exception(+ "Could not recompile Slack insight-alert blocks",+ team_id=destination.team_id,+ hog_function_id=str(destination.id),+ )+ continue++ destination.inputs = {+ **(destination.inputs or {}),+ "blocks": {**blocks_input, "value": upgraded, "bytecode": bytecode},+ }+ repaired.append(destination)+ ids_by_team.setdefault(destination.team_id, []).append(destination.id)++ if apply and repaired:+ with transaction.atomic():+ HogFunction.objects.bulk_update(repaired, ["inputs"], batch_size=batch_size)+ for team_id, hog_function_ids in ids_by_team.items():+ # bulk_update skips post_save, so the running workers need telling by hand.+ _reload_after_commit(team_id=team_id, hog_function_ids=hog_function_ids)++ return ChartBlockBackfill(+ scanned=scanned,+ repaired=len(repaired),+ already_current=already_current,+ left_alone=left_alone,+ uncompilable=uncompilable,+ )+++def _reload_after_commit(*, team_id: int, hog_function_ids: Sequence[UUID]) -> None:+ serialized_ids = sorted(str(hog_function_id) for hog_function_id in hog_function_ids)+ transaction.on_commit(+ lambda: reload_hog_functions_on_workers(team_id=team_id, hog_function_ids=serialized_ids),+ robust=True,+ )diff --git a/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.py b/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.pynew file mode 100644index 000000000000..448e69c0c189--- /dev/null+++ b/products/alerts/backend/management/commands/backfill_insight_alert_slack_chart_block.py@@ -0,0 +1,65 @@+"""Add the insight chart to Slack insight-alert destinations that predate it.++Every destination stores its own copy of the Slack blocks, so the ones created before the chart+shipped keep posting a divider where the chart now goes. This finds them and rewrites that block.+Destinations whose blocks have been edited by hand are reported and left alone.++Reports by default. Region-agnostic - run it once per region, narrowing by team first.++ python manage.py backfill_insight_alert_slack_chart_block # dry run+ python manage.py backfill_insight_alert_slack_chart_block --team-ids 2 --apply+ python manage.py backfill_insight_alert_slack_chart_block --apply+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++from products.alerts.backend.destination_backfill import backfill_insight_alert_chart_blocks+++class Command(BaseCommand):+ help = "Backfill the insight chart block into Slack insight-alert destinations created before it shipped"++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-ids", type=str, default=None, help="Comma-separated team ids to limit to")+ parser.add_argument("--limit", type=int, default=None, help="Look at no more than this many destinations")+ parser.add_argument("--batch-size", type=int, default=100, help="Rows per UPDATE (default: 100)")+ parser.add_argument("--apply", action="store_true", default=False, help="Write them (default: report only)")++ def handle(self, *args: Any, **options: Any) -> None:+ apply: bool = options["apply"]+ result = backfill_insight_alert_chart_blocks(+ team_ids=_parse_team_ids(options["team_ids"]),+ limit=options["limit"],+ batch_size=options["batch_size"],+ apply=apply,+ )++ counts = [+ ("repaired" if apply else "would repair", result.repaired),+ ("already current", result.already_current),+ ("left as-is", result.left_alone),+ ]+ if result.uncompilable:+ counts.append(("would not compile, see the logs", result.uncompilable))++ width = max(len(label) for label, _ in counts)+ self.stdout.write(f"Checked {result.scanned} Slack insight-alert destination(s).")+ for label, count in counts:+ self.stdout.write(f" {label.ljust(width)} {count}")++ if not apply:+ self.stdout.write("Dry run. Re-run with --apply to write them.")+++def _parse_team_ids(raw: str | None) -> list[int] | None:+ if raw is None:+ return None+ try:+ team_ids = [int(team_id) for team_id in raw.split(",") if team_id.strip()]+ except ValueError:+ raise CommandError("--team-ids takes comma-separated integers, for example --team-ids 2,7")+ if not team_ids:+ raise CommandError("--team-ids needs at least one team id")+ return team_idsdiff --git a/products/alerts/backend/test/test_destination_backfill.py b/products/alerts/backend/test/test_destination_backfill.pynew file mode 100644index 000000000000..18b6a013bb5f--- /dev/null+++ b/products/alerts/backend/test/test_destination_backfill.py@@ -0,0 +1,210 @@+from typing import Any+from uuid import uuid4++from posthog.test.base import BaseTest++from django.test import SimpleTestCase++from parameterized import parameterized++from posthog.models.team.team import Team++from products.alerts.backend.destination_backfill import (+ INSIGHT_CHART_BLOCK,+ backfill_insight_alert_chart_blocks,+ blocks_with_chart,+)+from products.cdp.backend.models.hog_functions.hog_function import HogFunction++HEADER_BLOCK = {"type": "header", "text": {"type": "plain_text", "text": "Alert firing"}}+CONTEXT_BLOCK = {"type": "context", "elements": [{"type": "mrkdwn", "text": "Project"}]}+ACTIONS_BLOCK = {"type": "actions", "elements": [{"type": "button", "url": "{project.url}"}]}++PRE_CHART_BLOCKS = [HEADER_BLOCK, CONTEXT_BLOCK, {"type": "divider"}, ACTIONS_BLOCK]+++SLACK_INPUTS_SCHEMA = [+ {"key": "slack_workspace", "type": "integration"},+ {"key": "channel", "type": "string"},+ {"key": "blocks", "type": "json"},+]+++def _inputs(destination: HogFunction) -> dict[str, Any]:+ inputs = destination.inputs+ assert inputs is not None+ return inputs+++def slack_inputs(blocks: list[Any]) -> dict[str, Any]:+ return {+ "blocks": {"value": blocks, "bytecode": ["_H", 1], "order": 0},+ "channel": {"value": "C-ENG", "order": 1},+ "slack_workspace": {"value": 1, "order": 2},+ }+++class TestBlocksWithChart(SimpleTestCase):+ @parameterized.expand(+ [+ ("no divider above the buttons", [HEADER_BLOCK, CONTEXT_BLOCK, ACTIONS_BLOCK]),+ ("divider is not the last block before the buttons", [{"type": "divider"}, CONTEXT_BLOCK, ACTIONS_BLOCK]),+ ("divider carries extra keys", [{"type": "divider", "block_id": "mine"}, ACTIONS_BLOCK]),+ ("no buttons at all", [HEADER_BLOCK, {"type": "divider"}]),+ (+ "a chart was added by hand",+ [+ {"type": "image", "image_url": "{event.properties.insight_chart_url}", "alt_text": "Chart"},+ {"type": "divider"},+ ACTIONS_BLOCK,+ ],+ ),+ ("buttons come first", [ACTIONS_BLOCK, {"type": "divider"}]),+ ("blocks are not a list", {"type": "divider"}),+ ("blocks are missing", None),+ ]+ )+ def test_leaves_blocks_it_does_not_recognize_alone(self, _name: str, blocks: Any) -> None:+ assert blocks_with_chart(blocks) is None++ def test_replaces_the_divider_directly_above_the_buttons(self) -> None:+ assert blocks_with_chart(PRE_CHART_BLOCKS) == [+ HEADER_BLOCK,+ CONTEXT_BLOCK,+ INSIGHT_CHART_BLOCK,+ ACTIONS_BLOCK,+ ]++ def test_a_repaired_destination_is_no_longer_a_candidate(self) -> None:+ assert blocks_with_chart(blocks_with_chart(PRE_CHART_BLOCKS)) is None+++class TestBackfillInsightAlertChartBlocks(BaseTest):+ def _destination(+ self,+ *,+ blocks: list[Any] | None = None,+ template_id: str = "template-slack",+ event_id: str = "$insight_alert_firing",+ deleted: bool = False,+ team: Team | None = None,+ ) -> HogFunction:+ return HogFunction.objects.create(+ team=team or self.team,+ name="Alert → Slack",+ type="internal_destination",+ hog="return 1",+ enabled=True,+ deleted=deleted,+ template_id=template_id,+ inputs_schema=SLACK_INPUTS_SCHEMA,+ inputs=slack_inputs(blocks if blocks is not None else list(PRE_CHART_BLOCKS)),+ filters={+ "events": [{"id": event_id, "type": "events"}],+ "properties": [{"key": "alert_id", "value": str(uuid4()), "operator": "exact", "type": "event"}],+ },+ )++ def _stored_blocks(self, destination: HogFunction) -> Any:+ destination.refresh_from_db()+ return _inputs(destination)["blocks"]++ def test_apply_rewrites_the_blocks_and_their_bytecode(self) -> None:+ destination = self._destination()++ with self.captureOnCommitCallbacks(execute=True):+ result = backfill_insight_alert_chart_blocks(apply=True)++ assert (result.scanned, result.repaired, result.already_current, result.left_alone) == (1, 1, 0, 0)+ stored = self._stored_blocks(destination)+ assert stored["value"][2] == INSIGHT_CHART_BLOCK+ # A value written without a matching recompile would keep posting the old blocks.+ assert stored["bytecode"] != ["_H", 1]+ assert stored["order"] == 0++ def test_dry_run_reports_the_work_without_doing_it(self) -> None:+ destination = self._destination()++ result = backfill_insight_alert_chart_blocks()++ assert result.repaired == 1+ assert self._stored_blocks(destination)["value"] == PRE_CHART_BLOCKS++ def test_running_it_twice_changes_nothing_the_second_time(self) -> None:+ self._destination()++ with self.captureOnCommitCallbacks(execute=True):+ backfill_insight_alert_chart_blocks(apply=True)+ second = backfill_insight_alert_chart_blocks(apply=True)++ assert (second.scanned, second.repaired, second.already_current) == (1, 0, 1)++ def test_hand_edited_blocks_are_counted_but_not_written(self) -> None:+ custom = [HEADER_BLOCK, ACTIONS_BLOCK]+ destination = self._destination(blocks=custom)++ with self.captureOnCommitCallbacks(execute=True):+ result = backfill_insight_alert_chart_blocks(apply=True)++ assert (result.repaired, result.left_alone) == (0, 1)+ assert self._stored_blocks(destination)["value"] == custom++ def test_liquid_templated_blocks_are_left_alone(self) -> None:+ # A hog expression in liquid blocks would reach Slack as literal text.+ destination = self._destination()+ _inputs(destination)["blocks"]["templating"] = "liquid"+ destination.save(update_fields=["inputs"])++ with self.captureOnCommitCallbacks(execute=True):+ result = backfill_insight_alert_chart_blocks(apply=True)++ assert (result.repaired, result.left_alone) == (0, 1)+ assert self._stored_blocks(destination)["value"] == PRE_CHART_BLOCKS++ @parameterized.expand(+ [+ ("a webhook destination", {"template_id": "template-webhook"}),+ ("a Slack destination for another alert product", {"event_id": "$logs_alert_firing"}),+ ("a deleted destination", {"deleted": True}),+ ]+ )+ def test_skips(self, _name: str, overrides: dict[str, Any]) -> None:+ self._destination(**overrides)++ result = backfill_insight_alert_chart_blocks()++ assert result.scanned == 0++ def test_one_destination_that_will_not_compile_does_not_stop_the_sweep(self) -> None:+ # A hyphenated property is the everyday way an edited block stops compiling.+ broken_header = {"type": "header", "text": {"type": "plain_text", "text": "{event.properties.some-prop}"}}+ broken = self._destination(blocks=[broken_header, {"type": "divider"}, ACTIONS_BLOCK])+ healthy = self._destination()++ with self.captureOnCommitCallbacks(execute=True):+ result = backfill_insight_alert_chart_blocks(apply=True)++ assert (result.scanned, result.repaired, result.uncompilable) == (2, 1, 1)+ assert self._stored_blocks(healthy)["value"][2] == INSIGHT_CHART_BLOCK+ assert self._stored_blocks(broken)["value"][1] == {"type": "divider"}++ def test_limit_caps_how_many_destinations_the_sweep_touches(self) -> None:+ self._destination()+ self._destination()++ with self.captureOnCommitCallbacks(execute=True):+ result = backfill_insight_alert_chart_blocks(limit=1, apply=True)++ assert (result.scanned, result.repaired) == (1, 1)++ def test_team_ids_narrows_the_backfill(self) -> None:+ other_team = Team.objects.create(organization=self.organization, name="Other")+ mine = self._destination()+ theirs = self._destination(team=other_team)++ with self.captureOnCommitCallbacks(execute=True):+ result = backfill_insight_alert_chart_blocks(team_ids=[self.team.id], apply=True)++ assert (result.scanned, result.repaired) == (1, 1)+ assert self._stored_blocks(mine)["value"][2] == INSIGHT_CHART_BLOCK+ assert self._stored_blocks(theirs)["value"] == PRE_CHART_BLOCKS