: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(tasks): chunk long slack relay messages instead of truncating (#61673)
Vojta Bartoš46381dd9ac68
diff --git a/products/tasks/backend/temporal/slack_relay/activities.py b/products/tasks/backend/temporal/slack_relay/activities.pyindex e414d963bf46..24396d3e7a17 100644--- a/products/tasks/backend/temporal/slack_relay/activities.py+++ b/products/tasks/backend/temporal/slack_relay/activities.py@@ -113,6 +113,114 @@ def _strip_inline_markdown(cell: str) -> str:return cell.strip()+# Slack renders text above ~4000 characters as a "Show more" affordance and silently truncates;+# splitting at 3500 leaves comfortable headroom for the mention prefix and code-fence overhead.+SLACK_MESSAGE_TEXT_LIMIT = 3500++_FENCED_CODE_RE = re.compile(r"```([^\n]*)\n([\s\S]*?)\n```")+++def _split_markdown_for_slack(text: str, limit: int = SLACK_MESSAGE_TEXT_LIMIT) -> list[str]:+ """Split raw markdown into Slack-sized chunks at safe structural boundaries.++ Splits prefer paragraph (``\\n\\n``) and line (``\\n``) boundaries, then a hard+ character break as a last resort. Fenced code blocks that cross a chunk+ boundary are closed at the end of one chunk and reopened (with the same+ language hint) at the start of the next so each chunk is a self-contained+ markdown document. Callers convert each chunk to Slack mrkdwn independently;+ that ordering means a hard char break inside an inline span like ``**bold**``+ or ``[text](url)`` leaves the broken halves as literal text rather than+ producing dangling unbalanced markers in the rendered output.+ """+ if len(text) <= limit:+ return [text]++ segments: list[tuple[str, str, str]] = []+ pos = 0+ for match in _FENCED_CODE_RE.finditer(text):+ if match.start() > pos:+ segments.append(("text", "", text[pos : match.start()]))+ segments.append(("code", match.group(1), match.group(2)))+ pos = match.end()+ if pos < len(text):+ segments.append(("text", "", text[pos:]))++ chunks: list[str] = []+ current = ""++ def flush() -> None:+ nonlocal current+ stripped = current.rstrip()+ if stripped:+ chunks.append(stripped)+ current = ""++ def append_atom(atom: str, separator: str = "") -> None:+ """Append ``atom`` to the current chunk, flushing first if it would overflow."""+ nonlocal current+ candidate = current + (separator if current else "") + atom+ if len(candidate) <= limit:+ current = candidate+ return+ flush()+ current = atom++ def split_long_line(line: str) -> None:+ """Hard-split a single line that is itself longer than the limit."""+ nonlocal current+ remaining = line+ while len(remaining) > limit:+ flush()+ chunks.append(remaining[:limit])+ remaining = remaining[limit:]+ if remaining:+ append_atom(remaining, separator="\n")++ for kind, lang, body in segments:+ if kind == "text":+ for paragraph_index, paragraph in enumerate(body.split("\n\n")):+ separator = "\n\n" if paragraph_index > 0 or current else ""+ if len(current) + len(separator) + len(paragraph) <= limit:+ current = current + separator + paragraph+ continue+ if len(paragraph) <= limit:+ append_atom(paragraph, separator="\n\n")+ continue+ # Paragraph alone overflows — fall back to per-line packing.+ for line_index, line in enumerate(paragraph.split("\n")):+ sep = "\n" if line_index > 0 or current else ""+ if len(current) + len(sep) + len(line) <= limit:+ current = current + sep + line+ elif len(line) <= limit:+ append_atom(line, separator="\n")+ else:+ split_long_line(line)+ continue++ fence_open = f"```{lang}\n" if lang else "```\n"+ fence_close = "\n```"+ full_block = f"{fence_open}{body}{fence_close}"+ if len(full_block) <= limit:+ append_atom(full_block, separator="\n\n")+ continue+ # Block itself overflows — emit it across multiple fenced chunks, line-aligned.+ flush()+ overhead = len(fence_open) + len(fence_close)+ room = max(1, limit - overhead)+ cursor = 0+ while cursor < len(body):+ end = min(cursor + room, len(body))+ if end < len(body):+ newline = body.rfind("\n", cursor, end)+ if newline > cursor:+ end = newline+ chunks.append(f"{fence_open}{body[cursor:end]}{fence_close}")+ cursor = end + 1 if end < len(body) and body[end] == "\n" else end++ flush()+ return chunks++@dataclassclass RelaySlackMessageInput:run_id: str@@ -151,11 +259,11 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:logger.info("slack_relay_empty_text", run_id=input.run_id, relay_id=input.relay_id)return- text = _markdown_to_slack_mrkdwn(text)-- SLACK_MESSAGE_TEXT_LIMIT = 3900- if len(text) > SLACK_MESSAGE_TEXT_LIMIT:- text = f"{text[: SLACK_MESSAGE_TEXT_LIMIT - 3]}..."+ # Split the raw markdown first, then convert each chunk independently. Converting+ # per-chunk means an inline span broken by a hard char split (e.g. ``**bold**``+ # halved) stays literal in the output instead of leaving dangling Slack-mrkdwn+ # markers that would garble the rendering of surrounding text.+ chunks = [_markdown_to_slack_mrkdwn(chunk) for chunk in _split_markdown_for_slack(text)]context = SlackThreadContext(integration_id=mapping.integration_id,@@ -169,7 +277,9 @@ def relay_slack_message(input: RelaySlackMessageInput) -> None:mention_prefix = f"<@{mapping.mentioning_slack_user_id}> " if mapping.mentioning_slack_user_id else ""if input.delete_progress:handler.delete_progress()- handler.post_thread_message(f"{mention_prefix}{text}")+ for index, chunk in enumerate(chunks):+ prefix = mention_prefix if index == 0 else ""+ handler.post_thread_message(f"{prefix}{chunk}")if input.reaction_emoji is not None:handler.update_reaction(input.reaction_emoji)diff --git a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py b/products/tasks/backend/temporal/slack_relay/tests/test_activities.pyindex 4e55b2ea17e1..193dcfe01791 100644--- a/products/tasks/backend/temporal/slack_relay/tests/test_activities.py+++ b/products/tasks/backend/temporal/slack_relay/tests/test_activities.py@@ -15,8 +15,10 @@ from posthog.models.user import Userfrom products.slack_app.backend.models import SlackThreadTaskMappingfrom products.tasks.backend.models import Task, TaskRunfrom products.tasks.backend.temporal.slack_relay.activities import (+ SLACK_MESSAGE_TEXT_LIMIT,RelaySlackMessageInput,_markdown_to_slack_mrkdwn,+ _split_markdown_for_slack,relay_slack_message,)@@ -154,3 +156,173 @@ class TestMarkdownToSlackMrkdwn(unittest.TestCase):md = "| a | b |\n| c | d |"result = _markdown_to_slack_mrkdwn(md)assert "```" not in result+++class TestSplitTextForSlack(TestCase):+ def test_short_text_returns_single_chunk(self):+ assert _split_markdown_for_slack("hello world") == ["hello world"]++ def test_each_chunk_under_limit(self):+ paragraph = ("word " * 200).strip()+ text = "\n\n".join([paragraph] * 10)+ chunks = _split_markdown_for_slack(text)+ assert len(chunks) > 1+ for chunk in chunks:+ assert len(chunk) <= SLACK_MESSAGE_TEXT_LIMIT++ def test_split_prefers_paragraph_boundary(self):+ paragraph = ("alpha " * 400).strip() # ~2400 chars per paragraph+ text = f"{paragraph}\n\n{paragraph}"+ chunks = _split_markdown_for_slack(text)+ assert len(chunks) == 2+ assert chunks[0] == paragraph+ assert chunks[1] == paragraph++ def test_split_falls_back_to_line_within_paragraph(self):+ line = ("alpha " * 100).strip() # ~600 chars+ text = "\n".join([line] * 10) # single paragraph, ~6000 chars+ chunks = _split_markdown_for_slack(text)+ assert len(chunks) >= 2+ for chunk in chunks:+ for chunk_line in chunk.split("\n"):+ assert chunk_line == line++ def test_hard_breaks_single_long_line(self):+ line = "x" * (SLACK_MESSAGE_TEXT_LIMIT + 500)+ chunks = _split_markdown_for_slack(line)+ assert len(chunks) == 2+ assert all(len(chunk) <= SLACK_MESSAGE_TEXT_LIMIT for chunk in chunks)+ assert "".join(chunks) == line++ def test_oversized_code_block_keeps_fences_balanced(self):+ body_lines = [f"line {i:04d}" for i in range(800)]+ body = "\n".join(body_lines)+ text = f"```python\n{body}\n```"+ chunks = _split_markdown_for_slack(text)+ assert len(chunks) >= 2+ for chunk in chunks:+ assert chunk.startswith("```python\n")+ assert chunk.endswith("\n```")+ assert chunk.count("```") == 2+ assert len(chunk) <= SLACK_MESSAGE_TEXT_LIMIT++ def test_mixed_text_and_code_block_preserves_block(self):+ prefix = "intro paragraph\n\n"+ suffix = "\n\ntrailing paragraph"+ code = "```js\n" + "console.log('hi');\n" * 10 + "```"+ text = prefix + code + suffix+ chunks = _split_markdown_for_slack(text)+ joined = "\n\n".join(chunks)+ assert "```js\n" in joined+ assert joined.count("```") % 2 == 0++ def test_paragraph_split_preserves_markdown_for_per_chunk_conversion(self):+ # Each chunk must stay a valid markdown document on its own so that the+ # per-chunk mrkdwn conversion produces correctly-rendered output.+ paragraph_a = "This **bold** and [link](https://example.com) " * 50+ paragraph_b = "Another **bold** and [link](https://example.com) " * 50+ text = f"{paragraph_a.strip()}\n\n{paragraph_b.strip()}"+ chunks = _split_markdown_for_slack(text)+ assert len(chunks) == 2+ for chunk in chunks:+ converted = _markdown_to_slack_mrkdwn(chunk)+ assert "*bold*" in converted+ assert "<https://example.com|link>" in converted+ assert "**" not in converted # inline bold markers must be fully converted++ def test_hard_char_break_leaves_broken_inline_span_as_literal(self):+ # A single line longer than the limit forces a hard char break. Doing it+ # before conversion means a halved ``**bold**`` simply fails to match the+ # converter regex on either side, so both chunks keep the literal ``**``+ # rather than ending up with a dangling unbalanced ``*`` in Slack mrkdwn.+ prefix = "x" * (SLACK_MESSAGE_TEXT_LIMIT - 4)+ line = prefix + "**bold**" + "y" * 100+ chunks = _split_markdown_for_slack(line)+ assert len(chunks) == 2+ converted_first = _markdown_to_slack_mrkdwn(chunks[0])+ converted_second = _markdown_to_slack_mrkdwn(chunks[1])+ # Neither chunk should contain a valid Slack-mrkdwn ``*bold*`` because+ # the span was halved; both should preserve the raw asterisks instead.+ assert "*bold*" not in converted_first+ assert "*bold*" not in converted_second+ # And, critically, no chunk leaks a lone unbalanced ``*`` that would+ # turn the rest of the message italic.+ for chunk in (converted_first, converted_second):+ assert chunk.count("*") % 2 == 0+++class TestRelaySlackMessageChunking(TestCase):+ org: ClassVar[Organization]+ team: ClassVar[Team]+ user: ClassVar[User]+ integration: ClassVar[Integration]+ task: ClassVar[Task]+ task_run: ClassVar[TaskRun]++ @classmethod+ def setUpTestData(cls):+ cls.org = Organization.objects.create(name="ChunkOrg")+ cls.team = Team.objects.create(organization=cls.org, name="ChunkTeam")+ cls.user = User.objects.create(email="[email protected]")+ cls.task = Task.objects.create(+ team=cls.team,+ title="Chunk task",+ description="desc",+ origin_product=Task.OriginProduct.SLACK,+ created_by=cls.user,+ repository="org/repo",+ )+ cls.task_run = TaskRun.objects.create(+ task=cls.task,+ team=cls.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={},+ )+ cls.integration = Integration.objects.create(+ team=cls.team,+ kind="slack",+ integration_id="T456",+ config={},+ )+ SlackThreadTaskMapping.objects.create(+ team=cls.team,+ integration=cls.integration,+ slack_workspace_id="T456",+ channel="C456",+ thread_ts="2222.2",+ task=cls.task,+ task_run=cls.task_run,+ mentioning_slack_user_id="U456",+ )++ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.update_reaction")+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.post_thread_message")+ @patch("products.slack_app.backend.slack_thread.SlackThreadHandler.delete_progress")+ def test_long_text_posts_multiple_chunks_with_prefix_only_on_first(+ self,+ mock_delete_progress,+ mock_post,+ mock_update,+ ):+ paragraph = ("alpha " * 400).strip()+ text = "\n\n".join([paragraph] * 4)+ relay_slack_message(+ RelaySlackMessageInput(+ run_id=str(self.task_run.id),+ relay_id="relay-chunked",+ text=text,+ user_message_ts="1234.5",+ reaction_emoji="hedgehog",+ )+ )++ mock_delete_progress.assert_called_once()+ assert mock_post.call_count >= 2+ first_posted = mock_post.call_args_list[0].args[0]+ assert first_posted.startswith("<@U456> ")+ for call in mock_post.call_args_list[1:]:+ assert not call.args[0].startswith("<@U456>")+ mock_update.assert_called_once_with("hedgehog")++ self.task_run.refresh_from_db()+ assert "relay-chunked" in self.task_run.state.get("slack_sent_relay_ids", [])