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.

feat(tasks): move task-run streams and caches to dedicated redis (#62108)

Alessandro Pogliaghia673e1b52c2f
diff --git a/posthog/caching/tasks_redis_cache.py b/posthog/caching/tasks_redis_cache.py
new file mode 100644
index 000000000000..e1994ab7ed8a
--- /dev/null
+++ b/posthog/caching/tasks_redis_cache.py
@@ -0,0 +1 @@
+TASKS_DEDICATED_CACHE_ALIAS = "tasks_dedicated"
diff --git a/posthog/settings/data_stores.py b/posthog/settings/data_stores.py
index b33754a17571..fa50975bda6b 100644
--- a/posthog/settings/data_stores.py
+++ b/posthog/settings/data_stores.py
@@ -533,6 +533,8 @@ FLAGS_REDIS_URL = os.getenv("FLAGS_REDIS_URL", None)
# Dedicated Redis for ai-gateway HyperCache reads
AI_GATEWAY_REDIS_URL = os.getenv("AI_GATEWAY_REDIS_URL", None)
+TASKS_REDIS_URL = os.getenv("TASKS_REDIS_URL", None)
+
# Rust feature flags service URL
# This is used to proxy flag evaluation requests to the Rust feature flags service
FEATURE_FLAGS_SERVICE_URL = os.getenv("FEATURE_FLAGS_SERVICE_URL", "http://localhost:3001")
@@ -594,6 +596,19 @@ if AI_GATEWAY_REDIS_URL:
"KEY_PREFIX": "posthog",
}
+if TASKS_REDIS_URL:
+ from posthog.caching.tasks_redis_cache import TASKS_DEDICATED_CACHE_ALIAS
+
+ CACHES[TASKS_DEDICATED_CACHE_ALIAS] = {
+ "BACKEND": "django_redis.cache.RedisCache",
+ "LOCATION": TASKS_REDIS_URL,
+ "OPTIONS": {
+ "CLIENT_CLASS": "django_redis.client.DefaultClient",
+ "COMPRESSOR": "posthog.caching.zstd_compressor.ZstdCompressor",
+ },
+ "KEY_PREFIX": "posthog",
+ }
+
QUERY_CACHE_REDIS_CLUSTER_URL: str | None = os.getenv("QUERY_CACHE_REDIS_CLUSTER_URL", None)
if QUERY_CACHE_REDIS_CLUSTER_URL:
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 5f81b15e4e86..968d595d8609 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -11,7 +11,6 @@ from typing import Any, cast
from urllib.parse import parse_qs, urlparse
from django.conf import settings
-from django.core.cache import cache
from django.db import models, transaction
from django.db.models import F, OuterRef, Q, Subquery
from django.db.models.functions import JSONObject
@@ -75,6 +74,7 @@ from .models import (
TaskPresence,
TaskRun,
)
+from .redis import get_tasks_cache
from .repository_readiness import compute_repository_readiness
from .serializers import (
CodeInviteRedeemRequestSerializer,
@@ -1152,7 +1152,7 @@ class TaskViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
task_run.save(update_fields=["artifacts", "updated_at"])
for artifact_id in pending_user_artifact_ids:
- cache.delete(build_task_staged_artifact_cache_key(str(task.id), artifact_id))
+ get_tasks_cache().delete(build_task_staged_artifact_cache_key(str(task.id), artifact_id))
if github_user_token and pr_authorship_mode == PrAuthorshipMode.USER:
cache_github_user_token(str(task_run.id), github_user_token)
@@ -2787,13 +2787,14 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
def stream(self, request, pk=None, **kwargs):
task_run = cast(TaskRun, self.get_object())
stream_key = get_task_run_stream_key(str(task_run.id))
+ stream_created_at = task_run.created_at
last_event_id = request.headers.get("Last-Event-ID")
start_latest = request.GET.get("start") == "latest"
format_sse_event = self._format_sse_event
origin_product = origin_product_label(task_run)
async def async_stream() -> AsyncGenerator[bytes, None]:
- redis_stream = TaskRunRedisStream(stream_key)
+ redis_stream = TaskRunRedisStream(stream_key, stream_created_at)
connection_started_at = asyncio.get_running_loop().time()
# Default to client_disconnect: any exit that isn't an explicit
# completion/error/unavailable is the client (or proxy) going away.
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 595e1d1af04d..8585b0ede1eb 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -753,10 +753,10 @@ class TaskRun(models.Model):
if not agent_active:
return
- from django.core.cache import cache
+ from products.tasks.backend.redis import get_tasks_cache
cache_key = f"tasks:task_run:heartbeat:{self.id}:active"
- if not cache.add(cache_key, True, timeout=60):
+ if not get_tasks_cache().add(cache_key, True, timeout=60):
return
import asyncio
@@ -978,7 +978,7 @@ class TaskRun(models.Model):
}
def publish_stream_event(self, event: dict[str, Any]) -> None:
- publish_task_run_stream_event(str(self.id), event)
+ publish_task_run_stream_event(str(self.id), event, self.created_at)
def publish_stream_state_event(self) -> None:
self.publish_stream_event(self.build_stream_state_event())
diff --git a/products/tasks/backend/push_dispatcher.py b/products/tasks/backend/push_dispatcher.py
index e2e7b6133fde..09fa20210863 100644
--- a/products/tasks/backend/push_dispatcher.py
+++ b/products/tasks/backend/push_dispatcher.py
@@ -21,7 +21,6 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Literal
-from django.core.cache import cache
from django.db import transaction
from django.utils import timezone
@@ -32,6 +31,7 @@ from posthog.models.user_push_token import UserPushToken
from posthog.tasks.push_notifications import send_user_push
from products.tasks.backend.models import TaskPresence
+from products.tasks.backend.redis import get_tasks_cache
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
@@ -134,7 +134,7 @@ def _enqueue_inner(task_run: TaskRun, *, kind: PushKind, body: str) -> None:
return
cooldown_key = f"push_notification:{task_run.id}:{kind}"
- if not cache.add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):
+ if not get_tasks_cache().add(cooldown_key, True, timeout=_COOLDOWN_SECONDS[kind]):
logger.debug("push_dispatcher.cooldown_hit", run_id=str(task_run.id), kind=kind)
return
diff --git a/products/tasks/backend/redis.py b/products/tasks/backend/redis.py
new file mode 100644
index 000000000000..c6480a82be25
--- /dev/null
+++ b/products/tasks/backend/redis.py
@@ -0,0 +1,44 @@
+from datetime import UTC, datetime
+
+from django.conf import settings
+from django.core.cache import BaseCache, caches
+
+from posthog.caching.tasks_redis_cache import TASKS_DEDICATED_CACHE_ALIAS
+from posthog.redis import get_async_client, get_client
+
+# One-time stream cutover: runs created on/after this instant use the dedicated tasks Redis;
+# older runs stay on the shared Redis until their streams drain (~6h TTL), so a live run is
+# never split across instances. Transitional — remove this and the stream routing below once
+# prod-us has fully drained past the cutover.
+TASKS_REDIS_STREAM_CUTOVER_AT = datetime(2026, 6, 9, 0, 0, tzinfo=UTC)
+
+
+def _use_dedicated_stream(created_at: datetime | None) -> bool:
+ if not settings.TASKS_REDIS_URL:
+ return False
+ if created_at is None:
+ # Unknown creation time: stay on the shared Redis so we never split an
+ # already-running pre-cutover stream across instances.
+ return False
+ return created_at >= TASKS_REDIS_STREAM_CUTOVER_AT
+
+
+def _tasks_stream_redis_url(created_at: datetime | None) -> str:
+ dedicated = settings.TASKS_REDIS_URL
+ if dedicated is not None and _use_dedicated_stream(created_at):
+ return dedicated
+ return settings.REDIS_URL
+
+
+def get_tasks_stream_redis_async(created_at: datetime | None = None):
+ return get_async_client(_tasks_stream_redis_url(created_at))
+
+
+def get_tasks_stream_redis_sync(created_at: datetime | None = None):
+ return get_client(_tasks_stream_redis_url(created_at))
+
+
+def get_tasks_cache() -> BaseCache:
+ if settings.TASKS_REDIS_URL and TASKS_DEDICATED_CACHE_ALIAS in settings.CACHES:
+ return caches[TASKS_DEDICATED_CACHE_ALIAS]
+ return caches["default"]
diff --git a/products/tasks/backend/repository_readiness.py b/products/tasks/backend/repository_readiness.py
index 52163bc0cee1..09f33f787591 100644
--- a/products/tasks/backend/repository_readiness.py
+++ b/products/tasks/backend/repository_readiness.py
@@ -6,7 +6,6 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
-from django.core.cache import cache
from django.utils import timezone
import requests
@@ -16,6 +15,7 @@ from posthog.models.integration import GitHubIntegration, Integration
from products.error_tracking.backend.facade import api as error_tracking_api
from products.event_definitions.backend.models.event_definition import EventDefinition
from products.tasks.backend.models import Task
+from products.tasks.backend.redis import get_tasks_cache
logger = logging.getLogger(__name__)
@@ -407,7 +407,7 @@ def compute_repository_readiness(
key = _cache_key(team_id=team.id, integration_id=integration.id, repository=repository, window_days=window_days)
if not refresh:
- cached = cache.get(key)
+ cached = get_tasks_cache().get(key)
if isinstance(cached, dict):
generated_at_str = cached.get("generatedAt")
if generated_at_str:
@@ -439,7 +439,7 @@ def compute_repository_readiness(
"generatedAt": timezone.now().isoformat(),
"cacheAgeSeconds": 0,
}
- cache.set(key, response, READINESS_CACHE_TTL_SECONDS)
+ get_tasks_cache().set(key, response, READINESS_CACHE_TTL_SECONDS)
return response
try:
@@ -621,5 +621,5 @@ def compute_repository_readiness(
},
}
- cache.set(key, response, READINESS_CACHE_TTL_SECONDS)
+ get_tasks_cache().set(key, response, READINESS_CACHE_TTL_SECONDS)
return response
diff --git a/products/tasks/backend/serializers.py b/products/tasks/backend/serializers.py
index 19e1a94ac0c5..31f4dccf8315 100644
--- a/products/tasks/backend/serializers.py
+++ b/products/tasks/backend/serializers.py
@@ -2,7 +2,6 @@ import base64
import binascii
from zoneinfo import available_timezones
-from django.core.cache import cache
from django.db import transaction
from django.utils import timezone
@@ -24,6 +23,7 @@ from .constants import (
INITIAL_PERMISSION_MODE_CHOICES,
)
from .models import SandboxEnvironment, Task, TaskAutomation, TaskRun
+from .redis import get_tasks_cache
from .services.title_generator import generate_task_title
from .temporal.process_task.utils import (
PUBLIC_REASONING_EFFORTS,
@@ -419,14 +419,14 @@ class TaskRunDetailSerializer(serializers.ModelSerializer):
"""Return presigned S3 URL for log access, cached to avoid regeneration."""
cache_key = f"task_run_log_url:{obj.id}"
- cached_url = cache.get(cache_key)
+ cached_url = get_tasks_cache().get(cache_key)
if cached_url:
return cached_url
presigned_url = object_storage.get_presigned_url(obj.log_url, expiration=3600)
if presigned_url:
- cache.set(cache_key, presigned_url, timeout=PRESIGNED_URL_CACHE_TTL)
+ get_tasks_cache().set(cache_key, presigned_url, timeout=PRESIGNED_URL_CACHE_TTL)
return presigned_url
diff --git a/products/tasks/backend/services/staged_artifacts.py b/products/tasks/backend/services/staged_artifacts.py
index 5bb6364b4302..458a9cc0b65f 100644
--- a/products/tasks/backend/services/staged_artifacts.py
+++ b/products/tasks/backend/services/staged_artifacts.py
@@ -4,7 +4,6 @@ import os
from typing import Any
from django.conf import settings
-from django.core.cache import cache
from django.utils import timezone
import structlog
@@ -12,6 +11,7 @@ import structlog
from posthog.storage import object_storage
from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.redis import get_tasks_cache
STAGED_TASK_ARTIFACT_CACHE_TTL_SECONDS = 24 * 60 * 60
RUN_ARTIFACT_TTL_DAYS = "30"
@@ -66,7 +66,7 @@ def build_task_artifact_entry(
def cache_task_staged_artifact(task: Task, artifact: dict[str, Any]) -> None:
artifact_id = str(artifact["id"])
- cache.set(
+ get_tasks_cache().set(
build_task_staged_artifact_cache_key(str(task.id), artifact_id),
artifact,
timeout=STAGED_TASK_ARTIFACT_CACHE_TTL_SECONDS,
@@ -79,7 +79,7 @@ def get_task_staged_artifacts(task: Task, artifact_ids: list[str]) -> tuple[list
for artifact_id in artifact_ids:
cache_key = build_task_staged_artifact_cache_key(str(task.id), artifact_id)
- artifact = cache.get(cache_key)
+ artifact = get_tasks_cache().get(cache_key)
if not isinstance(artifact, dict):
missing_ids.append(artifact_id)
continue
@@ -94,7 +94,7 @@ def consume_task_staged_artifacts(task: Task, artifact_ids: list[str]) -> tuple[
return [], missing_ids
for artifact_id in artifact_ids:
- cache.delete(build_task_staged_artifact_cache_key(str(task.id), artifact_id))
+ get_tasks_cache().delete(build_task_staged_artifact_cache_key(str(task.id), artifact_id))
return artifacts, []
diff --git a/products/tasks/backend/stream/redis_stream.py b/products/tasks/backend/stream/redis_stream.py
index 64c761a504d9..2b2527d5e4e8 100644
--- a/products/tasks/backend/stream/redis_stream.py
+++ b/products/tasks/backend/stream/redis_stream.py
@@ -1,6 +1,7 @@
import json
import asyncio
from collections.abc import AsyncGenerator
+from datetime import datetime
from typing import Optional
from django.conf import settings
@@ -9,8 +10,7 @@ import structlog
import redis.exceptions as redis_exceptions
from asgiref.sync import async_to_sync
-from posthog.redis import get_async_client
-
+from products.tasks.backend.redis import get_tasks_stream_redis_async
from products.tasks.backend.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTL
from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS
@@ -112,11 +112,12 @@ class TaskRunRedisStream:
def __init__(
self,
stream_key: str,
+ created_at: datetime | None = None,
timeout: int = TASK_RUN_STREAM_TIMEOUT,
max_length: int = TASK_RUN_STREAM_MAX_LENGTH,
):
self._stream_key = stream_key
- self._redis_client = get_async_client(settings.REDIS_URL)
+ self._redis_client = get_tasks_stream_redis_async(created_at)
self._timeout = timeout
self._sequence_timeout = max(timeout, TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
self._max_length = max_length
@@ -507,7 +508,7 @@ class TaskRunRedisStream:
return False
-def publish_task_run_stream_event(run_id: str, event: dict) -> str | None:
+def publish_task_run_stream_event(run_id: str, event: dict, created_at: datetime | None = None) -> str | None:
"""Synchronously publish a task-run event to Redis.
This is intended for sync Django model/view code that needs to mirror
@@ -515,7 +516,7 @@ def publish_task_run_stream_event(run_id: str, event: dict) -> str | None:
"""
async def _publish() -> str:
- redis_stream = TaskRunRedisStream(get_task_run_stream_key(run_id))
+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(run_id), created_at)
return await redis_stream.write_event(event)
try:
@@ -525,11 +526,11 @@ def publish_task_run_stream_event(run_id: str, event: dict) -> str | None:
return None
-def publish_task_run_stream_complete(run_id: str) -> None:
+def publish_task_run_stream_complete(run_id: str, created_at: datetime | None = None) -> 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))
+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(run_id), created_at)
await redis_stream.mark_complete()
try:
diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
index 91fbb883d65c..e03484a6c6e2 100644
--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
@@ -5,6 +5,7 @@ from temporalio import activity
from posthog.temporal.common.utils import asyncify
+from products.tasks.backend.models import TaskRun
from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.stream.redis_stream import publish_task_run_stream_complete
from products.tasks.backend.temporal.exceptions import SandboxNotFoundError
@@ -46,7 +47,14 @@ def cleanup_sandbox(input: CleanupSandboxInput) -> None:
logger.warning("cleanup_sandbox_destroy_failed", extra={"sandbox_id": input.sandbox_id}, exc_info=True)
if input.complete_stream_on_cleanup and input.run_id and stream_completion_safe:
- publish_task_run_stream_complete(input.run_id)
+ created_at = None
+ try:
+ created_at = TaskRun.objects.filter(id=input.run_id).values_list("created_at", flat=True).first()
+ except Exception:
+ logger.warning(
+ "cleanup_sandbox_created_at_lookup_failed", extra={"run_id": input.run_id}, exc_info=True
+ )
+ publish_task_run_stream_complete(input.run_id, created_at)
logger.info(
"cleanup_sandbox_stream_completion_published",
extra={"sandbox_id": input.sandbox_id, "run_id": input.run_id},
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 825bd150c48a..9ad6e61c20ed 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
@@ -59,11 +59,12 @@ async def relay_sandbox_events(input: RelaySandboxEventsInput) -> None:
if validation_error:
raise ValueError(f"Invalid sandbox URL: {validation_error}")
+ task_run = await TaskRunModel.objects.select_related("task__created_by").aget(id=input.run_id)
+
stream_key = get_task_run_stream_key(input.run_id)
- redis_stream = TaskRunRedisStream(stream_key)
+ redis_stream = TaskRunRedisStream(stream_key, task_run.created_at)
await redis_stream.initialize()
- task_run = await TaskRunModel.objects.select_related("task__created_by").aget(id=input.run_id)
created_by = task_run.task.created_by
connection_token = create_sandbox_connection_token(
task_run=task_run,
diff --git a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
index 6342866db62e..03c667c3d770 100644
--- a/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/send_followup_to_sandbox.py
@@ -1,16 +1,17 @@
import json
import time
from dataclasses import dataclass
+from datetime import datetime
from typing import Any
import structlog
-from django_redis import get_redis_connection
from temporalio import activity
from posthog.temporal.common.utils import close_db_connections
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.redis import get_tasks_stream_redis_sync
from products.tasks.backend.services.agent_command import (
FOLLOWUP_TIMEOUT_SECONDS,
REFRESH_TIMEOUT_SECONDS,
@@ -79,7 +80,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:
artifacts, missing_artifact_ids = get_task_run_artifacts_by_id(task_run, artifact_ids)
if missing_artifact_ids:
error_msg = f"Artifacts not found on this run: {', '.join(missing_artifact_ids)}"
- _write_error_and_complete(input.run_id, error_msg)
+ _write_error_and_complete(input.run_id, error_msg, task_run.created_at)
raise RuntimeError(f"send_followup failed: {error_msg}")
result = send_user_message(
@@ -97,7 +98,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:
)
if result.success:
- _write_turn_complete(input.run_id, _get_stop_reason(result.data))
+ _write_turn_complete(input.run_id, _get_stop_reason(result.data), task_run.created_at)
logger.info("send_followup_delivered", run_id=input.run_id)
else:
logger.warning(
@@ -107,7 +108,7 @@ def send_followup_to_sandbox(input: SendFollowupToSandboxInput) -> None:
status_code=result.status_code,
)
error_msg = result.error or "Failed to send message to sandbox"
- _write_error_and_complete(input.run_id, error_msg)
+ _write_error_and_complete(input.run_id, error_msg, task_run.created_at)
# Propagate failure to the workflow.
raise RuntimeError(f"send_followup failed: {error_msg}")
@@ -208,7 +209,9 @@ def _get_stop_reason(result_data: dict[str, Any] | None) -> str:
return stop_reason if isinstance(stop_reason, str) and stop_reason else STOP_REASON_END_TURN
-def _write_turn_complete(run_id: str, stop_reason: str = STOP_REASON_END_TURN) -> None:
+def _write_turn_complete(
+ run_id: str, stop_reason: str = STOP_REASON_END_TURN, created_at: datetime | None = None
+) -> None:
"""Write a synthetic turn_complete event to the Redis stream."""
stream_key = get_task_run_stream_key(run_id)
event = {
@@ -218,14 +221,14 @@ def _write_turn_complete(run_id: str, stop_reason: str = STOP_REASON_END_TURN) -
"params": {"source": "posthog", "stopReason": stop_reason},
},
}
- conn = get_redis_connection("default")
+ conn = get_tasks_stream_redis_sync(created_at)
conn.xadd(stream_key, {"data": json.dumps(event)}, maxlen=2000)
-def _write_error_and_complete(run_id: str, error_message: str) -> None:
+def _write_error_and_complete(run_id: str, error_message: str, created_at: datetime | None = None) -> None:
"""Write an error event followed by turn_complete to the Redis stream."""
stream_key = get_task_run_stream_key(run_id)
- conn = get_redis_connection("default")
+ conn = get_tasks_stream_redis_sync(created_at)
error_event = {
"type": "notification",
@@ -235,4 +238,4 @@ def _write_error_and_complete(run_id: str, error_message: str) -> None:
},
}
conn.xadd(stream_key, {"data": json.dumps(error_event)}, maxlen=2000)
- _write_turn_complete(run_id)
+ _write_turn_complete(run_id, created_at=created_at)
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
index 1ed7ca956485..ec809611483a 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
@@ -82,7 +82,7 @@ def test_cleanup_sandbox_completes_stream_when_requested(activity_environment, m
sandbox.execute.assert_not_called()
sandbox.destroy.assert_called_once_with()
- publish_complete.assert_called_once_with("run-123")
+ publish_complete.assert_called_once_with("run-123", None)
@pytest.mark.django_db
@@ -134,7 +134,7 @@ def test_cleanup_sandbox_completes_stream_when_sandbox_is_already_gone(activity_
),
)
- publish_complete.assert_called_once_with("run-123")
+ publish_complete.assert_called_once_with("run-123", None)
@pytest.mark.skipif(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
index f29eff1923e0..b8647e1ef0d0 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py
@@ -1,6 +1,7 @@
import json
import asyncio
import importlib
+from datetime import datetime
from types import SimpleNamespace
from typing import cast
@@ -196,7 +197,7 @@ class TestRelaySandboxEventsCancellation:
)
class StubTaskRunRedisStream:
- def __init__(self, stream_key: str) -> None:
+ def __init__(self, stream_key: str, created_at: datetime | None = None) -> None:
self.stream_key = stream_key
async def initialize(self) -> None:
@@ -213,7 +214,9 @@ class TestRelaySandboxEventsCancellation:
return self
async def aget(self, id: str) -> SimpleNamespace:
- return SimpleNamespace(task=SimpleNamespace(created_by=SimpleNamespace(id=123)))
+ return SimpleNamespace(
+ task=SimpleNamespace(created_by=SimpleNamespace(id=123)), created_at=datetime(2026, 1, 1)
+ )
async def fake_relay_loop(**_kwargs: object) -> None:
raise asyncio.CancelledError
@@ -510,7 +513,7 @@ class TestRelaySandboxEventsErrorHandling:
)
class StubTaskRunRedisStream:
- def __init__(self, stream_key: str) -> None:
+ def __init__(self, stream_key: str, created_at: datetime | None = None) -> None:
self.stream_key = stream_key
async def initialize(self) -> None:
@@ -527,7 +530,9 @@ class TestRelaySandboxEventsErrorHandling:
return self
async def aget(self, id: str) -> SimpleNamespace:
- return SimpleNamespace(task=SimpleNamespace(created_by=SimpleNamespace(id=123)))
+ return SimpleNamespace(
+ task=SimpleNamespace(created_by=SimpleNamespace(id=123)), created_at=datetime(2026, 1, 1)
+ )
async def fake_relay_loop(**_kwargs: object) -> None:
raise RuntimeError("relay error")
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py
index 680d2482d0bd..c9033710dbce 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_send_followup_to_sandbox.py
@@ -25,10 +25,12 @@ class TestGetStopReason(BaseTest):
class TestWriteTurnComplete(BaseTest):
- @patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_redis_connection")
- def test_writes_stop_reason_to_synthetic_event(self, mock_get_redis_connection):
+ @patch(
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_tasks_stream_redis_sync"
+ )
+ def test_writes_stop_reason_to_synthetic_event(self, mock_get_tasks_stream_redis_sync):
mock_conn = MagicMock()
- mock_get_redis_connection.return_value = mock_conn
+ mock_get_tasks_stream_redis_sync.return_value = mock_conn
_write_turn_complete("run-123", "max_tokens")
@@ -39,11 +41,13 @@ class TestWriteTurnComplete(BaseTest):
class TestSendFollowupToSandbox(BaseTest):
- @patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_redis_connection")
+ @patch(
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_tasks_stream_redis_sync"
+ )
@patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.send_user_message")
@patch("products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.TaskRun.objects")
def test_propagates_stop_reason_from_command_result(
- self, mock_task_run_objects, mock_send_user_message, mock_get_redis_connection
+ self, mock_task_run_objects, mock_send_user_message, mock_get_tasks_stream_redis_sync
):
task_run = MagicMock()
task_run.task.created_by = None
@@ -54,7 +58,7 @@ class TestSendFollowupToSandbox(BaseTest):
)
mock_conn = MagicMock()
- mock_get_redis_connection.return_value = mock_conn
+ mock_get_tasks_stream_redis_sync.return_value = mock_conn
send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-123", message="hello"))
diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.py
index 989dac325136..8003e4279863 100644
--- a/products/tasks/backend/temporal/process_task/utils.py
+++ b/products/tasks/backend/temporal/process_task/utils.py
@@ -6,7 +6,6 @@ from typing import TYPE_CHECKING, Any, Optional
from urllib.parse import urlparse
from django.conf import settings
-from django.core.cache import cache
from pydantic import BaseModel
@@ -16,6 +15,7 @@ from posthog.temporal.oauth import TOKEN_EXPIRATION_SECONDS, PosthogMcpScopes, h
from products.mcp_store.backend.facade.api import get_active_installations
from products.tasks.backend.constants import InitialPermissionMode
+from products.tasks.backend.redis import get_tasks_cache
if TYPE_CHECKING:
from posthog.models.user import User
@@ -204,13 +204,13 @@ def mark_mcp_token_issued(run_id: str) -> None:
The cache entry self-expires after MCP_TOKEN_REFRESH_INTERVAL_SECONDS, so
`should_refresh_mcp_token` returns True again past that window.
"""
- cache.set(_mcp_token_issued_cache_key(run_id), True, timeout=MCP_TOKEN_REFRESH_INTERVAL_SECONDS)
+ get_tasks_cache().set(_mcp_token_issued_cache_key(run_id), True, timeout=MCP_TOKEN_REFRESH_INTERVAL_SECONDS)
def should_refresh_mcp_token(run_id: str) -> bool:
"""Return True if no MCP token has been issued for this run within the
last MCP_TOKEN_REFRESH_INTERVAL_SECONDS window."""
- return cache.get(_mcp_token_issued_cache_key(run_id)) is None
+ return get_tasks_cache().get(_mcp_token_issued_cache_key(run_id)) is None
@dataclass(frozen=True)
@@ -498,11 +498,13 @@ def _github_user_token_cache_key(run_id: str) -> str:
def cache_github_user_token(run_id: str, github_user_token: str) -> None:
- cache.set(_github_user_token_cache_key(run_id), github_user_token, timeout=GITHUB_USER_TOKEN_CACHE_TTL_SECONDS)
+ get_tasks_cache().set(
+ _github_user_token_cache_key(run_id), github_user_token, timeout=GITHUB_USER_TOKEN_CACHE_TTL_SECONDS
+ )
def get_cached_github_user_token(run_id: str) -> str | None:
- token = cache.get(_github_user_token_cache_key(run_id))
+ token = get_tasks_cache().get(_github_user_token_cache_key(run_id))
return token if isinstance(token, str) and token else None
diff --git a/products/tasks/backend/tests/test_redis_stream_routing.py b/products/tasks/backend/tests/test_redis_stream_routing.py
new file mode 100644
index 000000000000..84e89df5162a
--- /dev/null
+++ b/products/tasks/backend/tests/test_redis_stream_routing.py
@@ -0,0 +1,34 @@
+from datetime import UTC, datetime, timedelta
+
+from unittest.mock import patch
+
+from django.test import SimpleTestCase, override_settings
+
+from products.tasks.backend import redis as tasks_redis
+
+CUTOVER = datetime(2026, 6, 9, tzinfo=UTC)
+AFTER = CUTOVER + timedelta(seconds=1)
+BEFORE = CUTOVER - timedelta(seconds=1)
+
+
[email protected](tasks_redis, "TASKS_REDIS_STREAM_CUTOVER_AT", CUTOVER)
+class TestStreamRouting(SimpleTestCase):
+ @override_settings(TASKS_REDIS_URL=None, REDIS_URL="redis://shared")
+ def test_no_dedicated_url_always_uses_shared(self):
+ self.assertFalse(tasks_redis._use_dedicated_stream(AFTER))
+ self.assertEqual(tasks_redis._tasks_stream_redis_url(AFTER), "redis://shared")
+
+ @override_settings(TASKS_REDIS_URL="redis://dedicated", REDIS_URL="redis://shared")
+ def test_routes_by_cutover(self):
+ self.assertTrue(tasks_redis._use_dedicated_stream(CUTOVER))
+ self.assertTrue(tasks_redis._use_dedicated_stream(AFTER))
+ self.assertFalse(tasks_redis._use_dedicated_stream(BEFORE))
+
+ self.assertEqual(tasks_redis._tasks_stream_redis_url(AFTER), "redis://dedicated")
+ self.assertEqual(tasks_redis._tasks_stream_redis_url(BEFORE), "redis://shared")
+
+ @override_settings(TASKS_REDIS_URL="redis://dedicated", REDIS_URL="redis://shared")
+ def test_missing_created_at_uses_shared(self):
+ # Unknown created_at must not move a stream onto the dedicated instance.
+ self.assertFalse(tasks_redis._use_dedicated_stream(None))
+ self.assertEqual(tasks_redis._tasks_stream_redis_url(None), "redis://shared")