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.

chore(tasks): turn-completed signal, run history read and state helpers (#106428)

Rafael Audibertd3822855c194
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
index 613695a8e150..144f80a88dd3 100644
--- a/products/tasks/backend/agent_proxy_callback.py
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -17,7 +17,7 @@ from products.tasks.backend.presentation.serializers import (
AgentProxyCallbackResponseSerializer,
TaskRunErrorResponseSerializer,
)
-from products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed
+from products.tasks.backend.turn_completed import dispatch_turn_completed
from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
@@ -150,7 +150,7 @@ def agent_proxy_callback(request, run_id: str) -> JsonResponse:
id=run_id, task_id=task_id, team_id=team_id
)
task_run.signal_agent_turn_completed()
- dispatched = dispatch_task_run_turn_completed(task_run, turn_completed=data["turn_completed"])
+ dispatched = dispatch_turn_completed(task_run, turn_completed=data["turn_completed"])
except TaskRun.DoesNotExist:
logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
except Exception:
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index d2e7dab224dd..172825a2e91d 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -1,13 +1,14 @@
import re
+import json
import time
import hashlib
import logging
from collections import Counter
-from collections.abc import Collection, Iterable, Mapping, Sequence
+from collections.abc import Callable, Collection, Iterable, Iterator, Mapping, Sequence
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field, replace
-from datetime import datetime, timedelta
-from typing import Any, Literal
+from datetime import UTC, datetime, timedelta
+from typing import Any, Literal, TypeVar
from urllib.parse import urlparse
from uuid import UUID, uuid4
@@ -120,6 +121,7 @@ from products.tasks.backend.logic.services.space_setup import (
space_setup_task_title,
)
from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_run
+from products.tasks.backend.logic.stream.backlog import TaskRunStreamBacklogIndex
from products.tasks.backend.mentions import resolve_mentioned_user_ids
from products.tasks.backend.models import (
MCP_CREDENTIAL_OWNER_STATE_KEY,
@@ -699,6 +701,43 @@ def get_task_for_slack_unfurl(task_id: str | UUID, team_id: int, user_id: int) -
)
+_StateEntryResult = TypeVar("_StateEntryResult")
+
+
+def read_task_state_entry(task_id: str | UUID, team_id: int, key: str) -> object:
+ """One key of the task's shared state bag, or ``None`` when the task or the key is missing."""
+ state = Task.objects.filter(id=task_id, team_id=team_id).values_list("state", flat=True).first()
+ return (state or {}).get(key)
+
+
+def update_task_state_entry(
+ task_id: str | UUID,
+ team_id: int,
+ key: str,
+ update: Callable[[Any], tuple[Any, _StateEntryResult]],
+) -> _StateEntryResult | None:
+ """Row-locked read-modify-write of one key in the task's shared state bag.
+
+ ``update`` gets the current value (``None`` when unset) and returns the value to store and a
+ result for the caller. Returning the current value unchanged skips the write. Returns ``None``
+ without calling ``update`` when the task does not exist.
+ """
+ results: list[_StateEntryResult] = []
+
+ def _mutate(state: dict[str, Any]) -> None:
+ current = state.get(key)
+ value, result = update(current)
+ results.append(result)
+ if value != current:
+ state[key] = value
+
+ try:
+ Task.mutate_state_atomic(task_id, _mutate, team_id=team_id)
+ except Task.DoesNotExist:
+ return None
+ return results[0]
+
+
def attach_slack_thread_reference(
*,
task_id: str | UUID,
@@ -4473,6 +4512,203 @@ def read_task_run_log_content(log_urls: list[str]) -> str:
return "".join(parts)
+def parse_task_run_log_entries(log_content: str) -> Iterator[dict]:
+ """The JSON objects in a JSONL log, skipping blank and malformed lines."""
+ for log_line in log_content.splitlines():
+ log_line = log_line.strip()
+ if not log_line:
+ continue
+ try:
+ parsed_line = json.loads(log_line)
+ except json.JSONDecodeError:
+ continue
+ if isinstance(parsed_line, dict):
+ yield parsed_line
+
+
+def _read_run_stream_entries(run: TaskRun) -> list[dict]:
+ from products.tasks.backend.logic.stream.redis_stream import ( # noqa: PLC0415 — keep redis off the api import path
+ DATA_KEY,
+ get_task_run_stream_key,
+ )
+ from products.tasks.backend.redis import ( # noqa: PLC0415 — keep redis off the api import path
+ get_tasks_stream_redis_sync,
+ run_uses_dedicated_stream,
+ )
+
+ try:
+ client = get_tasks_stream_redis_sync(run_uses_dedicated_stream(run.state))
+ raw_entries = client.xrange(get_task_run_stream_key(str(run.id)))
+ except Exception:
+ logger.warning("task_run_stream_read_failed run_id=%s", run.id, exc_info=True)
+ return []
+ entries: list[dict] = []
+ for _stream_id, fields in raw_entries:
+ raw = fields.get(DATA_KEY) if isinstance(fields, dict) else None
+ if raw is None:
+ continue
+ try:
+ parsed = json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ continue
+ if isinstance(parsed, dict):
+ entries.append(parsed)
+ return entries
+
+
+def read_task_run_stream_entries(run_id: str | UUID, task_id: str | UUID, team_id: int) -> list[dict]:
+ """Every frame still held in the run's live Redis stream, oldest first.
+
+ The stream is capped and expires after the run ends, so a caller that needs the whole history
+ uses ``read_task_run_history``. Returns an empty list when the run is not visible or the
+ stream is gone.
+ """
+ run = _get_visible_run(run_id, task_id, team_id)
+ return _read_run_stream_entries(run) if run is not None else []
+
+
+_USER_PROMPT_METHODS = frozenset({"_posthog/user_message", "session/prompt"})
+
+
+def _holds_user_prompt(entries: list[dict]) -> bool:
+ for entry in entries:
+ notification = entry.get("notification") if entry.get("type") == "notification" else None
+ if isinstance(notification, dict) and notification.get("method") in _USER_PROMPT_METHODS:
+ return True
+ return False
+
+
+def _server_notification_key(entry: dict) -> str | None:
+ # A persisted server notification carries no event id, but both stores hold the same timestamped event.
+ notification = entry.get("notification") if entry.get("type") == "notification" else None
+ method = notification.get("method") if isinstance(notification, dict) else None
+ if entry.get("event_id") or not isinstance(method, str) or not method.startswith("_posthog/"):
+ return None
+ return json.dumps(entry, sort_keys=True)
+
+
+def _overlap_with_log_tail(log_entries: list[dict], stream_entries: list[dict]) -> int:
+ """How many leading stream entries the log already holds, as the tail it ends with."""
+ if not stream_entries:
+ return 0
+ first = stream_entries[0]
+ for start in range(max(0, len(log_entries) - len(stream_entries)), len(log_entries)):
+ size = len(log_entries) - start
+ if log_entries[start] == first and log_entries[start:] == stream_entries[:size]:
+ return size
+ return 0
+
+
+def _entry_time(entry: dict) -> datetime | None:
+ try:
+ parsed = datetime.fromisoformat(entry["timestamp"])
+ except (KeyError, TypeError, ValueError):
+ return None
+ return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC)
+
+
+def _merge_by_timestamp(entries: list[dict], extra: list[dict]) -> list[dict]:
+ """Slots each of ``extra`` in before the first of ``entries`` stamped later, keeping both orders."""
+ merged: list[dict] = []
+ pending = list(extra)
+ for entry in entries:
+ entry_time = _entry_time(entry)
+ while pending and entry_time is not None and (pending_time := _entry_time(pending[0])) is not None:
+ if pending_time > entry_time:
+ break
+ merged.append(pending.pop(0))
+ merged.append(entry)
+ return [*merged, *pending]
+
+
+def read_task_run_history(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, max_bytes: int
+) -> list[dict] | None:
+ """Every frame of the conversation across the run's resume chain, oldest first.
+
+ The logs hold every run, and the run's live stream adds what its log has not caught up with
+ yet. The agent stamps one event id in both stores, so a stream entry the logs already cover is
+ dropped, the way the thread's stream view merges them. An agent that stamps no ids keeps the
+ whole run in an untrimmed stream, which then stands in for the run's own log, apart from the
+ server notifications that only the log holds.
+
+ Returns ``None`` without downloading any log when the logs to read are over ``max_bytes``, and
+ an empty list when the run is not visible.
+ """
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return []
+ log_urls = [ancestor.log_url for ancestor in run.get_resume_chain()]
+ from products.tasks.backend.logic.stream.redis_stream import ( # noqa: PLC0415 — keep redis off the api import path
+ TASK_RUN_STREAM_MAX_LENGTH,
+ )
+
+ stream_entries = _read_run_stream_entries(run)
+ # A stream at the length cap may have lost its head to the trim, so only a shorter one can stand in for the log.
+ stream_is_whole_run = (
+ len(stream_entries) < TASK_RUN_STREAM_MAX_LENGTH
+ and not any(entry.get("event_id") for entry in stream_entries)
+ and _holds_user_prompt(stream_entries)
+ )
+ if log_urls and get_task_run_log_size(log_urls) > max_bytes:
+ return None
+ if stream_is_whole_run:
+ earlier_entries = (
+ list(parse_task_run_log_entries(read_task_run_log_content(log_urls[:-1]))) if log_urls[:-1] else []
+ )
+ # A server notification can reach the log after its live write failed or was skipped for want of a watcher.
+ streamed = {_server_notification_key(entry) for entry in stream_entries}
+ persisted_only = [
+ entry
+ for entry in parse_task_run_log_entries(read_task_run_log_content(log_urls[-1:]))
+ if (key := _server_notification_key(entry)) is not None and key not in streamed
+ ]
+ return [*earlier_entries, *_merge_by_timestamp(stream_entries, persisted_only)]
+ log_entries = list(parse_task_run_log_entries(read_task_run_log_content(log_urls))) if log_urls else []
+ if not any(entry.get("event_id") for entry in stream_entries):
+ # Without ids the backlog index matches nothing, so the log's catch-up of the stream is cut by position.
+ stream_entries = stream_entries[_overlap_with_log_tail(log_entries, stream_entries) :]
+ backlog = TaskRunStreamBacklogIndex(log_entries)
+ persisted_server_notifications = {
+ key for key in (_server_notification_key(entry) for entry in log_entries) if key is not None
+ }
+ uncovered = [
+ entry
+ for entry in stream_entries
+ if not backlog.covers(entry) and _server_notification_key(entry) not in persisted_server_notifications
+ ]
+ # A live-only server notification can predate log frames, so it goes back to its place in time.
+ live_only = [entry for entry in uncovered if _server_notification_key(entry) is not None]
+ tail = [entry for entry in uncovered if _server_notification_key(entry) is None]
+ return _merge_by_timestamp([*log_entries, *tail], live_only)
+
+
+def publish_task_run_stream_notification(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, method: str, params: dict, *, persist: bool = True
+) -> contracts.StreamNotificationDelivery:
+ """Write a server-originated ``_posthog/*`` notification to the run's live stream, and to its S3
+ log unless ``persist`` is off.
+
+ The live write reaches connected threads the way an agent-server frame would; the log append is
+ what a later bootstrap replays, so the frame survives the stream's expiry. A persisted frame is
+ written live only after the log append succeeds, so a thread never shows a frame that a reload
+ loses. A frame that only matters to threads open right now skips the log, which is a rewrite of
+ the whole object. The result reports each leg, so a caller can decide which one it needs.
+ """
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return contracts.StreamNotificationDelivery(live=False, persisted=False)
+ event = run.build_notification_event(method, params)
+ if persist:
+ try:
+ run.append_log([event], lock_attempts=1)
+ except Exception:
+ logger.warning("task_run_stream_notification_log_append_failed run_id=%s", run_id, exc_info=True)
+ return contracts.StreamNotificationDelivery(live=False, persisted=False)
+ live = run.publish_stream_event(event) is not None
+ return contracts.StreamNotificationDelivery(live=live, persisted=persist)
+
+
def create_task_run_connection_token(
run_id: str | UUID, task_id: str | UUID, team_id: int, *, user_id: int, distinct_id: str
) -> str | None:
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 6d300e9456ca..28d948813a6b 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -55,6 +55,18 @@ class TaskDTO:
slug: str = ""
+@dataclass(frozen=True)
+class StreamNotificationDelivery:
+ """Where a server-originated stream notification landed.
+
+ ``live`` reached the run's Redis stream, so connected threads show the frame now. ``persisted``
+ reached the run's S3 log, so a thread loaded after the stream expires replays it too.
+ """
+
+ live: bool
+ persisted: bool
+
+
@dataclass(frozen=True)
class SignalImplementationRunDTO:
"""Identity of a signals-origin ("self-driving") implementation run that produced a PR.
diff --git a/products/tasks/backend/facade/task_run_signals.py b/products/tasks/backend/facade/task_run_signals.py
index 88d1f2b9fd1d..c3749957be46 100644
--- a/products/tasks/backend/facade/task_run_signals.py
+++ b/products/tasks/backend/facade/task_run_signals.py
@@ -2,6 +2,7 @@ from collections.abc import Callable, Iterable
from uuid import UUID
from django.db.models.signals import post_save
+from django.dispatch import Signal
from products.tasks.backend.models import Task, TaskRun
@@ -13,6 +14,17 @@ def connect_task_run_post_save(receiver: Callable[..., None], *, dispatch_uid: s
post_save.connect(receiver, sender=TaskRun, dispatch_uid=dispatch_uid)
+# Sent with `task_run=` once an interactive run finishes a turn, so other products react to it
+# without the tasks product importing them.
+task_run_turn_completed = Signal()
+
+
+def connect_task_run_turn_completed(receiver: Callable[..., None], *, dispatch_uid: str) -> None:
+ """``receiver`` gets ``task_run=`` each time an interactive run finishes a turn. A receiver
+ that raises is logged and never fails the report."""
+ task_run_turn_completed.connect(receiver, sender=TaskRun, dispatch_uid=dispatch_uid)
+
+
# A guard gets (task_id, team_id, user_id) before a run starts and returns a message to refuse it with, or None.
TaskRunStartGuard = Callable[[str, int, int | None], str | None]
_task_run_start_guards: dict[str, TaskRunStartGuard] = {}
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index d3bed06654a3..e04e79ae5d55 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -34,7 +34,7 @@ from products.tasks.backend.logic.stream.redis_stream import (
)
from products.tasks.backend.metrics import observe_stream_write_skipped
from products.tasks.backend.models import TaskRun
-from products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed
+from products.tasks.backend.turn_completed import dispatch_turn_completed
from ee.hogai.sandbox import (
PI_RUNTIME_ERROR_MESSAGE,
@@ -572,7 +572,7 @@ def _dispatch_turn_completed_sync(run_id: str, *, succeeded: bool = False, turn_
return
task_run.signal_agent_turn_completed(succeeded=succeeded)
- dispatch_task_run_turn_completed(task_run, turn_completed=turn_completed)
+ dispatch_turn_completed(task_run, turn_completed=turn_completed)
async def _dispatch_turn_failed(run_id: str) -> None:
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index e9723cc04dc2..a04ca496fd83 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -1,5 +1,6 @@
import os
import re
+import copy
import json
import uuid
from collections.abc import Callable, Iterable
@@ -899,16 +900,40 @@ class Task(DeletedMetaFields, models.Model):
"""PR URL last announced to this task's Slack thread, if any."""
return (self.state or {}).get(SLACK_NOTIFIED_PR_URL_STATE_KEY)
- def mark_slack_pr_notified(self, pr_url: str) -> None:
- """Record ``pr_url`` as the PR announced to the task's Slack thread. Row-locked
- merge so it doesn't clobber other keys in the shared state bag."""
+ @classmethod
+ def mutate_state_atomic(
+ cls,
+ task_id: str | uuid.UUID,
+ mutator: Callable[[dict[str, Any]], None],
+ *,
+ team_id: int | None = None,
+ ) -> dict[str, Any]:
+ """Apply a state mutation while holding a row lock on the task.
+
+ Several writers share the task's state bag, so a locked read keeps one writer from
+ clobbering the keys of another. Skips the save when the mutator changes nothing. Raises
+ ``Task.DoesNotExist`` when the task is missing.
+ """
with transaction.atomic():
- task = Task.objects.select_for_update().only("id", "state").get(id=self.id)
- state = dict(task.state or {})
+ # NO KEY UPDATE does not wait on the KEY SHARE lock that every task run write takes on this row.
+ tasks = cls.objects.select_for_update(no_key=True).only("id", "state")
+ locked_task = (tasks.filter(team_id=team_id) if team_id is not None else tasks).get(id=task_id)
+ current = locked_task.state or {}
+ # A deep copy, so a mutator that edits a nested value in place still differs from ``current``.
+ state = copy.deepcopy(current)
+ mutator(state)
+ if state != current:
+ locked_task.state = state
+ locked_task.save(update_fields=["state", "updated_at"])
+ return state
+
+ def mark_slack_pr_notified(self, pr_url: str) -> None:
+ """Record ``pr_url`` as the PR announced to the task's Slack thread."""
+
+ def _mutate(state: dict[str, Any]) -> None:
state[SLACK_NOTIFIED_PR_URL_STATE_KEY] = pr_url
- task.state = state
- task.save(update_fields=["state", "updated_at"])
- self.state = state
+
+ self.state = Task.mutate_state_atomic(self.id, _mutate)
def claim_slack_pr_closed_notification(self, pr_url: str, *, merged: bool) -> bool:
"""Record that the task's Slack thread is told ``pr_url`` merged or closed, and say whether to post.
@@ -937,29 +962,27 @@ class Task(DeletedMetaFields, models.Model):
def mark_pr_ready_email_queued(self, pr_url: str, *, queued_at: datetime | None = None) -> bool:
"""Record that this task's PR-ready email task was queued, preserving other state keys."""
- with transaction.atomic():
- task = Task.objects.select_for_update().only("id", "state").get(id=self.id)
- state = dict(task.state or {})
+ queued = False
+
+ def _mutate(state: dict[str, Any]) -> None:
+ nonlocal queued
if state.get(PR_READY_EMAIL_QUEUED_AT_STATE_KEY) or state.get(PR_READY_EMAIL_SENT_AT_STATE_KEY):
- self.state = state
- return False
+ return
state[PR_READY_EMAIL_QUEUED_AT_STATE_KEY] = (queued_at or django_timezone.now()).isoformat()
state[PR_READY_EMAIL_PR_URL_STATE_KEY] = pr_url
- task.state = state
- task.save(update_fields=["state", "updated_at"])
- self.state = state
- return True
+ queued = True
+
+ self.state = Task.mutate_state_atomic(self.id, _mutate)
+ return queued
def mark_pr_ready_email_sent(self, pr_url: str, *, sent_at: datetime | None = None) -> None:
"""Record confirmed PR-ready email delivery, preserving other state keys."""
- with transaction.atomic():
- task = Task.objects.select_for_update().only("id", "state").get(id=self.id)
- state = dict(task.state or {})
+
+ def _mutate(state: dict[str, Any]) -> None:
state[PR_READY_EMAIL_SENT_AT_STATE_KEY] = (sent_at or django_timezone.now()).isoformat()
state[PR_READY_EMAIL_PR_URL_STATE_KEY] = pr_url
- task.state = state
- task.save(update_fields=["state", "updated_at"])
- self.state = state
+
+ self.state = Task.mutate_state_atomic(self.id, _mutate)
def soft_delete(self, capture_fn: Callable[..., None] | None = None):
deleted_at = django_timezone.now()
@@ -3171,8 +3194,9 @@ class TaskRun(models.Model):
"completed_at": self.completed_at.isoformat() if self.completed_at else None,
}
- def publish_stream_event(self, event: dict[str, Any]) -> None:
- publish_task_run_stream_event(
+ def publish_stream_event(self, event: dict[str, Any]) -> str | None:
+ """The stream id of the live write, or ``None`` when it was skipped or failed."""
+ return publish_task_run_stream_event(
str(self.id),
event,
run_uses_dedicated_stream(self.state),
@@ -3183,6 +3207,14 @@ class TaskRun(models.Model):
def publish_stream_state_event(self) -> None:
self.publish_stream_event(self.build_stream_state_event())
+ def build_notification_event(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
+ """A server-originated notification in the ACP envelope agent-server frames use."""
+ return {
+ "type": "notification",
+ "timestamp": django_timezone.now().isoformat(),
+ "notification": {"jsonrpc": "2.0", "method": method, "params": params},
+ }
+
def emit_console_event(self, level: LogLevel, message: str) -> None:
"""Emit a console-style log event in ACP notification format."""
event = {
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 60b5d26ba458..3dd11f86089d 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -317,17 +317,7 @@ def _release_backlog_bytes(size_bytes: int) -> None:
def _parse_backlog(log_content: str) -> tuple[list[dict], TaskRunStreamBacklogIndex]:
# Runs via asyncio.to_thread: parsing a log at the byte cap takes long
# enough to stall every other stream on the ASGI event loop.
- entries: list[dict] = []
- for log_line in log_content.splitlines():
- log_line = log_line.strip()
- if not log_line:
- continue
- try:
- parsed_line = json.loads(log_line)
- except json.JSONDecodeError:
- continue
- if isinstance(parsed_line, dict):
- entries.append(parsed_line)
+ entries = list(tasks_facade.parse_task_run_log_entries(log_content))
return entries, TaskRunStreamBacklogIndex(entries)
diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.py
index fbbb4bea37ba..568da315a8b5 100644
--- a/products/tasks/backend/push_dispatcher.py
+++ b/products/tasks/backend/push_dispatcher.py
@@ -31,11 +31,7 @@ from posthog.models.user import User
from posthog.models.user_push_token import UserPushToken
from posthog.tasks.push_notifications import send_user_push
-from products.tasks.backend.metrics import (
- PUSH_DISPATCHER_FAILURES_TOTAL,
- PUSH_DISPATCHER_OUTCOMES_TOTAL,
- TURN_COMPLETED_SUPPRESSED_TOTAL,
-)
+from products.tasks.backend.metrics import PUSH_DISPATCHER_FAILURES_TOTAL, PUSH_DISPATCHER_OUTCOMES_TOTAL
from products.tasks.backend.models import Task, TaskPresence
from products.tasks.backend.redis import get_tasks_cache
from products.tasks.backend.visibility import task_visibility_q
@@ -93,16 +89,6 @@ def notify_task_run_turn_completed(task_run: TaskRun) -> None:
_enqueue(task_run, kind="turn_completed", body=f'"{_task_title(task_run)}" finished')
-def dispatch_task_run_turn_completed(task_run: TaskRun, *, turn_completed: bool = True) -> bool:
- if task_run.mode != "interactive":
- return False
- if not turn_completed:
- TURN_COMPLETED_SUPPRESSED_TOTAL.labels(reason="idle_resume").inc()
- return False
- notify_task_run_turn_completed(task_run)
- return True
-
-
def notify_task_handoff(task: Task, *, recipient: User, actor: User | None, message_id: UUID) -> None:
"""Fire a push notification when a task is handed off to ``recipient``.
diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
index 02865e808192..068bf673b1d5 100644
--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py
@@ -37,7 +37,6 @@ from products.tasks.backend.models import (
Task as TaskModel,
TaskRun as TaskRunModel,
)
-from products.tasks.backend.push_dispatcher import dispatch_task_run_turn_completed
from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.constants import INACTIVITY_TIMEOUT_DEFAULT_SECONDS, resolve_inactivity_timeout
from products.tasks.backend.temporal.metrics import increment_tool_call_only_heartbeat
@@ -46,6 +45,7 @@ from products.tasks.backend.temporal.process_task.utils import (
get_task_run_credential_user,
is_slack_interaction_state,
)
+from products.tasks.backend.turn_completed import dispatch_turn_completed
from ee.hogai.sandbox import (
PI_RUNTIME_ERROR_MESSAGE,
@@ -1012,7 +1012,7 @@ def _safe_dispatch_turn_completed(task_run: TaskRunModel, *, turn_completed: boo
dispatch never bubbles into the relay loop.
"""
try:
- dispatch_task_run_turn_completed(task_run, turn_completed=turn_completed)
+ dispatch_turn_completed(task_run, turn_completed=turn_completed)
except Exception:
logger.warning(
"relay_sandbox_events_push_dispatch_failed",
diff --git a/products/tasks/backend/tests/test_facade_stream_notifications.py b/products/tasks/backend/tests/test_facade_stream_notifications.py
new file mode 100644
index 000000000000..86f6405d1e6d
--- /dev/null
+++ b/products/tasks/backend/tests/test_facade_stream_notifications.py
@@ -0,0 +1,205 @@
+import json
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from products.tasks.backend.facade.api import (
+ parse_task_run_log_entries,
+ publish_task_run_stream_notification,
+ read_task_run_history,
+ read_task_run_stream_entries,
+)
+from products.tasks.backend.facade.contracts import StreamNotificationDelivery
+from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_key, publish_task_run_stream_event
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.redis import get_tasks_stream_redis_sync
+
+USER_PROMPT = {"type": "notification", "notification": {"method": "_posthog/user_message", "params": {}}}
+SERVER_NOTIFICATION = {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:00+00:00",
+ "notification": {"jsonrpc": "2.0", "method": "_posthog/turn_suggestion", "params": {}},
+}
+
+
+def _frame(event_id: str) -> dict:
+ return {"type": "notification", "event_id": event_id, "notification": {"method": "session/update"}}
+
+
+LIVE_ONLY_NOTIFICATION = {
+ "type": "notification",
+ "timestamp": "2026-01-01T00:00:02+00:00",
+ "notification": {"jsonrpc": "2.0", "method": "_posthog/turn_suggestion_resolved", "params": {}},
+}
+
+
+def _numbered(index: int) -> dict:
+ return {"type": "notification", "notification": {"method": "session/update", "params": {"n": index}}}
+
+
+def _frame_without_id() -> dict:
+ return {"type": "notification", "notification": {"method": "session/update"}}
+
+
+def _stamped_at(entry: dict, timestamp: str) -> dict:
+ return {**entry, "timestamp": timestamp}
+
+
+class TestStreamNotifications(BaseTest):
+ def setUp(self):
+ super().setUp()
+ task = Task.objects.create(
+ team=self.team,
+ title="t",
+ description="d",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ created_by=self.user,
+ )
+ self.task_run = task.create_run(
+ mode="interactive",
+ extra_state={"use_dedicated_stream": False, "stream_presence_gated": False},
+ )
+ stream_key = get_task_run_stream_key(str(self.task_run.id))
+ get_tasks_stream_redis_sync().delete(stream_key)
+ self.addCleanup(get_tasks_stream_redis_sync().delete, stream_key)
+
+ def _entries(self, team_id: int | None = None) -> list[dict]:
+ return read_task_run_stream_entries(self.task_run.id, self.task_run.task_id, team_id or self.team.id)
+
+ def _publish(self, params: dict, team_id: int | None = None, persist: bool = True) -> StreamNotificationDelivery:
+ return publish_task_run_stream_notification(
+ self.task_run.id,
+ self.task_run.task_id,
+ team_id or self.team.id,
+ "_posthog/turn_suggestion",
+ params,
+ persist=persist,
+ )
+
+ def _history(self, max_bytes: int = 1024) -> list[dict] | None:
+ return read_task_run_history(self.task_run.id, self.task_run.task_id, self.team.id, max_bytes=max_bytes)
+
+ @parameterized.expand([("persisted", True), ("live_only", False)])
+ def test_notification_reaches_the_live_stream_and_the_log_when_persisted(self, _name: str, persist: bool):
+ with patch.object(TaskRun, "append_log") as append_log:
+ assert self._publish({"turnIndex": 0}, persist=persist) == StreamNotificationDelivery(
+ live=True, persisted=persist
+ )
+
+ live = self._entries()[-1]
+ assert live["notification"] == {
+ "jsonrpc": "2.0",
+ "method": "_posthog/turn_suggestion",
+ "params": {"turnIndex": 0},
+ }
+ assert live["timestamp"]
+ if persist:
+ append_log.assert_called_once_with([live], lock_attempts=1)
+ else:
+ append_log.assert_not_called()
+
+ def test_log_append_failure_skips_the_live_write(self):
+ before = len(self._entries())
+
+ with patch.object(TaskRun, "append_log", side_effect=RuntimeError("lock busy")):
+ assert self._publish({}) == StreamNotificationDelivery(live=False, persisted=False)
+
+ assert len(self._entries()) == before
+
+ def test_a_run_outside_the_team_publishes_nothing(self):
+ assert self._publish({}, team_id=self.team.id + 1) == StreamNotificationDelivery(live=False, persisted=False)
+ assert self._entries(team_id=self.team.id + 1) == []
+
+ def test_parse_task_run_log_entries_skips_lines_that_are_not_objects(self):
+ content = "\n".join([json.dumps({"type": "notification"}), "not json", json.dumps([1, 2]), "", "{}"])
+
+ assert list(parse_task_run_log_entries(content)) == [{"type": "notification"}, {}]
+
+ @parameterized.expand(
+ [
+ # No event ids and a user prompt: the stream holds the whole run, so its log is not read.
+ ("unstamped_stream_stands_in_for_the_log", [USER_PROMPT], [_frame("b-1")], [USER_PROMPT]),
+ # Stamped ids: the log comes first and the stream adds only what the log has not caught up with.
+ (
+ "stamped_stream_adds_its_tail",
+ [_frame("b-1"), _frame("b-2")],
+ [_frame("b-1")],
+ [_frame("b-1"), _frame("b-2")],
+ ),
+ # No user prompt: a stream of server frames alone does not replace the log.
+ (
+ "server_frames_do_not_replace_the_log",
+ [{"type": "notification"}],
+ [_frame("b-1")],
+ [_frame("b-1"), {"type": "notification"}],
+ ),
+ # A persisted server notification sits in both stores without an id, and appears once.
+ (
+ "persisted_server_notification_appears_once",
+ [_frame("b-1"), SERVER_NOTIFICATION],
+ [_frame("b-1"), SERVER_NOTIFICATION],
+ [_frame("b-1"), SERVER_NOTIFICATION],
+ ),
+ # A persisted server notification whose live write was skipped comes from the log, in timestamp order.
+ (
+ "unstamped_stream_keeps_a_server_notification_only_the_log_holds",
+ [USER_PROMPT, _stamped_at(_frame_without_id(), "2026-01-01T00:00:01+00:00")],
+ [_frame("b-1"), SERVER_NOTIFICATION],
+ [USER_PROMPT, SERVER_NOTIFICATION, _stamped_at(_frame_without_id(), "2026-01-01T00:00:01+00:00")],
+ ),
+ # An unstamped stream at the cap overlaps the log's tail, and the overlap appears once.
+ (
+ "capped_unstamped_stream_overlapping_the_log",
+ [_numbered(2), _numbered(3), _numbered(4)],
+ [_numbered(1), _numbered(2), _numbered(3)],
+ [_numbered(1), _numbered(2), _numbered(3), _numbered(4)],
+ 3,
+ ),
+ # A live-only server notification keeps its place in time among the logged frames.
+ (
+ "live_only_server_notification_keeps_its_place",
+ [_stamped_at(_frame("b-1"), "2026-01-01T00:00:00+00:00"), LIVE_ONLY_NOTIFICATION],
+ [
+ _stamped_at(_frame("b-1"), "2026-01-01T00:00:00+00:00"),
+ _stamped_at(_frame("b-2"), "2026-01-01T00:00:05+00:00"),
+ ],
+ [
+ _stamped_at(_frame("b-1"), "2026-01-01T00:00:00+00:00"),
+ LIVE_ONLY_NOTIFICATION,
+ _stamped_at(_frame("b-2"), "2026-01-01T00:00:05+00:00"),
+ ],
+ ),
+ # An unstamped stream at the length cap may be a trimmed tail, so the log is still read.
+ (
+ "unstamped_stream_at_the_cap_keeps_the_log",
+ [USER_PROMPT, USER_PROMPT],
+ [_frame("b-1")],
+ [_frame("b-1"), USER_PROMPT, USER_PROMPT],
+ 2,
+ ),
+ ]
+ )
+ def test_history_merges_the_log_and_the_live_stream(
+ self, _name: str, stream: list[dict], log: list[dict], expected: list[dict], stream_cap: int = 5_000
+ ):
+ for event in stream:
+ publish_task_run_stream_event(str(self.task_run.id), event)
+ log_content = "\n".join(json.dumps(entry) for entry in log)
+
+ with (
+ patch("posthog.storage.object_storage.head_object", return_value={"ContentLength": len(log_content)}),
+ patch("posthog.storage.object_storage.read", return_value=log_content),
+ patch("products.tasks.backend.logic.stream.redis_stream.TASK_RUN_STREAM_MAX_LENGTH", stream_cap),
+ ):
+ assert self._history() == expected
+
+ def test_history_over_the_byte_cap_downloads_nothing(self):
+ with (
+ patch("posthog.storage.object_storage.head_object", return_value={"ContentLength": 2048}),
+ patch("posthog.storage.object_storage.read") as read,
+ ):
+ assert self._history(max_bytes=1024) is None
+
+ read.assert_not_called()
diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.py
index ef1157105808..7baa1b4c724f 100644
--- a/products/tasks/backend/tests/test_models.py
+++ b/products/tasks/backend/tests/test_models.py
@@ -864,6 +864,16 @@ class TestTaskSlackPrNotification(TestCase):
self.assertEqual(task.state["unrelated"], "keep-me")
self.assertEqual(task.slack_notified_pr_url, "https://github.com/org/repo/pull/1")
+ def test_mutate_state_atomic_saves_a_nested_value_edited_in_place(self):
+ task = self._task()
+ task.state = {"offers": {"items": [1]}}
+ task.save(update_fields=["state"])
+
+ Task.mutate_state_atomic(task.id, lambda state: state["offers"]["items"].append(2))
+
+ task.refresh_from_db()
+ self.assertEqual(task.state["offers"], {"items": [1, 2]})
+
class TestTaskSlug(TestCase):
organization: ClassVar[Organization]
diff --git a/products/tasks/backend/tests/test_turn_completed.py b/products/tasks/backend/tests/test_turn_completed.py
new file mode 100644
index 000000000000..20ede26247be
--- /dev/null
+++ b/products/tasks/backend/tests/test_turn_completed.py
@@ -0,0 +1,72 @@
+from collections.abc import Callable
+
+from posthog.test.base import BaseTest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.tasks.backend.facade.task_run_signals import task_run_turn_completed
+from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.turn_completed import dispatch_turn_completed
+
+
+class TestDispatchTurnCompleted(BaseTest):
+ def _run(self, mode: str) -> TaskRun:
+ task = Task.objects.create(
+ team=self.team,
+ title="t",
+ description="d",
+ origin_product=Task.OriginProduct.POSTHOG_AI,
+ created_by=self.user,
+ )
+ return task.create_run(mode=mode)
+
+ def _connect(self, receiver: Callable[..., None]) -> None:
+ task_run_turn_completed.connect(receiver, sender=TaskRun, dispatch_uid="test_turn_completed")
+ self.addCleanup(task_run_turn_completed.disconnect, sender=TaskRun, dispatch_uid="test_turn_completed")
+
+ @parameterized.expand(
+ [
+ ("interactive_turn", "interactive", True, True),
+ ("idle_resume", "interactive", False, False),
+ ("background_run", "background", True, False),
+ ]
+ )
+ def test_fans_out_only_for_a_completed_interactive_turn(
+ self, _name: str, mode: str, turn_completed: bool, expected: bool
+ ) -> None:
+ task_run = self._run(mode)
+ receiver = MagicMock()
+ self._connect(receiver)
+
+ with patch("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed") as notify:
+ assert dispatch_turn_completed(task_run, turn_completed=turn_completed) is expected
+
+ assert notify.called is expected
+ assert receiver.called is expected
+ if expected:
+ assert receiver.call_args.kwargs["task_run"] == task_run
+
+ def test_a_failing_push_does_not_suppress_the_signal(self) -> None:
+ receiver = MagicMock()
+ self._connect(receiver)
+
+ with (
+ patch(
+ "products.tasks.backend.push_dispatcher.notify_task_run_turn_completed",
+ side_effect=RuntimeError("push down"),
+ ),
+ self.assertRaises(RuntimeError),
+ ):
+ dispatch_turn_completed(self._run("interactive"))
+
+ assert receiver.called
+
+ def test_a_failing_receiver_does_not_fail_the_report(self) -> None:
+ def failing_receiver(**kwargs: object) -> None:
+ raise RuntimeError("boom")
+
+ self._connect(failing_receiver)
+
+ with patch("products.tasks.backend.push_dispatcher.notify_task_run_turn_completed"):
+ assert dispatch_turn_completed(self._run("interactive")) is True
diff --git a/products/tasks/backend/turn_completed.py b/products/tasks/backend/turn_completed.py
new file mode 100644
index 000000000000..10e3bbfed089
--- /dev/null
+++ b/products/tasks/backend/turn_completed.py
@@ -0,0 +1,19 @@
+from products.tasks.backend import push_dispatcher
+from products.tasks.backend.facade.task_run_signals import task_run_turn_completed
+from products.tasks.backend.metrics import TURN_COMPLETED_SUPPRESSED_TOTAL
+from products.tasks.backend.models import TaskRun
+
+
+def dispatch_turn_completed(task_run: TaskRun, *, turn_completed: bool = True) -> bool:
+ """Everything that reacts to an interactive run finishing a turn. The proxy callback, the event
+ ingest and the sandbox relay all report that moment, so they share this one fan-out."""
+ if task_run.mode != "interactive":
+ return False
+ if not turn_completed:
+ TURN_COMPLETED_SUPPRESSED_TOTAL.labels(reason="idle_resume").inc()
+ return False
+ # send_robust logs a receiver that raises, so one product's failure never fails the reporter.
+ # It runs before the push, so push delivery never decides whether other products hear the turn.
+ task_run_turn_completed.send_robust(sender=TaskRun, task_run=task_run)
+ push_dispatcher.notify_task_run_turn_completed(task_run)
+ return True