Skip to content

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

fix(signals): thread scout reports by heading at any length (#90590)

posthog[bot]37d79a4166fd
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutSlackDestination.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutSlackDestination.tsx
index 5448ae61da86..ea817d571ce6 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerScoutSlackDestination.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerScoutSlackDestination.tsx
@@ -21,9 +21,9 @@ export function ScannerScoutSlackDestination({
// `output_destinations` also holds the webhook destination this scout provisioned, and replacing
// the object would drop that pointer while the destination kept delivering.
const destination = destinations?.slack
- // Threading is always on rather than a setting: it only takes effect when a report is too long
- // for one Slack section, and the alternative there is a clipped digest. A short one still posts
- // as a single message however many headings it has.
+ // Threading is always on rather than a setting: a scanner report is a heading-structured digest,
+ // so the channel gets a short lead with the sections in the thread, and a summary past one Slack
+ // section is never clipped. A report with no heading still posts as a single message.
const withSlack = (slack: SignalScoutOutputDestinationsApi['slack'] | undefined): void =>
onChange(
slack ? { ...destinations, slack: { ...slack, thread_reports: true } } : { ...destinations, slack: null }
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
index 6d401fed5e82..3d6727561451 100644
--- a/products/signals/backend/scout_harness/AGENTS.md
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -25,6 +25,7 @@ In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick e
- `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.
+ A threaded report splits its summary at the shallowest Markdown heading level that summary repeats at, so a sub-heading rides in its parent's reply and the thread mirrors the outline the reader sees in the inbox; a level used once is the report's own title rather than a seam, so the split descends past it. The split runs at any length, because a typical digest fits inside one Slack section and a length test leaves it in the channel as the wall of text threading exists to break up. A summary with no heading has no seam and stays one message, hard-chunked only past the section cap.
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.
diff --git a/products/signals/backend/scout_harness/slack_delivery.py b/products/signals/backend/scout_harness/slack_delivery.py
index 9e28e9e68498..94cc3ddbd771 100644
--- a/products/signals/backend/scout_harness/slack_delivery.py
+++ b/products/signals/backend/scout_harness/slack_delivery.py
@@ -23,7 +23,6 @@ from products.signals.backend.scout_harness.slack_charts import (
strip_chart_blocks,
)
from products.signals.backend.slack_formatting import (
- SLACK_SECTION_TEXT_MAX_LEN,
chunk_slack_mrkdwn,
escape_slack_mrkdwn,
markdown_to_slack_mrkdwn,
@@ -314,36 +313,21 @@ def build_scout_report_slack_message(
def _report_summary_chunks(report: SignalReport) -> list[str]:
- """Convert the report summary to mrkdwn, splitting into thread chunks only when it is too long.
-
- A summary that fits one Slack section stays a single chunk, so a short report posts as one message
- however many headings it has. A longer one splits at its own Markdown headings, packing adjacent
- sections into as few chunks as each fits in one Slack section, so the reply count tracks content
- size rather than heading count and the thread keeps its full tail. The split runs after
- `strip_chart_references` so a chart link never straddles two messages."""
+ """Convert the report summary to mrkdwn and split it into one chunk per heading section.
+
+ Called only for a threaded delivery. The first chunk leads the channel and each later one
+ becomes a reply, so the thread mirrors the report's outline at any length. Length is not the
+ test: a typical digest fits inside one Slack section, so a length test leaves it as one wall of
+ text. A summary with no headings has no seam and stays one chunk. A section too long for one
+ Slack section is hard-chunked on its line ends. The split runs after `strip_chart_references`
+ so a chart link never straddles two messages."""
summary_text = strip_chart_references((report.summary or "").strip())
- rendered = markdown_to_slack_mrkdwn(summary_text)
- if len(rendered) <= SLACK_SECTION_TEXT_MAX_LEN:
- return [rendered] if rendered else []
chunks: list[str] = []
- current = ""
for segment in split_markdown_by_headings(summary_text):
rendered_segment = markdown_to_slack_mrkdwn(segment.strip())
if not rendered_segment:
continue
- candidate = f"{current}\n\n{rendered_segment}" if current else rendered_segment
- if len(candidate) <= SLACK_SECTION_TEXT_MAX_LEN:
- current = candidate
- continue
- # The running block is full: flush it, then hard-chunk the oversized segment on its line ends.
- # Keep the last piece open so a following short section packs onto it instead of opening a new reply.
- if current:
- chunks.append(current)
- segment_chunks = chunk_slack_mrkdwn(rendered_segment)
- chunks.extend(segment_chunks[:-1])
- current = segment_chunks[-1] if segment_chunks else ""
- if current:
- chunks.append(current)
+ chunks.extend(chunk_slack_mrkdwn(rendered_segment))
return chunks
@@ -429,8 +413,10 @@ def build_scout_report_thread_slack_messages(
"""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, 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."""
+ report link. Every later chunk becomes a threaded reply, so the channel shows a short lead and
+ the thread holds the report's sections in order, with nothing clipped at the section cap. A
+ summary that opens with a heading puts that first section in the lead, so the channel never
+ shows a title-only stub."""
scout_name = _prettify_scout_name(run.skill_name)
header = _report_header(report)
lead_blocks: list[dict] = [
diff --git a/products/signals/backend/slack_formatting.py b/products/signals/backend/slack_formatting.py
index 2facfe6cc348..a69e1ed29b9d 100644
--- a/products/signals/backend/slack_formatting.py
+++ b/products/signals/backend/slack_formatting.py
@@ -1,8 +1,11 @@
from __future__ import annotations
import re
+from collections import Counter
from typing import TYPE_CHECKING
+from posthog.dataclasses import frozen
+
if TYPE_CHECKING:
from markdown_to_mrkdwn import SlackMarkdownConverter
@@ -125,16 +128,25 @@ def truncate_slack_section(text: str) -> str:
# A top-of-line ATX heading (`# `…`###### `). The scout writes its summary in Markdown, so its own
# headings are the natural seams to split a long report on for threaded Slack delivery.
-_MARKDOWN_HEADING_RE = re.compile(r"^#{1,6}[ \t]+\S")
+_MARKDOWN_HEADING_RE = re.compile(r"^(#{1,6})[ \t]+\S")
# Opens or closes a fenced code block (``` or ~~~, up to three leading spaces per CommonMark). A
# `# ` line inside a fence is code, not a heading: splitting there would orphan the fence and hand
# the snippet to the mrkdwn converter as prose.
_MARKDOWN_FENCE_RE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
-def _heading_line_offsets(text: str) -> list[int]:
- """Character offsets of the ATX heading lines, skipping any inside a fenced code block."""
- offsets: list[int] = []
+@frozen
+class _MarkdownHeading:
+ """Where an ATX heading starts in the text, and how deep it is. Both fields are plain ints, so a
+ tuple would let a call site read the level as an offset."""
+
+ offset: int
+ level: int
+
+
+def _markdown_headings(text: str) -> list[_MarkdownHeading]:
+ """Every ATX heading in the text, skipping any inside a fenced code block."""
+ headings: list[_MarkdownHeading] = []
fence: str | None = None # marker of the currently open fence, else None
offset = 0
for line in text.split("\n"):
@@ -145,24 +157,39 @@ def _heading_line_offsets(text: str) -> list[int]:
fence = None
elif fence_match:
fence = fence_match.group(1)
- elif _MARKDOWN_HEADING_RE.match(line):
- offsets.append(offset)
+ else:
+ heading_match = _MARKDOWN_HEADING_RE.match(line)
+ if heading_match:
+ headings.append(_MarkdownHeading(offset=offset, level=len(heading_match.group(1))))
offset += len(line) + 1 # +1 for the "\n" that split dropped
- return offsets
+ return headings
+
+
+def _split_heading_level(levels: list[int]) -> int:
+ """The shallowest heading level the text repeats at, else the shallowest level present.
+
+ A level that appears once is the summary's own title rather than a seam between sections, so
+ splitting there would return the whole summary as one segment."""
+ counts = Counter(levels)
+ repeated = sorted(level for level, count in counts.items() if count > 1)
+ return repeated[0] if repeated else min(levels)
def split_markdown_by_headings(text: str) -> list[str]:
- """Split a Markdown summary into the lead and one segment per heading.
+ """Split a Markdown summary into the lead and one segment per top-level heading.
- The first element is the text before the first heading (empty when the summary opens with one).
- Each later element is a heading and the body under it. Headings inside fenced code blocks are
- left in place, so a snippet is never split mid-fence. No content is dropped."""
+ The first element is the text before the first split point (empty when the summary opens with a
+ heading of that level). Each later element is a heading and everything under it, including its
+ sub-headings, so a segment holds the same block a reader folds shut. Headings inside fenced code
+ blocks are left in place, so a snippet is never split mid-fence. No content is dropped."""
text = text.strip()
if not text:
return []
- starts = _heading_line_offsets(text)
- if not starts:
+ headings = _markdown_headings(text)
+ if not headings:
return [text]
+ split_level = _split_heading_level([heading.level for heading in headings])
+ starts = [heading.offset for heading in headings if heading.level == split_level]
segments = [text[: starts[0]]]
for index, start in enumerate(starts):
end = starts[index + 1] if index + 1 < len(starts) else len(text)
diff --git a/products/signals/backend/test/test_scout_slack_delivery.py b/products/signals/backend/test/test_scout_slack_delivery.py
index de5a8dd9c421..af6378ef17a8 100644
--- a/products/signals/backend/test/test_scout_slack_delivery.py
+++ b/products/signals/backend/test/test_scout_slack_delivery.py
@@ -331,15 +331,16 @@ class TestScoutSlackDelivery(BaseTest):
assert not any(text.endswith("…") for text in section_texts)
assert any(tail_marker in text for text in section_texts)
- def test_threaded_short_report_with_headings_posts_a_single_message(self) -> None:
- # Threading must track content size, not heading count: a short report that fits one Slack
- # section posts as one message however many headings it has, so it never floods a thread.
+ def test_threaded_short_report_posts_one_reply_per_heading_section(self) -> None:
+ # The bug: threading only kicked in past the section cap, so a typical digest that fits one
+ # section posted as one wall of text. A report with headings now threads at any length, and
+ # a sub-heading rides in its parent's reply instead of opening one of its own.
emission = self._make_emission()
report = SignalReport.objects.create(
team=self.team,
status=SignalReport.Status.READY,
title="Checkout failures",
- summary="Lead line.\n\n## First\nshort body\n\n## Second\nshort body",
+ summary="Lead line.\n\n## First\nshort body\n\n### Detail\ndeeper body\n\n## Second\nshort body",
)
integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
fake_client = MagicMock()
@@ -358,30 +359,29 @@ class TestScoutSlackDelivery(BaseTest):
thread_reports=True,
)
- # Only the lead message and the unconditional @PostHog follow-up reply — no per-heading replies.
+ # The lead, one reply per top-level section, then the unconditional @PostHog follow-up.
calls = fake_client.chat_postMessage.call_args_list
- assert len(calls) == 2
+ assert len(calls) == 4
assert "thread_ts" not in calls[0].kwargs
- section_texts = [block["text"]["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "section"]
- assert len(section_texts) == 1
- assert "First" in section_texts[0] and "Second" in section_texts[0]
- assert calls[1].kwargs["blocks"][0]["type"] == "context"
-
- def test_threaded_report_packs_many_small_headings_into_few_replies(self) -> None:
- # A report past the section cap made of many small heading sections must pack adjacent
- # sections up to the Slack limit, not post one reply per heading. Otherwise the reply count
- # tracks heading count and a heading-dense report bursts a request per heading into the thread.
+ lead_sections = [block["text"]["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "section"]
+ assert lead_sections == ["Lead line."]
+ first_reply, second_reply = calls[1].kwargs, calls[2].kwargs
+ assert first_reply["thread_ts"] == "1785418710.000600"
+ assert "First" in first_reply["blocks"][0]["text"]["text"]
+ assert "Detail" in first_reply["blocks"][0]["text"]["text"]
+ assert "Second" not in first_reply["blocks"][0]["text"]["text"]
+ assert "Second" in second_reply["blocks"][0]["text"]["text"]
+ assert calls[3].kwargs["blocks"][0]["type"] == "context"
+
+ def test_threaded_report_without_headings_posts_a_single_message(self) -> None:
+ # Headings are the seams threading splits on. A summary with none has nothing to split, so it
+ # stays one channel message rather than being cut mid-prose.
emission = self._make_emission()
- heading_count = 50
- summary = "".join(
- f"## Section {i}\nBody line for section {i} with a bit of detail to add length.\n\n"
- for i in range(heading_count)
- )
report = SignalReport.objects.create(
team=self.team,
status=SignalReport.Status.READY,
title="Checkout failures",
- summary=summary,
+ summary="One paragraph of prose.\n\nAnd a second one, still without a heading.",
)
integration = Integration.objects.create(team=self.team, kind=Integration.IntegrationKind.SLACK)
fake_client = MagicMock()
@@ -400,15 +400,14 @@ class TestScoutSlackDelivery(BaseTest):
thread_reports=True,
)
+ # Only the lead message and the unconditional @PostHog follow-up reply.
calls = fake_client.chat_postMessage.call_args_list
- section_texts = [
- block["text"]["text"] for call in calls for block in call.kwargs["blocks"] if block["type"] == "section"
- ]
- # Packed: far fewer sections than headings, each within the cap, and no section is dropped.
- assert len(section_texts) < heading_count // 5
- assert all(len(text) <= 2900 for text in section_texts)
- joined = "\n".join(section_texts)
- assert all(f"Section {i}" in joined for i in range(heading_count))
+ assert len(calls) == 2
+ assert "thread_ts" not in calls[0].kwargs
+ section_texts = [block["text"]["text"] for block in calls[0].kwargs["blocks"] if block["type"] == "section"]
+ assert len(section_texts) == 1
+ assert "second one" in section_texts[0]
+ assert calls[1].kwargs["blocks"][0]["type"] == "context"
def test_reply_posted_regardless_of_ai_approval(self) -> None:
# The Slack follow-up invite is unconditional — no AI-approval gate on scout output.
diff --git a/products/signals/backend/test/test_slack_formatting.py b/products/signals/backend/test/test_slack_formatting.py
index d2d72e6b71bc..8d0d6504bf3d 100644
--- a/products/signals/backend/test/test_slack_formatting.py
+++ b/products/signals/backend/test/test_slack_formatting.py
@@ -95,12 +95,31 @@ class TestStripChartReferences(SimpleTestCase):
class TestSplitMarkdownByHeadings(SimpleTestCase):
def test_lead_precedes_one_segment_per_heading(self) -> None:
- summary = "Intro line.\n\n## First\nbody one\n\n### Second\nbody two"
+ summary = "Intro line.\n\n## First\nbody one\n\n## Second\nbody two"
segments = split_markdown_by_headings(summary)
assert segments[0].strip() == "Intro line."
assert segments[1].startswith("## First")
- assert segments[2].startswith("### Second")
+ assert segments[2].startswith("## Second")
+ assert len(segments) == 3
+
+ def test_sub_headings_stay_inside_their_parent_segment(self) -> None:
+ # A split at every level bursts a sub-headed report into a segment per sub-point, which the
+ # reader gets as one Slack reply each. The split runs at the level the summary repeats at.
+ summary = "## First\nbody one\n\n### Detail\nmore\n\n## Second\nbody two"
+ segments = split_markdown_by_headings(summary)
+
+ assert segments == ["", "## First\nbody one\n\n### Detail\nmore\n\n", "## Second\nbody two"]
+
+ def test_a_lone_top_heading_is_not_a_split_point(self) -> None:
+ # A level used once is the summary's own title. Splitting there returns everything under it
+ # as a single segment, which is the wall of text threading exists to break up.
+ summary = "# Title\n\nIntro line.\n\n## First\nbody one\n\n## Second\nbody two"
+ segments = split_markdown_by_headings(summary)
+
+ assert segments[0].strip() == "# Title\n\nIntro line."
+ assert segments[1].startswith("## First")
+ assert segments[2].startswith("## Second")
assert len(segments) == 3
def test_leading_heading_yields_empty_lead(self) -> None:
diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx
index c3cd76521505..795be3ad1041 100644
--- a/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx
+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutSlackDestination.tsx
@@ -132,8 +132,8 @@ export function ScoutSlackDestination({
checked={destination?.thread_reports ?? false}
onChange={setThreadReports}
disabledReason={disabledReason}
- label="Post long reports as a thread"
- tooltip="Post a short lead in the channel and split the rest by the report's headings into replies, so a long summary is not cut off."
+ label="Post reports as a thread"
+ tooltip="Post a short lead in the channel and split the rest by the report's headings into replies, so the channel stays readable and a long summary is not cut off."
bordered
/>
) : null}