: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
feat(tasks): add task run stream sequencing (#58132)
Alessandro Pogliaghi28889b19f88f
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.pyindex 5affe337d8c9..d451c54b27a6 100644--- a/products/tasks/backend/api.py+++ b/products/tasks/backend/api.py@@ -1461,7 +1461,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):with timer("s3_append"):task_run.append_log(entries)- task_run.heartbeat_workflow()+ task_run.heartbeat_workflow(agent_active=True)response = Response(TaskRunDetailSerializer(task_run, context=self.get_serializer_context()).data)response["Server-Timing"] = timer.to_header_string()diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex 107d8dd006eb..39f2cb9dc6c6 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -710,10 +710,13 @@ class TaskRun(models.Model):"""Get the Temporal workflow ID for this task run."""return self.get_workflow_id(self.task_id, self.id)- def heartbeat_workflow(self) -> None:+ def heartbeat_workflow(self, agent_active: bool = False) -> None:+ if not agent_active:+ return+from django.core.cache import cache- cache_key = f"tasks:task_run:heartbeat:{self.id}"+ cache_key = f"tasks:task_run:heartbeat:{self.id}:active"if not cache.add(cache_key, True, timeout=60):return@@ -726,7 +729,7 @@ class TaskRun(models.Model):try:client = sync_connect()handle = client.get_workflow_handle(self.workflow_id)- asyncio.run(handle.signal(ProcessTaskWorkflow.heartbeat))+ asyncio.run(handle.signal(ProcessTaskWorkflow.heartbeat, arg=agent_active))except Exception as e:logger.warning("task_run.heartbeat_failed", task_run_id=str(self.id), error=str(e))diff --git a/products/tasks/backend/stream/redis_stream.py b/products/tasks/backend/stream/redis_stream.pyindex 44eeecd6d72d..138ab6085d64 100644--- a/products/tasks/backend/stream/redis_stream.py+++ b/products/tasks/backend/stream/redis_stream.py@@ -17,6 +17,7 @@ logger = structlog.get_logger(__name__)# still bounding Redis growth for streams with a one-hour TTL.TASK_RUN_STREAM_MAX_LENGTH = 20_000TASK_RUN_STREAM_TIMEOUT = 60 * 60 # 60 minutes+TASK_RUN_STREAM_SEQUENCE_TIMEOUT = 24 * 60 * 60 # match sandbox event-ingest token lifetimeTASK_RUN_STREAM_PREFIX = "task-run-stream:"TASK_RUN_STREAM_READ_COUNT = 16TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS = 0.05@@ -39,10 +40,41 @@ class TaskRunStreamError(Exception):pass+class TaskRunStreamSequenceGap(Exception):+ def __init__(self, *, expected_sequence: int, received_sequence: int, last_accepted_seq: int):+ self.expected_sequence = expected_sequence+ self.received_sequence = received_sequence+ self.last_accepted_seq = last_accepted_seq+ super().__init__(f"Expected sequence {expected_sequence}, got {received_sequence}")+++class TaskRunStreamCompletionSequenceMismatch(Exception):+ def __init__(self, *, final_sequence: int, last_accepted_seq: int):+ self.final_sequence = final_sequence+ self.last_accepted_seq = last_accepted_seq+ super().__init__(+ f"Cannot complete stream at sequence {final_sequence}; last accepted sequence is {last_accepted_seq}"+ )+++class TaskRunStreamAlreadyCompleted(Exception):+ def __init__(self, *, last_accepted_seq: int):+ self.last_accepted_seq = last_accepted_seq+ super().__init__("Task run stream is already complete")++def get_task_run_stream_key(run_id: str) -> str:return f"{TASK_RUN_STREAM_PREFIX}{run_id}"+def get_task_run_stream_sequence_key(stream_key: str) -> str:+ return f"{stream_key}:last-seq"+++def get_task_run_stream_completed_key(stream_key: str) -> str:+ return f"{stream_key}:completed"++class TaskRunRedisStream:"""Manages task run event streaming via Redis streams.@@ -58,6 +90,7 @@ class TaskRunRedisStream:self._stream_key = stream_keyself._redis_client = get_async_client(settings.REDIS_URL)self._timeout = timeout+ self._sequence_timeout = max(timeout, TASK_RUN_STREAM_SEQUENCE_TIMEOUT)self._max_length = max_lengthasync def initialize(self) -> None:@@ -202,9 +235,120 @@ class TaskRunRedisStream:await self._redis_client.expire(self._stream_key, self._timeout)return _normalize_stream_id(stream_id)+ async def get_last_sequence(self) -> int:+ sequence_key = get_task_run_stream_sequence_key(self._stream_key)+ last_sequence_raw = await self._redis_client.get(sequence_key)+ if last_sequence_raw is not None:+ await self._redis_client.expire(sequence_key, self._sequence_timeout)+ return int(last_sequence_raw or 0)++ async def write_event_with_sequence(self, event: dict, sequence: int) -> str | None:+ """Write an event if it is the next unseen sequence number.++ Sequences must start at 1; sequence 0 is the initial sentinel and is+ treated as already accepted.+ Returns the Redis stream ID for newly accepted events, or None for a+ duplicate sequence that was already accepted on an earlier connection.+ """+ sequence_key = get_task_run_stream_sequence_key(self._stream_key)+ completed_key = get_task_run_stream_completed_key(self._stream_key)+ raw = json.dumps(event)++ while True:+ async with self._redis_client.pipeline(transaction=True) as pipe:+ try:+ await pipe.watch(sequence_key, completed_key)+ last_sequence_raw = await pipe.get(sequence_key)+ last_sequence = int(last_sequence_raw or 0)+ if await pipe.exists(completed_key):+ raise TaskRunStreamAlreadyCompleted(last_accepted_seq=last_sequence)++ if sequence <= last_sequence:+ return None++ if sequence != last_sequence + 1:+ raise TaskRunStreamSequenceGap(+ expected_sequence=last_sequence + 1,+ received_sequence=sequence,+ last_accepted_seq=last_sequence,+ )++ pipe.multi()+ pipe.xadd(+ self._stream_key,+ {DATA_KEY: raw},+ maxlen=self._max_length,+ approximate=True,+ )+ pipe.expire(self._stream_key, self._timeout)+ pipe.set(sequence_key, sequence, ex=self._sequence_timeout)+ results = await pipe.execute()+ return _normalize_stream_id(results[0])+ except redis_exceptions.WatchError:+ continue+async def mark_complete(self) -> None:"""Write a completion sentinel to signal end of stream."""- await self.write_event({"type": "STREAM_STATUS", "status": "complete"})+ completed_key = get_task_run_stream_completed_key(self._stream_key)+ raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})++ while True:+ async with self._redis_client.pipeline(transaction=True) as pipe:+ try:+ await pipe.watch(completed_key)+ if await pipe.exists(completed_key):+ return++ pipe.multi()+ pipe.xadd(+ self._stream_key,+ {DATA_KEY: raw},+ maxlen=self._max_length,+ approximate=True,+ )+ pipe.expire(self._stream_key, self._timeout)+ pipe.set(completed_key, "1", ex=self._sequence_timeout)+ await pipe.execute()+ return+ except redis_exceptions.WatchError:+ continue++ async def mark_complete_after_sequence(self, final_sequence: int) -> None:+ """Write a completion sentinel only after the expected final sequence is accepted."""+ sequence_key = get_task_run_stream_sequence_key(self._stream_key)+ completed_key = get_task_run_stream_completed_key(self._stream_key)+ raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})++ while True:+ async with self._redis_client.pipeline(transaction=True) as pipe:+ try:+ await pipe.watch(sequence_key, completed_key)+ last_sequence_raw = await pipe.get(sequence_key)+ last_sequence = int(last_sequence_raw or 0)+ if await pipe.exists(completed_key):+ return++ if last_sequence != final_sequence:+ raise TaskRunStreamCompletionSequenceMismatch(+ final_sequence=final_sequence,+ last_accepted_seq=last_sequence,+ )++ pipe.multi()+ pipe.xadd(+ self._stream_key,+ {DATA_KEY: raw},+ maxlen=self._max_length,+ approximate=True,+ )+ pipe.expire(self._stream_key, self._timeout)+ if last_sequence_raw is not None:+ pipe.expire(sequence_key, self._sequence_timeout)+ pipe.set(completed_key, "1", ex=self._sequence_timeout)+ await pipe.execute()+ return+ except redis_exceptions.WatchError:+ continueasync def mark_error(self, error: str) -> None:"""Write an error sentinel to signal stream failure."""@@ -213,7 +357,9 @@ class TaskRunRedisStream:async def delete_stream(self) -> bool:"""Delete the Redis stream. Returns True if deleted."""try:- return await self._redis_client.delete(self._stream_key) > 0+ sequence_key = get_task_run_stream_sequence_key(self._stream_key)+ completed_key = get_task_run_stream_completed_key(self._stream_key)+ return await self._redis_client.delete(self._stream_key, sequence_key, completed_key) > 0except Exception:logger.exception("task_run_stream_delete_failed", stream_key=self._stream_key)return False@@ -235,3 +381,16 @@ def publish_task_run_stream_event(run_id: str, event: dict) -> str | None:except Exception:logger.exception("task_run_stream_publish_failed", run_id=run_id)return None+++def publish_task_run_stream_complete(run_id: str) -> None:+ """Synchronously publish a completion sentinel for a task-run stream."""++ async def _publish() -> None:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(run_id))+ await redis_stream.mark_complete()++ try:+ async_to_sync(_publish)()+ except Exception:+ logger.exception("task_run_stream_complete_publish_failed", run_id=run_id)diff --git a/products/tasks/backend/stream/tests/test_redis_stream.py b/products/tasks/backend/stream/tests/test_redis_stream.pynew file mode 100644index 000000000000..eec91dd99183--- /dev/null+++ b/products/tasks/backend/stream/tests/test_redis_stream.py@@ -0,0 +1,108 @@+import json+from uuid import uuid4++import pytest++from products.tasks.backend.stream.redis_stream import (+ DATA_KEY,+ TaskRunRedisStream,+ TaskRunStreamAlreadyCompleted,+ TaskRunStreamCompletionSequenceMismatch,+ TaskRunStreamSequenceGap,+)+++def _new_stream() -> TaskRunRedisStream:+ return TaskRunRedisStream(f"task-run-stream:test:{uuid4()}", timeout=60)+++async def _read_stream_events(redis_stream: TaskRunRedisStream) -> list[dict]:+ messages = await redis_stream._redis_client.xrange(redis_stream._stream_key)+ return [json.loads(message[DATA_KEY]) for _stream_id, message in messages]+++async def test_write_event_with_sequence_accepts_next_sequence() -> None:+ redis_stream = _new_stream()+ try:+ stream_id = await redis_stream.write_event_with_sequence({"type": "message"}, 1)++ assert stream_id is not None+ assert await redis_stream.get_last_sequence() == 1+ assert await _read_stream_events(redis_stream) == [{"type": "message"}]+ finally:+ await redis_stream.delete_stream()+++async def test_write_event_with_sequence_rejects_sequence_gap() -> None:+ redis_stream = _new_stream()+ try:+ with pytest.raises(TaskRunStreamSequenceGap) as exc:+ await redis_stream.write_event_with_sequence({"type": "message"}, 2)++ assert exc.value.expected_sequence == 1+ assert exc.value.received_sequence == 2+ assert exc.value.last_accepted_seq == 0+ assert await redis_stream.get_last_sequence() == 0+ assert await _read_stream_events(redis_stream) == []+ finally:+ await redis_stream.delete_stream()+++async def test_write_event_with_sequence_ignores_duplicate_sequence() -> None:+ redis_stream = _new_stream()+ try:+ first_stream_id = await redis_stream.write_event_with_sequence({"type": "first"}, 1)+ duplicate_stream_id = await redis_stream.write_event_with_sequence({"type": "duplicate"}, 1)++ assert first_stream_id is not None+ assert duplicate_stream_id is None+ assert await redis_stream.get_last_sequence() == 1+ assert await _read_stream_events(redis_stream) == [{"type": "first"}]+ finally:+ await redis_stream.delete_stream()+++async def test_write_event_with_sequence_rejects_write_after_completion() -> None:+ redis_stream = _new_stream()+ try:+ await redis_stream.write_event_with_sequence({"type": "message"}, 1)+ await redis_stream.mark_complete_after_sequence(1)++ with pytest.raises(TaskRunStreamAlreadyCompleted) as exc:+ await redis_stream.write_event_with_sequence({"type": "late"}, 2)++ assert exc.value.last_accepted_seq == 1+ finally:+ await redis_stream.delete_stream()+++async def test_mark_complete_after_sequence_rejects_sequence_mismatch() -> None:+ redis_stream = _new_stream()+ try:+ await redis_stream.write_event_with_sequence({"type": "message"}, 1)++ with pytest.raises(TaskRunStreamCompletionSequenceMismatch) as exc:+ await redis_stream.mark_complete_after_sequence(2)++ assert exc.value.final_sequence == 2+ assert exc.value.last_accepted_seq == 1+ assert await _read_stream_events(redis_stream) == [{"type": "message"}]+ finally:+ await redis_stream.delete_stream()+++async def test_mark_complete_is_idempotent() -> None:+ redis_stream = _new_stream()+ try:+ await redis_stream.mark_complete()+ await redis_stream.mark_complete()++ assert await _read_stream_events(redis_stream) == [{"type": "STREAM_STATUS", "status": "complete"}]+ finally:+ await redis_stream.delete_stream()diff --git a/products/tasks/backend/temporal/process_task/tests/test_followup.py b/products/tasks/backend/temporal/process_task/tests/test_followup.pyindex dac98db9bb2a..10c6b68f8096 100644--- a/products/tasks/backend/temporal/process_task/tests/test_followup.py+++ b/products/tasks/backend/temporal/process_task/tests/test_followup.py@@ -390,7 +390,7 @@ class TestCIFollowUpLoop:)near_delay = CI_FOLLOW_UP_DELAY.total_seconds() - 30await env.sleep(near_delay)- await handle.signal(ProcessTaskWorkflow.heartbeat, args=[True])+ await handle.signal(ProcessTaskWorkflow.heartbeat, arg=True)await env.sleep(60)followups_at_original_deadline = list(_ci_followup_calls)@@ -399,10 +399,34 @@ class TestCIFollowUpLoop:await handle.result()assert followups_at_original_deadline == [], (- "heartbeat(agent_active=True) should have pushed the CI follow-up past the original 15m boundary"+ "heartbeat should have pushed the CI follow-up past the original 15m boundary")assert _ci_followup_calls, "follow-up should still fire after the rescheduled deadline"+ @pytest.mark.timeout(90)+ async def test_idle_heartbeat_does_not_extend_ci_follow_up_clock(self):+ async with await WorkflowEnvironment.start_time_skipping() as env:+ task_queue = f"test-{uuid.uuid4()}"+ async with _make_worker(env, task_queue):+ handle = await env.client.start_workflow(+ ProcessTaskWorkflow.run,+ ProcessTaskInput(run_id="run-1"),+ id=f"test-{uuid.uuid4()}",+ task_queue=task_queue,+ retry_policy=RetryPolicy(maximum_attempts=1),+ execution_timeout=timedelta(hours=2),+ )+ near_delay = CI_FOLLOW_UP_DELAY.total_seconds() - 30+ await env.sleep(near_delay)+ await handle.signal(ProcessTaskWorkflow.heartbeat)+ await env.sleep(60)+ followups_at_original_deadline = list(_ci_followup_calls)++ await handle.signal(ProcessTaskWorkflow.complete_task, args=["completed", None])+ await handle.result()++ assert followups_at_original_deadline, "idle heartbeat should not push the CI follow-up deadline"+class TestFollowupGuards:@pytest.fixture(autouse=True)diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.pyindex ba5bf03f4859..cbf757cdf468 100644--- a/products/tasks/backend/temporal/process_task/workflow.py+++ b/products/tasks/backend/temporal/process_task/workflow.py@@ -923,9 +923,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):@temporalio.workflow.signalasync def heartbeat(self, agent_active: bool = False) -> None:+ if not agent_active:+ returnself._heartbeat_received = True- if agent_active:- self._last_active_time = workflow.now()+ self._last_active_time = workflow.now()@temporalio.workflow.signalasync def send_followup_message(self, message: str | None = None, artifact_ids: Optional[list[str]] = None) -> None:diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.pyindex 74a022bd888a..67007da65743 100644--- a/products/tasks/backend/tests/test_api.py+++ b/products/tasks/backend/tests/test_api.py@@ -3472,7 +3472,7 @@ class TestTaskRunAPI(BaseTaskAPITest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- mock_heartbeat.assert_called_once()+ mock_heartbeat.assert_called_once_with(agent_active=True)@patch("posthog.storage.object_storage.write")@patch("posthog.storage.object_storage.tag")diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 1768730f53e1..21ab3e391855 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -3,7 +3,7 @@ import uuidimport secretsfrom typing import ClassVar-from unittest.mock import patch+from unittest.mock import AsyncMock, patchfrom django.conf import settingsfrom django.core.exceptions import ValidationError@@ -902,16 +902,16 @@ class TestTaskRun(TestCase):from django.core.cache import cache- cache.delete(f"tasks:task_run:heartbeat:{run.id}")+ cache.delete(f"tasks:task_run:heartbeat:{run.id}:active")- run.heartbeat_workflow()+ run.heartbeat_workflow(agent_active=True)if expect_signal:mock_connect.assert_called_once()else:mock_connect.assert_not_called()- cache.delete(f"tasks:task_run:heartbeat:{run.id}")+ cache.delete(f"tasks:task_run:heartbeat:{run.id}:active")@patch("posthog.temporal.common.client.sync_connect")def test_heartbeat_workflow_rate_limited_by_cache(self, mock_connect):@@ -924,18 +924,49 @@ class TestTaskRun(TestCase):from django.core.cache import cache- cache_key = f"tasks:task_run:heartbeat:{run.id}"+ cache_key = f"tasks:task_run:heartbeat:{run.id}:active"cache.delete(cache_key)+ handle = mock_connect.return_value.get_workflow_handle.return_value+ handle.signal = AsyncMock()- run.heartbeat_workflow()+ run.heartbeat_workflow(agent_active=True)mock_connect.assert_called_once()+ handle.signal.assert_called_once()+ self.assertEqual(handle.signal.call_args.kwargs, {"arg": True})mock_connect.reset_mock()- run.heartbeat_workflow()+ run.heartbeat_workflow(agent_active=True)mock_connect.assert_not_called()cache.delete(cache_key)+ @patch("posthog.temporal.common.client.sync_connect")+ def test_heartbeat_workflow_ignores_idle_heartbeats(self, mock_connect):+ run = TaskRun.objects.create(+ task=self.task,+ team=self.team,+ status=TaskRun.Status.IN_PROGRESS,+ state={"mode": "background"},+ )++ from django.core.cache import cache++ cache.delete(f"tasks:task_run:heartbeat:{run.id}:active")++ handle = mock_connect.return_value.get_workflow_handle.return_value+ handle.signal = AsyncMock()++ run.heartbeat_workflow(agent_active=False)+ mock_connect.assert_not_called()++ run.heartbeat_workflow(agent_active=True)++ mock_connect.assert_called_once()+ handle.signal.assert_called_once()+ self.assertEqual(handle.signal.call_args.kwargs, {"arg": True})++ cache.delete(f"tasks:task_run:heartbeat:{run.id}:active")+class TestSandboxSnapshot(TestCase):organization: ClassVar[Organization]