: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
perf(slack-app): run the independent pre-task steps of a mention in parallel (#118353)
Vojta Bartoše63c16b94dcc
diff --git a/products/slack_app/backend/temporal/__init__.py b/products/slack_app/backend/temporal/__init__.pyindex 7afeb10d7537..2fbe876c7417 100644--- a/products/slack_app/backend/temporal/__init__.py+++ b/products/slack_app/backend/temporal/__init__.py@@ -32,6 +32,7 @@ from products.slack_app.backend.temporal.activities import (post_posthog_code_picker_timeout_activity,post_posthog_code_repo_picker_activity,post_slack_unfurl_charts_activity,+ posthog_code_thread_has_task_activity,prepare_slack_unfurl_charts_activity,process_slack_app_fork_thread_activity,request_untagged_followup_confirmation_activity,@@ -76,6 +77,7 @@ SLACK_APP_ACTIVITIES = [post_posthog_code_internal_error_activity,create_posthog_code_task_for_repo_activity,forward_posthog_code_followup_activity,+ posthog_code_thread_has_task_activity,create_posthog_code_routing_rule_activity,handle_posthog_code_slack_mention_command_activity,mark_slack_app_message_processing_activity,@@ -120,6 +122,7 @@ __all__ = ["discover_posthog_code_repository_via_agent_activity","enforce_posthog_code_billing_quota_activity","forward_posthog_code_followup_activity",+ "posthog_code_thread_has_task_activity","handle_posthog_code_slack_mention_command_activity","mark_slack_app_message_processing_activity","mark_slack_app_message_queued_activity",diff --git a/products/slack_app/backend/temporal/activities/__init__.py b/products/slack_app/backend/temporal/activities/__init__.pyindex d1b5c71172cd..b4d73a0a3378 100644--- a/products/slack_app/backend/temporal/activities/__init__.py+++ b/products/slack_app/backend/temporal/activities/__init__.py@@ -40,6 +40,7 @@ from products.slack_app.backend.temporal.activities.task_creation import (create_posthog_code_task_for_repo_activity,derive_mention_workflow_id,forward_posthog_code_followup_activity,+ posthog_code_thread_has_task_activity,)from products.slack_app.backend.temporal.activities.thread import collect_posthog_code_thread_messages_activityfrom products.slack_app.backend.temporal.activities.unfurl_charts import (@@ -71,6 +72,7 @@ __all__ = ["discover_posthog_code_repository_via_agent_activity","enforce_posthog_code_billing_quota_activity","forward_posthog_code_followup_activity",+ "posthog_code_thread_has_task_activity","handle_posthog_code_slack_mention_command_activity","mark_slack_app_message_processing_activity","mark_slack_app_message_queued_activity",diff --git a/products/slack_app/backend/temporal/activities/task_creation.py b/products/slack_app/backend/temporal/activities/task_creation.pyindex 267a0ea4d5ba..1215c9725e8d 100644--- a/products/slack_app/backend/temporal/activities/task_creation.py+++ b/products/slack_app/backend/temporal/activities/task_creation.py@@ -2,7 +2,7 @@ import reimport uuidimport textwrapfrom dataclasses import field-from typing import Any+from typing import TYPE_CHECKING, Anyfrom django.db import models@@ -34,6 +34,9 @@ from products.slack_app.backend.temporal.attachments import (from products.slack_app.backend.temporal.helpers import block_if_team_over_quota, safe_reactfrom products.slack_app.backend.temporal.types import PostHogCodeSlackMentionWorkflowInputs, SlackAppModelOverride+if TYPE_CHECKING:+ from products.slack_app.backend.models import SlackThreadTaskMapping+logger = structlog.get_logger(__name__)_RESUME_ERROR_MSG = "Sorry, I ran into an internal error restarting the agent. Please try again in a minute."@@ -871,6 +874,34 @@ def create_posthog_code_task_for_repo_activity()+def _followup_task_mappings(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, event_text: str+) -> "models.QuerySet[SlackThreadTaskMapping] | None":+ """The mapping a follow-up forwards to, or ``None`` when the message cannot be a follow-up."""+ from products.slack_app.backend.api import parse_rules_command+ from products.slack_app.backend.models import SlackThreadTaskMapping++ if parse_rules_command(event_text):+ return None+ return SlackThreadTaskMapping.objects.filter(+ integration_id=inputs.integration_id, channel=channel, thread_ts=thread_ts+ )+++@close_db_connections+def posthog_code_thread_has_task_activity(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str+) -> bool:+ """Whether `forward_posthog_code_followup_activity` will handle this message.++ It reads the same mapping, so the workflow knows a new thread early enough to run the+ new-thread steps at the same time as the model override classifier.+ """+ mappings = _followup_task_mappings(inputs, channel, thread_ts, inputs.event.get("text", ""))+ return mappings is not None and mappings.exists()++@activity.defn@close_db_connectionsdef forward_posthog_code_followup_activity(@@ -894,20 +925,12 @@ def forward_posthog_code_followup_activity("""from posthog.models.integration import Integration, SlackIntegration- from products.slack_app.backend.api import parse_rules_command, resolve_slack_user- from products.slack_app.backend.models import SlackThreadTaskMapping+ from products.slack_app.backend.api import resolve_slack_userfrom products.tasks.backend.facade import api as tasks_facade- if parse_rules_command(event_text):- return False-- try:- mapping = SlackThreadTaskMapping.objects.select_related("task_run", "task__created_by").get(- integration_id=inputs.integration_id,- channel=channel,- thread_ts=thread_ts,- )- except SlackThreadTaskMapping.DoesNotExist:+ mappings = _followup_task_mappings(inputs, channel, thread_ts, event_text)+ mapping = mappings.select_related("task_run", "task__created_by").first() if mappings is not None else None+ if mapping is None:logger.info("posthog_code_followup_not_handled", channel=channel, thread_ts=thread_ts)return Falsediff --git a/products/slack_app/backend/temporal/slack_app_mention_processing.py b/products/slack_app/backend/temporal/slack_app_mention_processing.pyindex af92ffb981e3..459f62057d5a 100644--- a/products/slack_app/backend/temporal/slack_app_mention_processing.py+++ b/products/slack_app/backend/temporal/slack_app_mention_processing.py@@ -1,12 +1,14 @@# Workflows in this module run on the max-ai temporal task queue.import json+import asynciofrom dataclasses import replacefrom datetime import timedelta-from typing import Any+from typing import TYPE_CHECKING, Anyfrom temporalio import workflowfrom temporalio.common import RetryPolicy+from posthog.dataclasses import frozenfrom posthog.temporal.common.base import PostHogWorkflowfrom products.slack_app.backend.temporal import (@@ -15,6 +17,7 @@ from products.slack_app.backend.temporal import (SlackAppModelOverride,SlackAppModelOverrideInput,SlackAppModelRouterInput,+ SlackAppProjectRoute,SlackAppProjectRouteInput,cascade_posthog_code_repository_activity,classify_posthog_code_task_needs_repo_activity,@@ -30,9 +33,13 @@ from products.slack_app.backend.temporal import (post_posthog_code_internal_error_activity,post_posthog_code_picker_timeout_activity,post_posthog_code_repo_picker_activity,+ posthog_code_thread_has_task_activity,request_untagged_followup_confirmation_activity,)+if TYPE_CHECKING:+ from products.slack_app.backend.services.slack_messages import SlackThreadMessage+POSTHOG_CODE_SLACK_MENTION_TIMEOUT_SECONDS = 10 * 60POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15@@ -44,6 +51,8 @@ POSTHOG_CODE_SLACK_PICKER_TIMEOUT_MINUTES = 15# branch. Standard two-step Temporal patch lifecycle: the call comes out once the# histories that recorded a plain marker have drained as well._PATCH_ID_MODEL_ROUTER = "slack-app-model-router-v1"+# Histories recorded without this marker replay `_prework_in_sequence`.+_PATCH_ID_PARALLEL_PREWORK = "slack-app-parallel-prework-v1"@workflow.defn(name="slack-app-mention-processing")@@ -96,132 +105,17 @@ class SlackAppMentionProcessingWorkflow(PostHogWorkflow):if blocked:return- # Untagged thread replies face the Haiku classifier before any- # forward. The webhook handler punted on this so its 3-second ack- # budget stays unencumbered; here we run it under Temporal's retry- # policy. Drop on chitchat or any failure (default-deny).- # File-only replies skip the classifier: there is no text to- # classify, and default-deny would silently drop the attachment.- # Replies with text still face it even when files are attached, so- # chitchat with a screenshot doesn't wake the agent.- event_files = event.get("files")- event_has_files = isinstance(event_files, list) and len(event_files) > 0- file_only_followup = event_has_files and not (event.get("text") or "").strip()- unconfirmed_followup = inputs.untagged_followup and not inputs.untagged_followup_confirmed- if unconfirmed_followup and not file_only_followup:- should_forward = await _execute_posthog_code_activity(- classify_untagged_followup_activity,- inputs,- channel,- thread_ts,- slack_user_id,- event.get("text", ""),- )- if not should_forward:- return-- # The reply is agent-directed. If the thread creator asked to be consulted- # about other people's replies, this is the moment to ask: the prompt now- # only interrupts someone over a message that would otherwise start work.- # A confirmed run skips it — the answer is what re-dispatched this.- if unconfirmed_followup:- awaiting_confirmation = await _execute_posthog_code_activity(- request_untagged_followup_confirmation_activity,- inputs,- channel,- thread_ts,- slack_user_id,- )- if awaiting_confirmation:- return-- # Read a model or effort request ("use fable for this one", "actually run- # this on opus") out of the message. Classified above the follow-up/new-task- # split because the mapping lookup that tells the two apart lives inside the- # follow-up activity: one call here serves whichever path the message takes,- # and recording the choice in history once stops a retry of either activity- # from landing on a different model than the first attempt announced.- model_override: SlackAppModelOverride | None = await _execute_posthog_code_activity(- classify_slack_app_model_override_activity,- SlackAppModelOverrideInput(- integration_id=inputs.integration_id,- slack_team_id=inputs.slack_team_id,- event_text=event.get("text", ""),- thread_ts=thread_ts,- ),- )-- followup_handled = await _execute_posthog_code_activity(- forward_posthog_code_followup_activity,- inputs,- channel,- thread_ts,- slack_user_id,- event.get("text", ""),- event.get("ts"),- model_override,- )- if followup_handled:- return-- # Untagged thread replies must not fall through to the new-task path.- # The user never @mentioned us — they only typed in a thread that- # used to have an active task. If the mapping is gone by the time we- # got here, the right behaviour is to do nothing.- if inputs.untagged_followup:+ if workflow.patched(_PATCH_ID_PARALLEL_PREWORK):+ prework = await _prework_in_parallel(inputs, channel, thread_ts, slack_user_id)+ else:+ prework = await _prework_in_sequence(inputs, channel, thread_ts, slack_user_id)+ if prework is None:return-- # Past both returns above the message opens a thread: explicit @mention, and- # the forward activity found no task mapped to it. Only such a message may- # pick its own project, because a task, its mapping and its run all belong to- # one. Everything below reads the integration from `inputs`, so the switch- # lands above the repo cascade. Eligibility is decided inside the activity.- project_route = await _execute_posthog_code_activity(- classify_slack_app_project_route_activity,- SlackAppProjectRouteInput(- integration_id=inputs.integration_id,- slack_team_id=inputs.slack_team_id,- event_text=event.get("text", ""),- user_id=inputs.user_id,- slack_user_id=slack_user_id,- thread_ts=thread_ts,- ),- )- if project_route is not None:- inputs = replace(inputs, integration_id=project_route.integration_id)- # The gate at the top of the run checked the project routing had- # resolved, not the one the message named. Without this the run spends- # the thread fetch, the needs-repo classifier and possibly a discovery- # sandbox before task creation refuses on the same quota.- blocked = await _execute_posthog_code_activity(- enforce_posthog_code_billing_quota_activity,- inputs,- channel,- thread_ts,- slack_user_id,- )- if blocked:- return-+ inputs = prework.inputs+ model_override = prework.model_override+ thread_messages = prework.thread_messagesuser_id = inputs.user_id- # A forked run is the one case where the thread we read and the thread we- # answer in are different. `channel`/`thread_ts` stay the DM throughout —- # they own the task, the mapping, the reaction and every follow-up — while- # the context block is built from the channel thread the user forked.- # Unset for every other run, so both pairs coincide.- context_channel = inputs.fork_source_channel or channel- context_thread_ts = inputs.fork_source_thread_ts or thread_ts-- thread_messages = await _execute_posthog_code_activity(- collect_posthog_code_thread_messages_activity,- inputs,- context_channel,- context_thread_ts,- )- if not thread_messages:- return-repository: str | None# Set only on the ambiguous path that runs the discovery sandboxrepo_research_task_id: str | None = None@@ -350,6 +244,233 @@ class SlackAppMentionProcessingWorkflow(PostHogWorkflow):)+@frozen+class _NewThreadPrework:+ """What the steps before repo selection hand to the rest of a new-thread run."""++ inputs: PostHogCodeSlackMentionWorkflowInputs+ model_override: SlackAppModelOverride | None+ thread_messages: "list[SlackThreadMessage]"+++def _model_override_input(inputs: PostHogCodeSlackMentionWorkflowInputs, thread_ts: str) -> SlackAppModelOverrideInput:+ return SlackAppModelOverrideInput(+ integration_id=inputs.integration_id,+ slack_team_id=inputs.slack_team_id,+ event_text=inputs.event.get("text", ""),+ thread_ts=thread_ts,+ )+++def _project_route_input(+ inputs: PostHogCodeSlackMentionWorkflowInputs, thread_ts: str, slack_user_id: str+) -> SlackAppProjectRouteInput:+ return SlackAppProjectRouteInput(+ integration_id=inputs.integration_id,+ slack_team_id=inputs.slack_team_id,+ event_text=inputs.event.get("text", ""),+ user_id=inputs.user_id,+ slack_user_id=slack_user_id,+ thread_ts=thread_ts,+ )+++def _is_file_only_followup(event: dict[str, Any]) -> bool:+ event_files = event.get("files")+ event_has_files = isinstance(event_files, list) and len(event_files) > 0+ return event_has_files and not (event.get("text") or "").strip()+++async def _untagged_followup_is_agent_directed(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, slack_user_id: str+) -> bool:+ return await _execute_posthog_code_activity(+ classify_untagged_followup_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ inputs.event.get("text", ""),+ )+++async def _awaiting_followup_confirmation(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, slack_user_id: str+) -> bool:+ return await _execute_posthog_code_activity(+ request_untagged_followup_confirmation_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ )+++async def _collect_thread_messages(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str+) -> "list[SlackThreadMessage]":+ # A forked run is the one case where the thread we read and the thread we+ # answer in are different. `channel`/`thread_ts` stay the DM throughout —+ # they own the task, the mapping, the reaction and every follow-up — while+ # the context block is built from the channel thread the user forked.+ # Unset for every other run, so both pairs coincide.+ return await _execute_posthog_code_activity(+ collect_posthog_code_thread_messages_activity,+ inputs,+ inputs.fork_source_channel or channel,+ inputs.fork_source_thread_ts or thread_ts,+ )+++async def _forward_followup(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+ model_override: SlackAppModelOverride | None,+) -> bool:+ return await _execute_posthog_code_activity(+ forward_posthog_code_followup_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ inputs.event.get("text", ""),+ inputs.event.get("ts"),+ model_override,+ )+++async def _apply_project_route(+ inputs: PostHogCodeSlackMentionWorkflowInputs,+ project_route: SlackAppProjectRoute | None,+ channel: str,+ thread_ts: str,+ slack_user_id: str,+) -> PostHogCodeSlackMentionWorkflowInputs | None:+ """The inputs to continue with, or ``None`` when the routed project is over its quota."""+ if project_route is None:+ return inputs+ inputs = replace(inputs, integration_id=project_route.integration_id)+ # The gate at the top of the run checked the project routing had+ # resolved, not the one the message named. Without this the run spends+ # the needs-repo classifier and possibly a discovery sandbox before task+ # creation refuses on the same quota.+ blocked = await _execute_posthog_code_activity(+ enforce_posthog_code_billing_quota_activity,+ inputs,+ channel,+ thread_ts,+ slack_user_id,+ )+ return None if blocked else inputs+++async def _prework_in_sequence(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, slack_user_id: str+) -> _NewThreadPrework | None:+ """The command order of histories recorded before `_PATCH_ID_PARALLEL_PREWORK`."""+ # Untagged thread replies face the Haiku classifier before any+ # forward. The webhook handler punted on this so its 3-second ack+ # budget stays unencumbered; here we run it under Temporal's retry+ # policy. Drop on chitchat or any failure (default-deny).+ # File-only replies skip the classifier: there is no text to+ # classify, and default-deny would silently drop the attachment.+ # Replies with text still face it even when files are attached, so+ # chitchat with a screenshot doesn't wake the agent.+ unconfirmed_followup = inputs.untagged_followup and not inputs.untagged_followup_confirmed+ if unconfirmed_followup and not _is_file_only_followup(inputs.event):+ if not await _untagged_followup_is_agent_directed(inputs, channel, thread_ts, slack_user_id):+ return None++ # The reply is agent-directed. If the thread creator asked to be consulted+ # about other people's replies, this is the moment to ask: the prompt now+ # only interrupts someone over a message that would otherwise start work.+ # A confirmed run skips it — the answer is what re-dispatched this.+ if unconfirmed_followup and await _awaiting_followup_confirmation(inputs, channel, thread_ts, slack_user_id):+ return None++ # Read a model or effort request ("use fable for this one", "actually run+ # this on opus") out of the message. Classified above the follow-up/new-task+ # split because the mapping lookup that tells the two apart lives inside the+ # follow-up activity: one call here serves whichever path the message takes,+ # and recording the choice in history once stops a retry of either activity+ # from landing on a different model than the first attempt announced.+ model_override: SlackAppModelOverride | None = await _execute_posthog_code_activity(+ classify_slack_app_model_override_activity, _model_override_input(inputs, thread_ts)+ )++ if await _forward_followup(inputs, channel, thread_ts, slack_user_id, model_override):+ return None++ # Untagged thread replies must not fall through to the new-task path.+ # The user never @mentioned us — they only typed in a thread that+ # used to have an active task. If the mapping is gone by the time we+ # got here, the right behaviour is to do nothing.+ if inputs.untagged_followup:+ return None++ # Past both returns above the message opens a thread: explicit @mention, and+ # the forward activity found no task mapped to it. Only such a message may+ # pick its own project, because a task, its mapping and its run all belong to+ # one. Everything below reads the integration from `inputs`, so the switch+ # lands above the repo cascade. Eligibility is decided inside the activity.+ project_route = await _execute_posthog_code_activity(+ classify_slack_app_project_route_activity, _project_route_input(inputs, thread_ts, slack_user_id)+ )+ routed_inputs = await _apply_project_route(inputs, project_route, channel, thread_ts, slack_user_id)+ if routed_inputs is None:+ return None++ thread_messages = await _collect_thread_messages(routed_inputs, channel, thread_ts)+ if not thread_messages:+ return None+ return _NewThreadPrework(inputs=routed_inputs, model_override=model_override, thread_messages=thread_messages)+++async def _prework_in_parallel(+ inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str, slack_user_id: str+) -> _NewThreadPrework | None:+ """Same decisions as `_prework_in_sequence`, with the independent steps run together.++ Each step reads only the message and the resolved project, so the slowest step sets+ the wall time instead of the sum of all of them.+ """+ model_override_task = asyncio.create_task(+ _execute_posthog_code_activity(+ classify_slack_app_model_override_activity, _model_override_input(inputs, thread_ts)+ )+ )++ if inputs.untagged_followup:+ # Untagged replies never open a thread. The override is wasted on a dropped reply.+ unconfirmed_followup = not inputs.untagged_followup_confirmed+ if unconfirmed_followup and not _is_file_only_followup(inputs.event):+ if not await _untagged_followup_is_agent_directed(inputs, channel, thread_ts, slack_user_id):+ return None+ if unconfirmed_followup and await _awaiting_followup_confirmation(inputs, channel, thread_ts, slack_user_id):+ return None+ await _forward_followup(inputs, channel, thread_ts, slack_user_id, await model_override_task)+ return None++ if await _execute_posthog_code_activity(posthog_code_thread_has_task_activity, inputs, channel, thread_ts):+ if await _forward_followup(inputs, channel, thread_ts, slack_user_id, await model_override_task):+ return None++ # A routed project is an install in the same Slack workspace, so the bot reads the same thread.+ project_route, thread_messages, model_override = await asyncio.gather(+ _execute_posthog_code_activity(+ classify_slack_app_project_route_activity, _project_route_input(inputs, thread_ts, slack_user_id)+ ),+ _collect_thread_messages(inputs, channel, thread_ts),+ model_override_task,+ )+ routed_inputs = await _apply_project_route(inputs, project_route, channel, thread_ts, slack_user_id)+ if routed_inputs is None or not thread_messages:+ return None+ return _NewThreadPrework(inputs=routed_inputs, model_override=model_override, thread_messages=thread_messages)++async def _execute_posthog_code_activity(activity_fn: Any, *args: Any) -> Any:return await workflow.execute_activity(activity_fn,diff --git a/products/slack_app/backend/temporal/tests/test_slack_app_mention_processing_workflow.py b/products/slack_app/backend/temporal/tests/test_slack_app_mention_processing_workflow.pyindex dd9f778b2e6e..c7c13cb79180 100644--- a/products/slack_app/backend/temporal/tests/test_slack_app_mention_processing_workflow.py+++ b/products/slack_app/backend/temporal/tests/test_slack_app_mention_processing_workflow.py@@ -4,18 +4,27 @@ from unittest.mock import patchfrom products.slack_app.backend.temporal import slack_app_mention_processingfrom products.slack_app.backend.temporal.types import PostHogCodeSlackMentionWorkflowInputs+_BILLING = "enforce_posthog_code_billing_quota_activity"+_CLASSIFY = "classify_untagged_followup_activity"+_CONFIRM = "request_untagged_followup_confirmation_activity"+_OVERRIDE = "classify_slack_app_model_override_activity"+_FORWARD = "forward_posthog_code_followup_activity"+@pytest.mark.asyncio[email protected]("parallel", [False, True])@pytest.mark.parametrize(- "text,expect_classifier",+ "text,expected_after_billing",[# File-only replies skip the classifier so the attachment isn't dropped.- ("", False),+ ("", [_CONFIRM, _OVERRIDE, _FORWARD]),# Replies with text still face the classifier even when files are attached.- ("nice weather today", True),+ ("nice weather today", [_CLASSIFY, _CONFIRM, _OVERRIDE, _FORWARD]),],)-async def test_untagged_followup_with_files_classifier_gating(text: str, expect_classifier: bool) -> None:+async def test_untagged_followup_with_files_classifier_gating(+ text: str, parallel: bool, expected_after_billing: list[str]+) -> None:workflow = slack_app_mention_processing.SlackAppMentionProcessingWorkflow()calls: list[str] = []inputs = PostHogCodeSlackMentionWorkflowInputs(@@ -47,26 +56,18 @@ async def test_untagged_followup_with_files_classifier_gating(text: str, expect_raise AssertionError(f"unexpected activity: {activity_fn.__name__}")- with patch.object(- slack_app_mention_processing, "_execute_posthog_code_activity", side_effect=fake_execute_activity+ with (+ patch.object(slack_app_mention_processing, "_execute_posthog_code_activity", side_effect=fake_execute_activity),+ patch.object(slack_app_mention_processing.workflow, "patched", return_value=parallel),):await workflow.run(inputs)- expected = ["enforce_posthog_code_billing_quota_activity"]- if expect_classifier:- expected.append("classify_untagged_followup_activity")- expected += [- "request_untagged_followup_confirmation_activity",- # The model-override classifier sits above the follow-up/new-task split, so it- # runs for a reply too.- "classify_slack_app_model_override_activity",- "forward_posthog_code_followup_activity",- ]- assert calls == expected+ assert calls == [_BILLING, *expected_after_billing]@pytest.mark.asyncio-async def test_confirmed_untagged_followup_skips_the_classifier_and_the_prompt() -> None:[email protected]("parallel", [False, True])+async def test_confirmed_untagged_followup_skips_the_classifier_and_the_prompt(parallel: bool) -> None:"""The click that re-dispatches carries the answer, so asking again wouldloop: prompt, confirm, classify, prompt."""workflow = slack_app_mention_processing.SlackAppMentionProcessingWorkflow()@@ -90,13 +91,10 @@ async def test_confirmed_untagged_followup_skips_the_classifier_and_the_prompt()return Trueraise AssertionError(f"unexpected activity: {activity_fn.__name__}")- with patch.object(- slack_app_mention_processing, "_execute_posthog_code_activity", side_effect=fake_execute_activity+ with (+ patch.object(slack_app_mention_processing, "_execute_posthog_code_activity", side_effect=fake_execute_activity),+ patch.object(slack_app_mention_processing.workflow, "patched", return_value=parallel),):await workflow.run(inputs)- assert calls == [- "enforce_posthog_code_billing_quota_activity",- "classify_slack_app_model_override_activity",- "forward_posthog_code_followup_activity",- ]+ assert calls == [_BILLING, _OVERRIDE, _FORWARD]diff --git a/products/slack_app/backend/temporal/tests/test_slack_app_mention_workflow.py b/products/slack_app/backend/temporal/tests/test_slack_app_mention_workflow.pyindex 93868c4caa2b..c32a3023b178 100644--- a/products/slack_app/backend/temporal/tests/test_slack_app_mention_workflow.py+++ b/products/slack_app/backend/temporal/tests/test_slack_app_mention_workflow.py@@ -75,6 +75,13 @@ class _Recorder:self.internal_errors: list[str] = []# ts -> forward result; missing means False (no existing task, fall through to new-task path).self.forward_results: dict[str, bool] = {}+ # ts -> mapping lookup result; missing means the forward result.+ self.has_task_results: dict[str, bool] = {}+ # ts per project route and thread fetch call, in execution order.+ self.project_route_calls: list[str | None] = []+ self.thread_fetches: list[str] = []+ # When set, the model override, project route and thread fetch fakes wait on it.+ self.new_thread_barrier: asyncio.Barrier | None = None# ts -> thread snapshot; missing means a one-message thread. An empty list is what# a deleted trigger message reads as.self.thread_messages: dict[str, list[SlackThreadMessage]] = {}@@ -136,11 +143,22 @@ def _fake_activities(rec: _Recorder) -> list:return Truereturn False+ async def wait_for_new_thread_steps() -> None:+ if rec.new_thread_barrier is not None:+ await asyncio.wait_for(rec.new_thread_barrier.wait(), timeout=10)++ @activity.defn(name="posthog_code_thread_has_task_activity")+ async def has_task(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> bool:+ ts = inputs.event["ts"]+ return rec.has_task_results.get(ts, rec.forward_results.get(ts, False))+@activity.defn(name="collect_posthog_code_thread_messages_activity")async def collect(inputs: PostHogCodeSlackMentionWorkflowInputs, channel: str, thread_ts: str) -> list[SlackThreadMessage]:ts = inputs.event["ts"]+ rec.thread_fetches.append(ts)+ await wait_for_new_thread_steps()return rec.thread_messages.get(ts, [SlackThreadMessage(user="U1", text=inputs.event["text"])])@activity.defn(name="cascade_posthog_code_repository_activity")@@ -204,10 +222,13 @@ def _fake_activities(rec: _Recorder) -> list:@activity.defn(name="classify_slack_app_model_override_activity")async def classify_model_override(input: SlackAppModelOverrideInput) -> SlackAppModelOverride | None:+ await wait_for_new_thread_steps()return rec.model_overrides.get(input.event_text)@activity.defn(name="classify_slack_app_project_route_activity")async def classify_project_route(input: SlackAppProjectRouteInput) -> SlackAppProjectRoute | None:+ rec.project_route_calls.append(input.thread_ts)+ await wait_for_new_thread_steps()return rec.project_routes.get(input.event_text)@activity.defn(name="classify_slack_app_model_router_activity")@@ -262,6 +283,7 @@ def _fake_activities(rec: _Recorder) -> list:quota,classify_followup,request_confirmation,+ has_task,forward,collect,cascade,@@ -431,6 +453,34 @@ async def test_model_override_reaches_a_followup_without_creating_a_task():assert rec.forwarded_with_override == {"1.1": override}assert rec.created == []assert rec.router_inputs == []+ assert rec.project_route_calls == []+ assert rec.thread_fetches == []+++async def test_new_thread_steps_run_at_the_same_time():+ rec = _Recorder()+ rec.new_thread_barrier = asyncio.Barrier(3)++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1"))+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.created == [("1.1", "org/auto-repo")]+ assert rec.internal_errors == []+++async def test_mention_whose_task_mapping_disappears_before_the_forward_still_creates_a_task():+ rec = _Recorder()+ rec.has_task_results["1.1"] = True++ async with _Harness(rec) as h:+ handle = await _signal_with_start(h.env, h.task_queue, f"wf-{uuid.uuid4()}", _message("1.1"))+ await asyncio.wait_for(handle.result(), timeout=30)++ assert rec.forwarded == []+ assert rec.created == [("1.1", "org/auto-repo")]@pytest.mark.asyncio