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(replay-vision): keep group summaries inside one clean slack message (#70514)

Kim Svatos Duganac3b989e8f65
diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.py
index 03d4dc3e4cfd..d7d05b2cf2fb 100644
--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py
+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py
@@ -55,8 +55,11 @@ MAX_OBSERVATIONS = 100
# cap guards against) samples across its newest SAMPLE_SCAN_LIMIT observations rather than every row,
# so this activity can't materialize an unbounded id list.
SAMPLE_SCAN_LIMIT = 10_000
-# Stay comfortably under Slack's ~40k message-text limit; truncate the tail if a report runs long.
-SLACK_TEXT_MAX = 38_000
+# Keep the whole report inside ONE Slack message. Slack's hard API limit is ~40k characters, but
+# anything over ~4,000 gets auto-split into multiple messages at arbitrary positions — which cuts
+# `<url|[N]>` citation tokens in half and renders both halves as garbage. The full report is always
+# available in-app, so truncate with a pointer instead of risking the split.
+SLACK_TEXT_MAX = 3_900
_SYSTEM_PROMPT = (
"You are summarizing automated observations of user session recordings into one concise group summary "
@@ -86,9 +89,10 @@ _MARKDOWN_BOLD_RE = re.compile(r"\*\*([^*]+)\*\*")
# both resolve them to observation links. The captured group is the 1-based observation number.
_OBS_CITATION_RE = re.compile(r"\[obs (\d+)\]")
# Cap adjacent citations on the stored report so an over-cited theme renders a representative handful, not a
-# wall of links. Cross-section variety stays the prompt's job.
+# wall of links. Cross-section variety stays the prompt's job. Markers count as one run across any mix of
+# whitespace/comma/semicolon separators — the model writes `[obs 1], [obs 4]` as often as `[obs 1] [obs 4]`.
_MAX_CITATIONS_PER_RUN = 6
-_CITATION_RUN_RE = re.compile(r"\[obs \d+\](?:\s*\[obs \d+\])+")
+_CITATION_RUN_RE = re.compile(r"\[obs \d+\](?:[\s,;]*\[obs \d+\])+")
def _cap_citation_runs(markdown: str) -> str:
@@ -470,8 +474,16 @@ def _markdown_to_slack(markdown: str, *, team_id: int, observation_ids: list[str
text = _MARKDOWN_HEADING_RE.sub(lambda m: f"*{m.group(1)}*", text)
text = _MARKDOWN_BOLD_RE.sub(lambda m: f"*{m.group(1)}*", text)
if len(text) > SLACK_TEXT_MAX:
- text = text[:SLACK_TEXT_MAX].rstrip() + "\n\n…_(truncated — see the full group summary in PostHog)_"
- # Re-run link sanitization: truncation may have split a defanged `` `url` `` code span,
- # dropping the closing backtick and re-exposing the bare URL to Slack's auto-unfurler.
+ cut = text[:SLACK_TEXT_MAX]
+ # Back up to the last line break so the cut can't land inside a `<url|[N]>` link or a
+ # defanged `` `url` `` code span — neither contains a newline. Only if the slice is one
+ # giant line, fall back to cutting just before an unterminated `<...` token.
+ newline = cut.rfind("\n")
+ if newline > 0:
+ cut = cut[:newline]
+ elif cut.rfind("<") > cut.rfind(">"):
+ cut = cut[: cut.rfind("<")]
+ text = cut.rstrip() + "\n\n…_(truncated — see the full group summary in PostHog)_"
+ # Re-run link sanitization as a belt-and-braces guard against any re-exposed bare URL.
text = strip_external_links_markdown(text)
return text
diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.py
index 48af5a50c40f..0bdb35825ca0 100644
--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py
+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py
@@ -1,5 +1,6 @@
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
+from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import patch
@@ -159,16 +160,23 @@ class TestVisionActionSynthesis(BaseTest):
self.assertNotIn("[9]", run.output["slack"])
self.assertNotIn("[obs 9]", run.output["slack"])
- def test_caps_runaway_citation_lists(self) -> None:
+ @parameterized.expand(
+ [
+ ("space_separated", " "),
+ ("comma_separated", ", "),
+ ]
+ )
+ def test_caps_runaway_citation_lists(self, _label: str, separator: str) -> None:
# A theme the model backs with many recordings must not render a wall of citations: an adjacent run
# is trimmed to a representative handful, keeping the first few. Guards both the in-app markdown and
- # (once it renders links) the Slack payload, since the cap runs on the stored report.
+ # (once it renders links) the Slack payload, since the cap runs on the stored report. The model
+ # separates citations with commas as often as spaces — both shapes must count as one run.
for i in range(10):
self._observation(f"obs {i}", session_id=f"s{i}")
action = self._action()
run = self._run_for(action)
- citations = " ".join(f"[obs {i}]" for i in range(1, 10)) # 9 adjacent citations
+ citations = separator.join(f"[obs {i}]" for i in range(1, 10)) # 9 adjacent citations
self._synthesize(action, run, llm_content=f"Users hit friction across this flow {citations}.")
run.refresh_from_db()
@@ -616,9 +624,23 @@ class TestMarkdownToSlack(BaseTest):
self.assertNotIn("**", out)
def test_truncates_long_text(self) -> None:
+ # Slack auto-splits messages over ~4k characters, so the payload must always fit one message.
out = _markdown_to_slack("x" * 50_000, team_id=self.team.id, observation_ids=[])
- self.assertLessEqual(len(out), 39_000)
+ self.assertLessEqual(len(out), 4_000)
+ self.assertIn("truncated", out)
+
+ def test_truncation_does_not_split_a_citation_link(self) -> None:
+ # A citation link straddling the cut point must be dropped whole, not cut in half — a dangling
+ # `<https://…` renders as garbage in Slack. The cut backs up to the previous line break.
+ from products.replay_vision.backend.temporal.vision_actions.synthesis import SLACK_TEXT_MAX
+
+ obs_id = str(uuid4())
+ text = "a" * (SLACK_TEXT_MAX - 50) + "\n" + "More friction at checkout [obs 1] and beyond. " * 5
+ out = _markdown_to_slack(text, team_id=self.team.id, observation_ids=[obs_id])
+ self.assertLessEqual(len(out), 4_000)
self.assertIn("truncated", out)
+ self.assertEqual(out.count("<"), out.count(">"))
+ self.assertNotIn(obs_id[:8], out) # the straddling link is gone entirely, not half-emitted
def test_truncation_does_not_re_expose_defanged_url(self) -> None:
# A non-PostHog URL straddling SLACK_TEXT_MAX must stay defanged after truncation.