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): mirror run streams to redis only while watched (#92253)

Alessandro Pogliaghifda0a2c859af
diff --git a/ee/hogai/sandbox/executor.py b/ee/hogai/sandbox/executor.py
index 890d3385926f..eb4683928bad 100644
--- a/ee/hogai/sandbox/executor.py
+++ b/ee/hogai/sandbox/executor.py
@@ -23,7 +23,12 @@ from posthog.temporal.common.client import sync_connect
from products.posthog_ai.backend.models.assistant import Conversation
from products.tasks.backend.facade import api as tasks_facade
-from products.tasks.backend.facade.streams import TaskRunRedisStream, TaskRunStreamError, get_task_run_stream_key
+from products.tasks.backend.facade.streams import (
+ TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS,
+ TaskRunRedisStream,
+ TaskRunStreamError,
+ get_task_run_stream_key,
+)
from products.tasks.backend.facade.temporal import ProcessTaskWorkflow, dispatch_task_processing_workflow
from ee.hogai.api.serializers import ConversationMinimalSerializer
@@ -263,6 +268,7 @@ async def _sandbox_stream(
stream_key = get_task_run_stream_key(run_id)
redis_stream = TaskRunRedisStream(stream_key)
+ await redis_stream.refresh_watched()
if not await redis_stream.wait_for_stream():
logger.warning("sandbox_stream_wait_timeout", stream_key=stream_key, run_id=run_id)
@@ -282,7 +288,14 @@ async def _sandbox_stream(
async def _reader() -> None:
try:
- async for ev in redis_stream.read_stream(start_id=start_id):
+ async for item in redis_stream.read_stream_entries(
+ start_id=start_id,
+ keepalive_interval_seconds=TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS,
+ ):
+ await redis_stream.refresh_watched()
+ if item is None:
+ continue
+ _stream_id, ev = item
await event_queue.put(ev)
except TaskRunStreamError as exc:
await event_queue.put({"_error": str(exc)})
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 56309e7a044f..cb0e6f6498e0 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -176,6 +176,8 @@ TASK_RUN_LOGS_MIRROR_ORIGIN_PRODUCTS: list[str] = get_list(
TASK_RUN_LOGS_MIRROR_OTLP_URL: str | None = get_from_env("TASK_RUN_LOGS_MIRROR_OTLP_URL", None, optional=True)
TASK_RUN_LOGS_MIRROR_OTLP_TOKEN: str | None = get_from_env("TASK_RUN_LOGS_MIRROR_OTLP_TOKEN", None, optional=True)
+TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS: list[str] = get_list(os.getenv("TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS", ""))
+
TEMPORAL_LOG_LEVEL_PRODUCE: str = os.getenv("TEMPORAL_LOG_LEVEL_PRODUCE", "DEBUG")
TEMPORAL_EXTERNAL_LOGS_QUEUE_SIZE: int = get_from_env("TEMPORAL_EXTERNAL_LOGS_QUEUE_SIZE", 0, type_cast=int)
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 790e364a10d3..966eab4be2a8 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2166,12 +2166,13 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"wizard_head_branch",
"use_modal_directory_resume_snapshots",
"use_modal_vm_sandbox",
- # Rollout stamps written once at dispatch by _capture_run_feature_flags; a PATCHable
- # value would let a task controller bypass the org feature flags (for telemetry, that
- # means injecting the internal OTLP capture token into their sandbox and re-enabling
- # the run-log mirror with the rollout off).
+ # Rollout stamps written once at dispatch by _capture_run_feature_flags or at run
+ # creation; a PATCHable value would let a task controller bypass the org feature flags
+ # (for telemetry, that means injecting the internal OTLP capture token into their
+ # sandbox and re-enabling the run-log mirror with the rollout off).
AGENT_OTEL_TELEMETRY_STATE_KEY,
"sandbox_event_ingest_enabled",
+ "stream_presence_gated",
PR_LOOP_ENABLED_STATE_KEY,
"snapshot_external_id",
"snapshot_kind",
diff --git a/products/tasks/backend/facade/streams.py b/products/tasks/backend/facade/streams.py
index c4e9da1b0308..4fb9ae09d25d 100644
--- a/products/tasks/backend/facade/streams.py
+++ b/products/tasks/backend/facade/streams.py
@@ -7,12 +7,14 @@ stream client. The SSE stream view also reads the connection-wait tuning constan
dedicated-stream flag helper from here.
"""
+from products.tasks.backend.feature_flags import run_stream_presence_gated
from products.tasks.backend.logic.stream.event_ingest import handle_task_run_event_ingest
from products.tasks.backend.logic.stream.redis_stream import (
TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS,
TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS,
+ TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS,
TaskRunRedisStream,
TaskRunStreamError,
get_task_run_stream_key,
@@ -25,10 +27,12 @@ __all__ = [
"TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS",
"TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS",
"TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS",
+ "TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS",
"TaskRunRedisStream",
"TaskRunStreamError",
"get_task_run_stream_key",
"handle_task_run_event_ingest",
"reset_task_run_stream",
+ "run_stream_presence_gated",
"run_uses_dedicated_stream",
]
diff --git a/products/tasks/backend/feature_flags.py b/products/tasks/backend/feature_flags.py
index f38950b72f72..72c428b7d7ba 100644
--- a/products/tasks/backend/feature_flags.py
+++ b/products/tasks/backend/feature_flags.py
@@ -66,6 +66,15 @@ def is_workflow_dispatch_restart_enabled(organization_id: str, distinct_id: str)
return _is_workflow_dispatch_org_flag_enabled(WORKFLOW_DISPATCH_RESTART_FEATURE_FLAG, organization_id, distinct_id)
+def is_task_run_stream_presence_gated(origin_product: str) -> bool:
+ return origin_product in settings.TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS
+
+
+def run_stream_presence_gated(state: dict | None) -> bool:
+ """Pinned onto TaskRun.state at creation so writers and readers agree for the run's life; absent means ungated."""
+ return bool((state or {}).get("stream_presence_gated", False))
+
+
def is_dev_stack_image_bake_enabled() -> bool:
"""Gates the nightly prebaked dev-stack image bake (a paid Modal VM run per tick).
diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.py
index b64849e180b8..46b28274ddc2 100644
--- a/products/tasks/backend/logic/services/connection_token.py
+++ b/products/tasks/backend/logic/services/connection_token.py
@@ -12,6 +12,7 @@ import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
+from products.tasks.backend.feature_flags import run_stream_presence_gated
from products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS
if TYPE_CHECKING:
@@ -39,6 +40,7 @@ class SandboxEventIngestTokenPayload:
task_id: str
team_id: int
sandbox_id: str | None
+ presence_gated: bool = False
@dataclass(frozen=True)
@@ -53,6 +55,7 @@ class StreamReadTokenPayload:
run_id: str
task_id: str
team_id: int
+ presence_gated: bool = False
def _normalize_pem_key(key: str) -> str:
@@ -259,11 +262,12 @@ def create_sandbox_event_ingest_token(
active_sandbox_id = sandbox_id or (task_run.state or {}).get("sandbox_id")
if not isinstance(active_sandbox_id, str) or not active_sandbox_id:
raise ValueError("Task run has no active sandbox identity")
+ presence_gated = run_stream_presence_gated(task_run.state)
return _encode_run_scoped_token(
task_run,
SANDBOX_EVENT_INGEST_AUDIENCE,
ttl,
- {"sandbox_id": active_sandbox_id},
+ {"sandbox_id": active_sandbox_id, "presence_gated": presence_gated},
)
@@ -274,17 +278,21 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPa
task_id = payload.get("task_id")
team_id = payload.get("team_id")
sandbox_id = payload.get("sandbox_id")
+ presence_gated = payload.get("presence_gated", False)
if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:
raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
if sandbox_id is not None and (not isinstance(sandbox_id, str) or not sandbox_id):
raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
+ if not isinstance(presence_gated, bool):
+ raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
return SandboxEventIngestTokenPayload(
run_id=run_id,
task_id=task_id,
team_id=team_id,
sandbox_id=sandbox_id,
+ presence_gated=presence_gated,
)
@@ -297,7 +305,8 @@ def create_stream_read_token(task_run: TaskRun, ttl: timedelta = STREAM_READ_TOK
public key. Carries no user identity and grants one capability: reading this
task run's stream.
"""
- return _encode_run_scoped_token(task_run, STREAM_READ_AUDIENCE, ttl)
+ presence_gated = run_stream_presence_gated(task_run.state)
+ return _encode_run_scoped_token(task_run, STREAM_READ_AUDIENCE, ttl, {"presence_gated": presence_gated})
def validate_stream_read_token(token: str) -> StreamReadTokenPayload:
@@ -306,8 +315,11 @@ def validate_stream_read_token(token: str) -> StreamReadTokenPayload:
run_id = payload.get("run_id")
task_id = payload.get("task_id")
team_id = payload.get("team_id")
+ presence_gated = payload.get("presence_gated", False)
if not isinstance(run_id, str) or not isinstance(task_id, str) or type(team_id) is not int:
raise jwt.InvalidTokenError("Stream read token has invalid claims")
+ if not isinstance(presence_gated, bool):
+ raise jwt.InvalidTokenError("Stream read token has invalid claims")
- return StreamReadTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id)
+ return StreamReadTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id, presence_gated=presence_gated)
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index 5c3c25a7e756..6367bf81e5b3 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -29,6 +29,7 @@ from products.tasks.backend.logic.stream.redis_stream import (
TaskRunStreamSequenceGap,
get_task_run_stream_key,
)
+from products.tasks.backend.metrics import observe_stream_write_skipped
from products.tasks.backend.models import TaskRun
from products.tasks.backend.push_dispatcher import notify_task_run_turn_completed
@@ -125,7 +126,7 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,
await _send_json(send, error.status_code, error.payload)
return True
- redis_stream = TaskRunRedisStream(get_task_run_stream_key(claims.run_id))
+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(claims.run_id), presence_gated=claims.presence_gated)
try:
result = await _ingest_event_lines(
@@ -195,16 +196,18 @@ async def _ingest_event_lines(
sequence = parsed_line.sequence
event = parsed_line.event
rtk_savings_properties = _parse_rtk_savings_properties(claims, event)
- stream_id = await redis_stream.write_event_with_sequence(
+ write = await redis_stream.write_event_with_sequence(
event,
sequence,
pending_side_effect=RTK_SAVINGS_SIDE_EFFECT if rtk_savings_properties is not None else None,
)
await _capture_rtk_savings_if_needed(redis_stream, claims, sequence, rtk_savings_properties)
- if stream_id is None:
+ if not write.accepted:
result.duplicate += 1
result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())
continue
+ if write.skipped:
+ observe_stream_write_skipped("ingest")
result.accepted += 1
result.last_accepted_seq = sequence
diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.py
index c27e7304880b..bb02c2189dad 100644
--- a/products/tasks/backend/logic/stream/redis_stream.py
+++ b/products/tasks/backend/logic/stream/redis_stream.py
@@ -1,4 +1,5 @@
import json
+import time
import asyncio
from collections.abc import AsyncGenerator
from typing import Optional
@@ -8,8 +9,11 @@ from django.conf import settings
import structlog
import redis.exceptions as redis_exceptions
+from posthog.dataclasses import frozen
+
from products.tasks.backend.logic.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTL
from products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS
+from products.tasks.backend.metrics import observe_stream_write_skipped
from products.tasks.backend.redis import get_tasks_stream_redis_async, get_tasks_stream_redis_sync
logger = structlog.get_logger(__name__)
@@ -20,6 +24,9 @@ TASK_RUN_STREAM_MAX_LENGTH = 5_000
TASK_RUN_STREAM_TIMEOUT = SANDBOX_TTL_SECONDS
TASK_RUN_STREAM_COMPLETED_TIMEOUT = min(30 * 60, TASK_RUN_STREAM_TIMEOUT // 3)
TASK_RUN_STREAM_SEQUENCE_TIMEOUT = int(SANDBOX_EVENT_INGEST_TOKEN_TTL.total_seconds())
+TASK_RUN_STREAM_WATCHED_TIMEOUT = 5 * 60
+TASK_RUN_STREAM_WATCHED_CACHE_SECONDS = 2.0
+TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS = 120.0
TASK_RUN_STREAM_PREFIX = "task-run-stream:"
TASK_RUN_STREAM_READ_COUNT = 16
# XREAD BLOCK is push-based (XADD wakes the blocked client immediately), so a
@@ -59,6 +66,27 @@ def _stream_id_sort_key(stream_id: str) -> tuple[int, int]:
return (0, 0)
+@frozen
+class TaskRunStreamWriteResult:
+ """Outcome of a sequenced stream write.
+
+ ``accepted`` is whether the sequence advanced. ``stream_id`` is set only when the
+ event was also mirrored into the Redis stream; a presence-gated write with no
+ attached reader is accepted without a stream id.
+ """
+
+ accepted: bool
+ stream_id: str | None = None
+
+ @property
+ def skipped(self) -> bool:
+ return self.accepted and self.stream_id is None
+
+
+TASK_RUN_STREAM_WRITE_DUPLICATE = TaskRunStreamWriteResult(accepted=False)
+TASK_RUN_STREAM_WRITE_SKIPPED = TaskRunStreamWriteResult(accepted=True)
+
+
class TaskRunStreamError(Exception):
pass
@@ -114,6 +142,10 @@ def get_task_run_stream_first_activity_key(stream_key: str) -> str:
return f"{stream_key}:ingest-first-agent-activity"
+def get_task_run_stream_watched_key(stream_key: str) -> str:
+ return f"{stream_key}:watched"
+
+
def get_task_run_stream_side_effect_pending_key(stream_key: str, side_effect: str, sequence: int) -> str:
return f"{stream_key}:side-effect:{side_effect}:{sequence}:pending"
@@ -134,6 +166,8 @@ class TaskRunRedisStream:
use_dedicated: bool = False,
timeout: int = TASK_RUN_STREAM_TIMEOUT,
max_length: int = TASK_RUN_STREAM_MAX_LENGTH,
+ *,
+ presence_gated: bool = False,
):
self._stream_key = stream_key
self._redis_client = get_tasks_stream_redis_async(use_dedicated)
@@ -141,6 +175,9 @@ class TaskRunRedisStream:
self._sequence_timeout = max(timeout, TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
self._completed_timeout = min(timeout, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
self._max_length = max_length
+ self._presence_gated = presence_gated
+ self._watched_cached_until = 0.0
+ self._last_watched_refresh_at: float | None = None
async def initialize(self) -> None:
"""Set expiry on the stream key to prevent unbounded growth."""
@@ -294,14 +331,7 @@ class TaskRunRedisStream:
except redis_exceptions.RedisError:
raise TaskRunStreamError("Stream read error")
- async def write_event(self, event: dict, *, ttl: int | None = None) -> str:
- """Write a single event to the stream.
-
- Refreshes TTL on every write (sliding window) so long-running tasks
- don't expire mid-stream, unless `ttl` overrides it for terminal writes.
- This is especially important for the sync publish path
- (publish_task_run_stream_event) which bypasses initialize().
- """
+ async def _xadd_event(self, event: dict, *, ttl: int | None = None) -> str:
raw = json.dumps(event)
stream_id = await self._redis_client.xadd(
self._stream_key,
@@ -312,6 +342,32 @@ class TaskRunRedisStream:
await self._redis_client.expire(self._stream_key, self._timeout if ttl is None else ttl)
return _normalize_stream_id(stream_id)
+ async def _is_watched(self) -> bool:
+ """Return whether a reader is attached, caching only a positive answer."""
+ now = time.monotonic()
+ if now < self._watched_cached_until:
+ return True
+ watched = bool(await self._redis_client.exists(get_task_run_stream_watched_key(self._stream_key)))
+ if watched:
+ self._watched_cached_until = now + TASK_RUN_STREAM_WATCHED_CACHE_SECONDS
+ return watched
+
+ async def write_event(self, event: dict, *, ttl: int | None = None) -> str | None:
+ """Write a single non-terminal event to the stream.
+
+ Refreshes TTL on every write (sliding window) so long-running tasks
+ don't expire mid-stream, unless `ttl` overrides it for terminal writes.
+ This is especially important for the sync publish path
+ (publish_task_run_stream_event) which bypasses initialize().
+
+ Returns None when the stream is presence-gated and no reader is attached.
+ Terminal sentinels bypass this gate.
+ """
+ if self._presence_gated and not await self._is_watched():
+ observe_stream_write_skipped("relay")
+ return None
+ return await self._xadd_event(event, ttl=ttl)
+
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)
@@ -319,6 +375,28 @@ class TaskRunRedisStream:
await self._redis_client.expire(sequence_key, self._sequence_timeout)
return _normalize_redis_int(last_sequence_raw)
+ async def mark_watched(self) -> None:
+ """Record that a reader is attached, so presence-gated writes keep mirroring."""
+ await self._redis_client.set(
+ get_task_run_stream_watched_key(self._stream_key),
+ "1",
+ ex=TASK_RUN_STREAM_WATCHED_TIMEOUT,
+ )
+
+ async def refresh_watched(self) -> None:
+ """Throttled, best-effort mark_watched; the throttle only advances on success so failures retry."""
+ now = time.monotonic()
+ if (
+ self._last_watched_refresh_at is not None
+ and now - self._last_watched_refresh_at < TASK_RUN_STREAM_WATCHED_REFRESH_INTERVAL_SECONDS
+ ):
+ return
+ try:
+ await self.mark_watched()
+ self._last_watched_refresh_at = now
+ except Exception:
+ logger.warning("task_run_stream_mark_watched_failed", stream_key=self._stream_key, exc_info=True)
+
async def set_agent_active(self, active: bool) -> None:
await self._redis_client.set(
get_task_run_stream_agent_active_key(self._stream_key),
@@ -387,37 +465,41 @@ class TaskRunRedisStream:
async def write_event_with_sequence(
self, event: dict, sequence: int, *, pending_side_effect: str | None = None
- ) -> str | None:
+ ) -> TaskRunStreamWriteResult:
"""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.
+ A duplicate sequence that was already accepted on an earlier connection is
+ rejected. On a presence-gated stream with no attached reader the sequence
+ still advances but the event is not mirrored into the stream.
"""
if settings.TEST:
return await self._write_event_with_sequence_for_tests(event, sequence, pending_side_effect)
sequence_key = get_task_run_stream_sequence_key(self._stream_key)
completed_key = get_task_run_stream_completed_key(self._stream_key)
+ watched_key = get_task_run_stream_watched_key(self._stream_key)
pending_side_effect_key = (
get_task_run_stream_side_effect_pending_key(self._stream_key, pending_side_effect, sequence)
if pending_side_effect is not None
else None
)
- raw = json.dumps(event)
while True:
async with self._redis_client.pipeline(transaction=True) as pipe:
try:
- await pipe.watch(sequence_key, completed_key)
+ if self._presence_gated:
+ await pipe.watch(sequence_key, completed_key, watched_key)
+ else:
+ await pipe.watch(sequence_key, completed_key)
last_sequence_raw = await pipe.get(sequence_key)
last_sequence = _normalize_redis_int(last_sequence_raw)
if await pipe.exists(completed_key):
raise TaskRunStreamAlreadyCompleted(last_accepted_seq=last_sequence)
if sequence <= last_sequence:
- return None
+ return TASK_RUN_STREAM_WRITE_DUPLICATE
if sequence != last_sequence + 1:
raise TaskRunStreamSequenceGap(
@@ -426,35 +508,41 @@ class TaskRunRedisStream:
last_accepted_seq=last_sequence,
)
+ mirror = not self._presence_gated or bool(await pipe.exists(watched_key))
+
pipe.multi()
- pipe.xadd(
- self._stream_key,
- {DATA_KEY: raw},
- maxlen=self._max_length,
- approximate=True,
- )
- pipe.expire(self._stream_key, self._timeout)
+ if mirror:
+ pipe.xadd(
+ self._stream_key,
+ {DATA_KEY: json.dumps(event)},
+ maxlen=self._max_length,
+ approximate=True,
+ )
+ pipe.expire(self._stream_key, self._timeout)
pipe.set(sequence_key, sequence, ex=self._sequence_timeout)
if pending_side_effect_key is not None:
pipe.set(pending_side_effect_key, "1", ex=self._sequence_timeout)
results = await pipe.execute()
- return _normalize_stream_id(results[0])
+ if not mirror:
+ return TASK_RUN_STREAM_WRITE_SKIPPED
+ return TaskRunStreamWriteResult(accepted=True, stream_id=_normalize_stream_id(results[0]))
except redis_exceptions.WatchError:
continue
async def _write_event_with_sequence_for_tests(
self, event: dict, sequence: int, pending_side_effect: str | None = None
- ) -> str | None:
+ ) -> TaskRunStreamWriteResult:
"""Apply sequencing semantics without WATCH/MULTI for fakeredis."""
sequence_key = get_task_run_stream_sequence_key(self._stream_key)
completed_key = get_task_run_stream_completed_key(self._stream_key)
+ watched_key = get_task_run_stream_watched_key(self._stream_key)
last_sequence = await self.get_last_sequence()
if await self._redis_client.exists(completed_key):
raise TaskRunStreamAlreadyCompleted(last_accepted_seq=last_sequence)
if sequence <= last_sequence:
- return None
+ return TASK_RUN_STREAM_WRITE_DUPLICATE
if sequence != last_sequence + 1:
raise TaskRunStreamSequenceGap(
@@ -463,12 +551,15 @@ class TaskRunRedisStream:
last_accepted_seq=last_sequence,
)
- stream_id = await self.write_event(event)
+ mirror = not self._presence_gated or bool(await self._redis_client.exists(watched_key))
+ stream_id = await self._xadd_event(event) if mirror else None
await self._redis_client.set(sequence_key, sequence, ex=self._sequence_timeout)
if pending_side_effect is not None:
pending_key = get_task_run_stream_side_effect_pending_key(self._stream_key, pending_side_effect, sequence)
await self._redis_client.set(pending_key, "1", ex=self._sequence_timeout)
- return stream_id
+ if stream_id is None:
+ return TASK_RUN_STREAM_WRITE_SKIPPED
+ return TaskRunStreamWriteResult(accepted=True, stream_id=stream_id)
async def mark_complete(self) -> None:
"""Write a completion sentinel to signal end of stream."""
@@ -507,7 +598,7 @@ class TaskRunRedisStream:
await self._redis_client.expire(self._stream_key, self._completed_timeout)
return
- await self.write_event({"type": "STREAM_STATUS", "status": "complete"}, ttl=self._completed_timeout)
+ await self._xadd_event({"type": "STREAM_STATUS", "status": "complete"}, ttl=self._completed_timeout)
await self._redis_client.set(completed_key, "1", ex=self._sequence_timeout)
async def mark_complete_after_sequence(self, final_sequence: int) -> None:
@@ -568,14 +659,14 @@ class TaskRunRedisStream:
last_accepted_seq=last_sequence,
)
- await self.write_event({"type": "STREAM_STATUS", "status": "complete"}, ttl=self._completed_timeout)
+ await self._xadd_event({"type": "STREAM_STATUS", "status": "complete"}, ttl=self._completed_timeout)
if last_sequence_raw is not None:
await self._redis_client.expire(sequence_key, self._sequence_timeout)
await self._redis_client.set(completed_key, "1", ex=self._sequence_timeout)
async def mark_error(self, error: str) -> None:
"""Write an error sentinel to signal stream failure."""
- await self.write_event(
+ await self._xadd_event(
{"type": "STREAM_STATUS", "status": "error", "error": error[:500]}, ttl=self._completed_timeout
)
await self._redis_client.set(
@@ -591,6 +682,7 @@ class TaskRunRedisStream:
heartbeat_key = get_task_run_stream_heartbeat_key(self._stream_key)
first_command_key = get_task_run_stream_first_command_key(self._stream_key)
first_activity_key = get_task_run_stream_first_activity_key(self._stream_key)
+ watched_key = get_task_run_stream_watched_key(self._stream_key)
deleted = await self._redis_client.delete(
self._stream_key,
sequence_key,
@@ -599,6 +691,7 @@ class TaskRunRedisStream:
heartbeat_key,
first_command_key,
first_activity_key,
+ watched_key,
)
return _normalize_redis_int(deleted) > 0
except Exception:
@@ -607,6 +700,7 @@ class TaskRunRedisStream:
def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:
+ """Clear a run's stream state for a restart, keeping the watched lease so an attached reader stays marked."""
stream_key = get_task_run_stream_key(run_id)
sequence_key = get_task_run_stream_sequence_key(stream_key)
completed_key = get_task_run_stream_completed_key(stream_key)
@@ -632,7 +726,9 @@ def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:
return False
-def publish_task_run_stream_event(run_id: str, event: dict, use_dedicated: bool = False) -> str | None:
+def publish_task_run_stream_event(
+ run_id: str, event: dict, use_dedicated: bool = False, *, presence_gated: bool = False
+) -> str | None:
"""Synchronously publish a task-run event to Redis.
This is intended for sync Django model/view code that needs to mirror
@@ -641,11 +737,17 @@ def publish_task_run_stream_event(run_id: str, event: dict, use_dedicated: bool
Bouncing back to the loop via ``async_to_sync`` would block that executor
thread. A sync client does the I/O inline on the calling thread with no
event-loop round-trip.
+
+ Returns None both when a presence-gated run has no attached reader and when the
+ write failed; no caller distinguishes the two, and the skip is counted separately.
"""
stream_key = get_task_run_stream_key(run_id)
client = get_tasks_stream_redis_sync(use_dedicated)
- raw = json.dumps(event)
try:
+ if presence_gated and not client.exists(get_task_run_stream_watched_key(stream_key)):
+ observe_stream_write_skipped("mirror")
+ return None
+ raw = json.dumps(event)
stream_id = client.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)
completed = client.exists(get_task_run_stream_completed_key(stream_key))
client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT if completed else TASK_RUN_STREAM_TIMEOUT)
diff --git a/products/tasks/backend/logic/stream/tests/test_redis_stream.py b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
index 49f1d08f1462..8d309607f22e 100644
--- a/products/tasks/backend/logic/stream/tests/test_redis_stream.py
+++ b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
@@ -3,12 +3,14 @@ from collections.abc import Awaitable, Callable
from uuid import uuid4
import pytest
+from unittest.mock import patch
from products.tasks.backend.logic.stream.redis_stream import (
DATA_KEY,
TASK_RUN_STREAM_COMPLETED_TIMEOUT,
TASK_RUN_STREAM_SEQUENCE_TIMEOUT,
TASK_RUN_STREAM_TIMEOUT,
+ TASK_RUN_STREAM_WATCHED_TIMEOUT,
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
@@ -16,6 +18,7 @@ from products.tasks.backend.logic.stream.redis_stream import (
_stream_id_sort_key,
get_task_run_stream_completed_key,
get_task_run_stream_key,
+ get_task_run_stream_watched_key,
publish_task_run_stream_complete,
publish_task_run_stream_event,
reset_task_run_stream,
@@ -23,8 +26,8 @@ from products.tasks.backend.logic.stream.redis_stream import (
from products.tasks.backend.redis import get_tasks_stream_redis_sync
-def _new_stream(timeout: int = 60) -> TaskRunRedisStream:
- return TaskRunRedisStream(f"task-run-stream:test:{uuid4()}", timeout=timeout)
+def _new_stream(timeout: int = 60, *, presence_gated: bool = False) -> TaskRunRedisStream:
+ return TaskRunRedisStream(f"task-run-stream:test:{uuid4()}", timeout=timeout, presence_gated=presence_gated)
async def _read_stream_events(redis_stream: TaskRunRedisStream) -> list[dict]:
@@ -36,9 +39,10 @@ async def _read_stream_events(redis_stream: TaskRunRedisStream) -> list[dict]:
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)
+ write = await redis_stream.write_event_with_sequence({"type": "message"}, 1)
- assert stream_id is not None
+ assert write.accepted is True
+ assert write.stream_id is not None
assert await redis_stream.get_last_sequence() == 1
assert await _read_stream_events(redis_stream) == [{"type": "message"}]
finally:
@@ -65,17 +69,198 @@ async def test_write_event_with_sequence_rejects_sequence_gap() -> None:
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)
+ first_write = await redis_stream.write_event_with_sequence({"type": "first"}, 1)
+ duplicate_write = await redis_stream.write_event_with_sequence({"type": "duplicate"}, 1)
- assert first_stream_id is not None
- assert duplicate_stream_id is None
+ assert first_write.stream_id is not None
+ assert duplicate_write.accepted is False
assert await redis_stream.get_last_sequence() == 1
assert await _read_stream_events(redis_stream) == [{"type": "first"}]
finally:
await redis_stream.delete_stream()
+ "presence_gated,watched,expect_mirrored",
+ [
+ pytest.param(True, False, False, id="gated_unwatched_skips"),
+ pytest.param(True, True, True, id="gated_watched_mirrors"),
+ pytest.param(False, False, True, id="ungated_always_mirrors"),
+ ],
+)
+async def test_write_event_with_sequence_mirrors_only_when_presence_allows(
+ presence_gated: bool, watched: bool, expect_mirrored: bool
+) -> None:
+ redis_stream = _new_stream(presence_gated=presence_gated)
+ try:
+ if watched:
+ await redis_stream.mark_watched()
+
+ write = await redis_stream.write_event_with_sequence({"type": "message"}, 1)
+
+ assert write.accepted is True
+ assert write.skipped is not expect_mirrored
+ assert (write.stream_id is not None) is expect_mirrored
+ assert await redis_stream.get_last_sequence() == 1
+ assert await _read_stream_events(redis_stream) == ([{"type": "message"}] if expect_mirrored else [])
+ finally:
+ await redis_stream.delete_stream()
+
+
+async def test_mark_watched_expires_so_presence_lapses() -> None:
+ redis_stream = _new_stream(presence_gated=True)
+ try:
+ await redis_stream.mark_watched()
+
+ watched_ttl = await redis_stream._redis_client.ttl(get_task_run_stream_watched_key(redis_stream._stream_key))
+
+ assert 0 < watched_ttl <= TASK_RUN_STREAM_WATCHED_TIMEOUT
+ finally:
+ await redis_stream.delete_stream()
+
+
+async def test_refresh_watched_retries_after_failure_and_throttles_after_success() -> None:
+ redis_stream = _new_stream()
+ watched_key = get_task_run_stream_watched_key(redis_stream._stream_key)
+ try:
+ mark_calls = 0
+ real_mark_watched = TaskRunRedisStream.mark_watched
+
+ async def flaky_mark_watched(stream: TaskRunRedisStream) -> None:
+ nonlocal mark_calls
+ mark_calls += 1
+ if mark_calls == 1:
+ raise ConnectionError("redis unavailable")
+ await real_mark_watched(stream)
+
+ with patch.object(TaskRunRedisStream, "mark_watched", flaky_mark_watched):
+ await redis_stream.refresh_watched()
+ assert not await redis_stream._redis_client.exists(watched_key)
+
+ await redis_stream.refresh_watched()
+ assert await redis_stream._redis_client.exists(watched_key)
+
+ await redis_stream.refresh_watched()
+ assert mark_calls == 2
+ finally:
+ await redis_stream.delete_stream()
+
+
+async def test_presence_gated_skip_still_advances_sequence_bookkeeping() -> None:
+ redis_stream = _new_stream(presence_gated=True)
+ try:
+ skipped = await redis_stream.write_event_with_sequence({"type": "first"}, 1)
+ duplicate = await redis_stream.write_event_with_sequence({"type": "first-again"}, 1)
+ await redis_stream.mark_watched()
+ mirrored = await redis_stream.write_event_with_sequence({"type": "second"}, 2)
+
+ assert skipped.skipped is True
+ assert duplicate.accepted is False
+ assert mirrored.stream_id is not None
+ assert await redis_stream.get_last_sequence() == 2
+ assert await _read_stream_events(redis_stream) == [{"type": "second"}]
+ finally:
+ await redis_stream.delete_stream()
+
+
+ "write_sentinel,expected_sentinel",
+ [
+ pytest.param(
+ lambda stream: stream.mark_complete_after_sequence(1),
+ {"type": "STREAM_STATUS", "status": "complete"},
+ id="mark_complete_after_sequence",
+ ),
+ pytest.param(
+ lambda stream: stream.mark_complete(),
+ {"type": "STREAM_STATUS", "status": "complete"},
+ id="mark_complete",
+ ),
+ pytest.param(
+ lambda stream: stream.mark_error("boom"),
+ {"type": "STREAM_STATUS", "status": "error", "error": "boom"},
+ id="mark_error",
+ ),
+ ],
+)
+async def test_terminal_sentinel_is_written_on_unwatched_presence_gated_stream(
+ write_sentinel: Callable[[TaskRunRedisStream], Awaitable[None]], expected_sentinel: dict
+) -> None:
+ redis_stream = _new_stream(presence_gated=True)
+ try:
+ await redis_stream.write_event_with_sequence({"type": "message"}, 1)
+
+ await write_sentinel(redis_stream)
+
+ assert await _read_stream_events(redis_stream) == [expected_sentinel]
+ finally:
+ await redis_stream.delete_stream()
+
+
+ "presence_gated,watched,expect_mirrored",
+ [
+ pytest.param(True, False, False, id="gated_unwatched_skips"),
+ pytest.param(True, True, True, id="gated_watched_mirrors"),
+ pytest.param(False, False, True, id="ungated_always_mirrors"),
+ ],
+)
+async def test_write_event_mirrors_only_when_presence_allows(
+ presence_gated: bool, watched: bool, expect_mirrored: bool
+) -> None:
+ redis_stream = _new_stream(presence_gated=presence_gated)
+ try:
+ if watched:
+ await redis_stream.mark_watched()
+
+ stream_id = await redis_stream.write_event({"type": "relayed"})
+
+ assert (stream_id is not None) is expect_mirrored
+ assert await _read_stream_events(redis_stream) == ([{"type": "relayed"}] if expect_mirrored else [])
+ finally:
+ await redis_stream.delete_stream()
+
+
[email protected]("watched", [False, True])
+def test_publish_task_run_stream_event_honors_presence_gating(watched: bool) -> None:
+ run_id = f"test:{uuid4()}"
+ stream_key = get_task_run_stream_key(run_id)
+ client = get_tasks_stream_redis_sync()
+ try:
+ if watched:
+ client.set(get_task_run_stream_watched_key(stream_key), "1", ex=TASK_RUN_STREAM_WATCHED_TIMEOUT)
+
+ stream_id = publish_task_run_stream_event(run_id, {"type": "message"}, presence_gated=True)
+
+ assert (stream_id is not None) is watched
+ assert client.xlen(stream_key) == (1 if watched else 0)
+ finally:
+ reset_task_run_stream(run_id)
+
+
+def test_reset_task_run_stream_keeps_watched_lease() -> None:
+ run_id = f"test:{uuid4()}"
+ stream_key = get_task_run_stream_key(run_id)
+ watched_key = get_task_run_stream_watched_key(stream_key)
+ client = get_tasks_stream_redis_sync()
+ try:
+ client.set(watched_key, "1", ex=TASK_RUN_STREAM_WATCHED_TIMEOUT)
+ client.xadd(stream_key, {"data": "{}"})
+
+ assert reset_task_run_stream(run_id)
+
+ assert not client.exists(stream_key)
+ assert client.exists(watched_key)
+ finally:
+ client.delete(watched_key)
+
+
@pytest.mark.parametrize(
"terminal",
[
@@ -225,6 +410,7 @@ async def test_resume_point_trimmed_only_when_cursor_predates_surviving_entries(
try:
first_id = await redis_stream.write_event({"type": "a"})
second_id = await redis_stream.write_event({"type": "b"})
+ assert first_id is not None and second_id is not None
# Special-case cursors and a still-present cursor are never gaps.
assert await redis_stream.resume_point_trimmed("0") is False
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index 85834a70af0d..6026e7057bfe 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -23,6 +23,7 @@ DevStackImageBakeOutcome = Literal["succeeded", "bake_failed", "failed", "dispat
# client_disconnect — client went away (GeneratorExit) before completion
# rotated — per-connection cap reached; clean EOF, client resumes
StreamConnectionOutcome = Literal["completed", "stream_error", "unavailable", "client_disconnect", "rotated"]
+StreamWriteSkippedPath = Literal["ingest", "mirror", "relay"]
_ALLOWED_MODES = {"background", "interactive"}
_ALLOWED_RUN_SOURCES = {"manual", "signal_report"}
_ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}
@@ -245,6 +246,12 @@ TASK_RUN_STREAM_RESUME_GAP_TOTAL = Counter(
labelnames=["origin_product"],
)
+TASK_RUN_STREAM_WRITE_SKIPPED_TOTAL = Counter(
+ "posthog_tasks_task_run_stream_write_skipped_total",
+ "Task-run events not mirrored into Redis because presence gating found no attached reader",
+ labelnames=["path"],
+)
+
TASK_RUN_AGENT_FAILURE_TOTAL = Counter(
"posthog_tasks_agent_turn_failed_total",
"TaskRun transitions to FAILED via the API facade (agent-server turn failures)",
@@ -586,6 +593,10 @@ def observe_stream_resume_gap(origin_product: str) -> None:
TASK_RUN_STREAM_RESUME_GAP_TOTAL.labels(origin_product=origin_product).inc()
+def observe_stream_write_skipped(path: StreamWriteSkippedPath) -> None:
+ TASK_RUN_STREAM_WRITE_SKIPPED_TOTAL.labels(path=path).inc()
+
+
def observe_task_run_failed(properties: dict[str, object]) -> None:
TASK_RUN_FAILED_TOTAL.labels(
origin_product=_metric_label(properties.get("origin_product")),
diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.py
index 167b7e4a2561..b01156c7353e 100644
--- a/products/tasks/backend/models.py
+++ b/products/tasks/backend/models.py
@@ -42,6 +42,7 @@ from posthog.uuidt import uuid7
from products.tasks.backend.constants import DEFAULT_TRUSTED_DOMAINS, PR_LOOP_ENABLED_STATE_KEY
from products.tasks.backend.error_telemetry import truncate_error_message
+from products.tasks.backend.feature_flags import is_task_run_stream_presence_gated, run_stream_presence_gated
from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_event
from products.tasks.backend.metrics import observe_task_run_created, observe_task_run_dispatch_callback
from products.tasks.backend.pr_urls import read_pr_urls
@@ -675,6 +676,7 @@ class Task(DeletedMetaFields, models.Model):
# Pin the stream-routing decision once so every reader/writer agrees for this run's life.
state.setdefault("use_dedicated_stream", dedicated_stream)
+ state.setdefault("stream_presence_gated", is_task_run_stream_presence_gated(task.origin_product))
is_resume = bool(resume_from_run_id)
has_pending = _has_pending_user_input(extra_state or {})
stamp_pending_user_message_id(state)
@@ -2772,7 +2774,12 @@ class TaskRun(models.Model):
}
def publish_stream_event(self, event: dict[str, Any]) -> None:
- publish_task_run_stream_event(str(self.id), event, run_uses_dedicated_stream(self.state))
+ publish_task_run_stream_event(
+ str(self.id),
+ event,
+ run_uses_dedicated_stream(self.state),
+ presence_gated=run_stream_presence_gated(self.state),
+ )
def publish_stream_state_event(self) -> None:
self.publish_stream_event(self.build_stream_state_event())
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index b41d1bab7702..5774158f0b4b 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -96,6 +96,7 @@ from products.tasks.backend.facade.streams import (
TaskRunRedisStream,
TaskRunStreamError,
get_task_run_stream_key,
+ run_stream_presence_gated,
run_uses_dedicated_stream,
)
from products.tasks.backend.presentation.serializers import (
@@ -3188,6 +3189,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
"finished — reconnect with the `Last-Event-ID` header set to the last received event id to "
"resume without gaps or duplicates. Only treat the stream as complete when the run itself "
"reaches a terminal status.\n\n"
+ "Resume guarantees cover mirrored events only: on runs where live mirroring is "
+ "presence-gated, events produced while no viewer was connected are not in the live stream. "
+ "Reload the run's session logs to recover the agent's output; run-state and progress "
+ "frames are not in those logs, so refetch the run itself for its current state.\n\n"
"`?start=latest` consumers must also carry `Last-Event-ID` across reconnects: reconnecting "
"without it re-resolves to the then-current latest event, silently skipping anything published "
"while disconnected.\n\n"
@@ -3232,6 +3237,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
start_latest = request.GET.get("start") == "latest"
format_sse_event = self._format_sse_event
origin_product = stream_info.origin_product
+ presence_gated = run_stream_presence_gated(stream_info.state)
async def async_stream() -> AsyncGenerator[bytes]:
redis_stream = TaskRunRedisStream(stream_key, use_dedicated_stream)
@@ -3243,15 +3249,22 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
# the open succeeded — keeps opened/closed balanced for the
# active-connections gauge regardless of which increment fails.
opened = False
+
try:
observe_stream_connection_opened(origin_product)
opened = True
delay = TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS
wait_started_at = asyncio.get_running_loop().time()
last_keepalive_at = wait_started_at
+ await redis_stream.refresh_watched()
+ waited_for_stream = False
while not await redis_stream.exists():
+ waited_for_stream = True
+ if presence_gated:
+ break
now = asyncio.get_running_loop().time()
+ await redis_stream.refresh_watched()
if now - wait_started_at >= TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS:
outcome = "unavailable"
yield format_sse_event({"error": "Stream not available"}, event_name="error")
@@ -3291,7 +3304,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
)
start_id = last_event_id or "0"
- if not last_event_id and start_latest:
+ if not last_event_id and start_latest and not waited_for_stream:
start_id = await redis_stream.get_latest_stream_id() or "0"
try:
async for stream_item in redis_stream.read_stream_entries(
@@ -3306,10 +3319,9 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):
else:
event_id, event = stream_item
yield format_sse_event(event, event_id=event_id)
- if (
- asyncio.get_running_loop().time() - connection_started_at
- >= TASK_RUN_STREAM_CONNECTION_MAX_SECONDS
- ):
+ now = asyncio.get_running_loop().time()
+ await redis_stream.refresh_watched()
+ if now - connection_started_at >= TASK_RUN_STREAM_CONNECTION_MAX_SECONDS:
outcome = "rotated"
# Without this marker a rotation EOF would be
# indistinguishable from run completion for API
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 086f564e0e84..f0fc438a7355 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
@@ -19,6 +19,7 @@ from temporalio.exceptions import ApplicationError
from posthog.temporal.common.utils import close_db_connections
+from products.tasks.backend.feature_flags import run_stream_presence_gated
from products.tasks.backend.logic.services.agent_command import sandbox_transport_token, validate_sandbox_url
from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
from products.tasks.backend.logic.services.permission_broker import (
@@ -144,7 +145,11 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_stre
).total_seconds()
stream_key = get_task_run_stream_key(input.run_id)
- redis_stream = TaskRunRedisStream(stream_key, run_uses_dedicated_stream(task_run.state))
+ redis_stream = TaskRunRedisStream(
+ stream_key,
+ run_uses_dedicated_stream(task_run.state),
+ presence_gated=run_stream_presence_gated(task_run.state),
+ )
await redis_stream.initialize()
actor_user = await sync_to_async(get_task_run_credential_user)(task_run.task, task_run.state)
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 169fdbc0bce0..a29c1201ae76 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,4 +1,3 @@
-import json
import time
import threading
import contextvars
@@ -17,6 +16,7 @@ from posthog.temporal.common.utils import close_db_connections
from posthog.temporal.oauth import PosthogMcpScopes
from products.tasks.backend.exceptions import CredentialUnavailableError
+from products.tasks.backend.feature_flags import run_stream_presence_gated
from products.tasks.backend.logic.services.agent_command import (
FOLLOWUP_TIMEOUT_SECONDS,
REFRESH_TIMEOUT_SECONDS,
@@ -30,10 +30,10 @@ from products.tasks.backend.logic.services.connection_token import create_sandbo
from products.tasks.backend.logic.services.peer_messages import mark_peer_message_outcome, peer_message_id_from_context
from products.tasks.backend.logic.services.run_actor import slack_actor_state_updates, user_has_current_team_access
from products.tasks.backend.logic.services.staged_artifacts import get_task_run_artifacts_by_id
-from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_key
+from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_event
from products.tasks.backend.metrics import observe_followup_denied_permission_stop, observe_followup_sandbox_stopped
from products.tasks.backend.models import AgentPeerMessage, TaskRun
-from products.tasks.backend.redis import get_tasks_stream_redis_sync, run_uses_dedicated_stream
+from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.oauth import create_oauth_access_token_for_run
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
apply_github_credentials_to_sandbox,
@@ -329,7 +329,12 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
run_state_actor_user_id=(task_run.state or {}).get("slack_actor_user_id"),
task_created_by_id=task_run.task.created_by_id,
)
- _write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))
+ _write_error_and_complete(
+ input.run_id,
+ error_msg,
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
+ )
raise RuntimeError(f"send_followup failed: {error_msg}")
if input.steer:
@@ -422,7 +427,12 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | 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, run_uses_dedicated_stream(task_run.state))
+ _write_error_and_complete(
+ input.run_id,
+ error_msg,
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
+ )
raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)
if input.message_id and actor_slack_user_id:
@@ -462,7 +472,12 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
reason=_steer_decline_reason(result.data),
)
return STEER_DECLINED_OUTCOME
- _write_turn_complete(input.run_id, _get_stop_reason(result.data), run_uses_dedicated_stream(task_run.state))
+ _write_turn_complete(
+ input.run_id,
+ _get_stop_reason(result.data),
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
+ )
logger.info("send_followup_delivered", run_id=input.run_id)
elif result.turn_in_flight:
# A read timeout means the message reached the sandbox and the turn is
@@ -487,7 +502,10 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
error=result.error,
)
_write_error_and_complete(
- input.run_id, DENIED_PERMISSION_STOP_MESSAGE, run_uses_dedicated_stream(task_run.state)
+ input.run_id,
+ DENIED_PERMISSION_STOP_MESSAGE,
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
)
raise ApplicationError(f"send_followup failed: {result.error}", non_retryable=True)
# Retry transport failures and known transient agent errors. message_id
@@ -511,7 +529,12 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
error=result.error,
status_code=result.status_code,
)
- _write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))
+ _write_error_and_complete(
+ input.run_id,
+ error_msg,
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
+ )
raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)
else:
logger.warning(
@@ -521,7 +544,12 @@ def _deliver_followup(input: SendFollowupToSandboxInput) -> str | None:
status_code=result.status_code,
)
error_msg = user_facing_agent_error(result.error)
- _write_error_and_complete(input.run_id, error_msg, run_uses_dedicated_stream(task_run.state))
+ _write_error_and_complete(
+ input.run_id,
+ error_msg,
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
+ )
# Propagate failure to the workflow.
raise ApplicationError(f"send_followup failed: {error_msg}", non_retryable=True)
@@ -644,7 +672,12 @@ def _deliver_peer_message(input: SendFollowupToSandboxInput, task_run: TaskRun,
_mark_peer_delivery_outcome(peer_message_id, AgentPeerMessage.Outcome.DELIVERED)
return None
_mark_peer_delivery_outcome(peer_message_id, AgentPeerMessage.Outcome.DELIVERED)
- _write_turn_complete(input.run_id, _get_stop_reason(result.data), run_uses_dedicated_stream(task_run.state))
+ _write_turn_complete(
+ input.run_id,
+ _get_stop_reason(result.data),
+ run_uses_dedicated_stream(task_run.state),
+ run_stream_presence_gated(task_run.state),
+ )
return None
if result.turn_in_flight:
# The read timeout means the message reached the sandbox and the turn is
@@ -1012,9 +1045,13 @@ 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, use_dedicated: bool = False) -> None:
+def _write_turn_complete(
+ run_id: str,
+ stop_reason: str = STOP_REASON_END_TURN,
+ use_dedicated: bool = False,
+ presence_gated: bool = False,
+) -> None:
"""Write a synthetic turn_complete event to the Redis stream."""
- stream_key = get_task_run_stream_key(run_id)
event = {
"type": "notification",
"notification": {
@@ -1022,15 +1059,13 @@ def _write_turn_complete(run_id: str, stop_reason: str = STOP_REASON_END_TURN, u
"params": {"source": "posthog", "stopReason": stop_reason},
},
}
- conn = get_tasks_stream_redis_sync(use_dedicated)
- conn.xadd(stream_key, {"data": json.dumps(event)}, maxlen=2000)
+ publish_task_run_stream_event(run_id, event, use_dedicated, presence_gated=presence_gated)
-def _write_error_and_complete(run_id: str, error_message: str, use_dedicated: bool = False) -> None:
+def _write_error_and_complete(
+ run_id: str, error_message: str, use_dedicated: bool = False, presence_gated: bool = False
+) -> None:
"""Write an error event followed by turn_complete to the Redis stream."""
- stream_key = get_task_run_stream_key(run_id)
- conn = get_tasks_stream_redis_sync(use_dedicated)
-
error_event = {
"type": "notification",
"notification": {
@@ -1038,5 +1073,5 @@ def _write_error_and_complete(run_id: str, error_message: str, use_dedicated: bo
"params": {"message": error_message},
},
}
- conn.xadd(stream_key, {"data": json.dumps(error_event)}, maxlen=2000)
- _write_turn_complete(run_id, use_dedicated=use_dedicated)
+ publish_task_run_stream_event(run_id, error_event, use_dedicated, presence_gated=presence_gated)
+ _write_turn_complete(run_id, use_dedicated=use_dedicated, presence_gated=presence_gated)
diff --git a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py
index ad680d814c04..c9e785057a53 100644
--- a/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py
+++ b/products/tasks/backend/temporal/process_task/activities/slack_agent_design_signals.py
@@ -350,12 +350,14 @@ async def _relay_from_redis(
local/no-proxy path, so the retry replay the resume guards against is not worth the plumbing here.
"""
redis_stream = TaskRunRedisStream(get_task_run_stream_key(input.run_id))
+ await redis_stream.refresh_watched()
try:
async for item in redis_stream.read_stream_entries(
start_id="0",
keepalive_interval_seconds=HEARTBEAT_INTERVAL_SECONDS,
):
activity.heartbeat()
+ await redis_stream.refresh_watched()
if item is None:
continue
_, event_data = item
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 a4539ae3b420..b7e4dd944996 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
@@ -285,7 +285,7 @@ class TestRelaySandboxEventsCancellation:
)
class StubTaskRunRedisStream:
- def __init__(self, stream_key: str, use_dedicated: bool = False) -> None:
+ def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:
self.stream_key = stream_key
async def initialize(self) -> None:
@@ -335,6 +335,73 @@ class TestRelaySandboxEventsCancellation:
redis_stream.mark_error.assert_not_awaited()
+class TestRelaySandboxEventsPresenceGating:
+ @pytest.mark.parametrize(
+ "run_state,expected_presence_gated",
+ [
+ pytest.param({"stream_presence_gated": True}, True, id="run_pinned_gated"),
+ pytest.param({"stream_presence_gated": False}, False, id="run_pinned_ungated"),
+ pytest.param({}, False, id="legacy_run_without_pin"),
+ ],
+ )
+ async def test_stream_presence_gating_follows_pinned_run_state(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ run_state: dict,
+ expected_presence_gated: bool,
+ ) -> None:
+ constructed: list[bool] = []
+
+ class StubTaskRunRedisStream:
+ def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:
+ constructed.append(presence_gated)
+
+ async def initialize(self) -> None:
+ return None
+
+ async def mark_complete(self) -> None:
+ return None
+
+ async def mark_error(self, error: str) -> None:
+ return None
+
+ class StubTaskRunQuerySet:
+ def select_related(self, *_args: str) -> "StubTaskRunQuerySet":
+ return self
+
+ async def aget(self, id: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ task=SimpleNamespace(created_by=SimpleNamespace(id=123), origin_product="slack"),
+ state=run_state,
+ )
+
+ async def fake_relay_loop(**_kwargs: object) -> bool:
+ return False
+
+ monkeypatch.setattr(relay_sandbox_events_module, "TaskRunRedisStream", StubTaskRunRedisStream)
+ monkeypatch.setattr(
+ relay_sandbox_events_module,
+ "TaskRunModel",
+ SimpleNamespace(objects=StubTaskRunQuerySet()),
+ )
+ monkeypatch.setattr(relay_sandbox_events_module, "create_sandbox_connection_token", lambda **_kwargs: "token")
+ monkeypatch.setattr(relay_sandbox_events_module, "validate_sandbox_url", lambda _url: None)
+ monkeypatch.setattr(relay_sandbox_events_module, "_relay_loop", fake_relay_loop)
+
+ await relay_sandbox_events(
+ RelaySandboxEventsInput(
+ run_id="run-id",
+ task_id="task-id",
+ sandbox_url="https://sandbox.example",
+ sandbox_connect_token=None,
+ team_id=1,
+ distinct_id="distinct-id",
+ )
+ )
+
+ assert constructed == [expected_presence_gated]
+
+
class TestRelaySandboxEventsMissingActor:
@pytest.mark.django_db
async def test_missing_slack_actor_fails_non_retryable_with_stream_error(
@@ -347,7 +414,7 @@ class TestRelaySandboxEventsMissingActor:
)
class StubTaskRunRedisStream:
- def __init__(self, stream_key: str, use_dedicated: bool = False) -> None:
+ def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:
self.stream_key = stream_key
async def initialize(self) -> None:
@@ -947,7 +1014,7 @@ class TestRelaySandboxEventsErrorHandling:
)
class StubTaskRunRedisStream:
- def __init__(self, stream_key: str, use_dedicated: bool = False) -> None:
+ def __init__(self, stream_key: str, use_dedicated: bool = False, *, presence_gated: bool = False) -> None:
self.stream_key = stream_key
async def initialize(self) -> None:
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 150ecad11850..564a661bfdb2 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
@@ -1,10 +1,16 @@
-import json
+from uuid import uuid4
from posthog.test.base import BaseTest
from unittest.mock import MagicMock, patch
from parameterized import parameterized
+from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_WATCHED_TIMEOUT,
+ get_task_run_stream_key,
+ get_task_run_stream_watched_key,
+)
+from products.tasks.backend.redis import get_tasks_stream_redis_sync
from products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox import (
STEER_DECLINE_REASON_UNREPORTED,
SendFollowupToSandboxInput,
@@ -47,28 +53,40 @@ class TestSteerDeclineReason(BaseTest):
class TestWriteTurnComplete(BaseTest):
@patch(
- "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_tasks_stream_redis_sync"
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.publish_task_run_stream_event"
)
- def test_writes_stop_reason_to_synthetic_event(self, mock_get_tasks_stream_redis_sync):
- mock_conn = MagicMock()
- mock_get_tasks_stream_redis_sync.return_value = mock_conn
-
+ def test_writes_stop_reason_to_synthetic_event(self, mock_publish):
_write_turn_complete("run-123", "max_tokens")
- payload = mock_conn.xadd.call_args.args[1]["data"]
- event = json.loads(payload)
+ event = mock_publish.call_args.args[1]
self.assertEqual(event["notification"]["method"], "_posthog/turn_complete")
self.assertEqual(event["notification"]["params"]["stopReason"], "max_tokens")
+ def test_presence_gated_write_skips_unwatched_stream_and_sets_ttl_when_watched(self):
+ run_id = f"test:{uuid4()}"
+ stream_key = get_task_run_stream_key(run_id)
+ watched_key = get_task_run_stream_watched_key(stream_key)
+ client = get_tasks_stream_redis_sync()
+ try:
+ _write_turn_complete(run_id, presence_gated=True)
+ self.assertFalse(client.exists(stream_key))
+
+ client.set(watched_key, "1", ex=TASK_RUN_STREAM_WATCHED_TIMEOUT)
+ _write_turn_complete(run_id, presence_gated=True)
+ self.assertEqual(client.xlen(stream_key), 1)
+ self.assertGreater(client.ttl(stream_key), 0)
+ finally:
+ client.delete(stream_key, watched_key)
+
class TestSendFollowupToSandbox(BaseTest):
@patch(
- "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_tasks_stream_redis_sync"
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.publish_task_run_stream_event"
)
@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_tasks_stream_redis_sync
+ self, mock_task_run_objects, mock_send_user_message, mock_publish
):
task_run = MagicMock()
task_run.task.created_by = None
@@ -78,13 +96,9 @@ class TestSendFollowupToSandbox(BaseTest):
data={"result": {"stopReason": "max_tokens"}},
)
- mock_conn = MagicMock()
- mock_get_tasks_stream_redis_sync.return_value = mock_conn
-
send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-123", message="hello"))
- payload = mock_conn.xadd.call_args.args[1]["data"]
- event = json.loads(payload)
+ event = mock_publish.call_args.args[1]
self.assertEqual(event["notification"]["params"]["stopReason"], "max_tokens")
# A bare mock would return a truthy value, which now reads as a rebind failure.
@@ -93,7 +107,7 @@ class TestSendFollowupToSandbox(BaseTest):
return_value=None,
)
@patch(
- "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.get_tasks_stream_redis_sync"
+ "products.tasks.backend.temporal.process_task.activities.send_followup_to_sandbox.publish_task_run_stream_event"
)
@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")
@@ -101,7 +115,7 @@ class TestSendFollowupToSandbox(BaseTest):
self,
mock_task_run_objects,
mock_send_user_message,
- mock_get_tasks_stream_redis_sync,
+ mock_publish,
mock_refresh_sandbox_mcp,
):
task_run = MagicMock()
@@ -144,4 +158,4 @@ class TestSendFollowupToSandbox(BaseTest):
message_id=None,
steer=True,
)
- mock_get_tasks_stream_redis_sync.assert_not_called()
+ mock_publish.assert_not_called()
diff --git a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
index 29856939ae3b..c0b89ca0fd0b 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_send_followup_to_sandbox.py
@@ -970,6 +970,7 @@ class TestSendFollowupTurnTimeout:
"run-1",
"The model response could not be completed. Please retry the task.",
False,
+ False,
)
_patches["turn_complete"].assert_not_called()
@@ -1044,7 +1045,7 @@ class TestSendFollowupTurnTimeout:
send_followup_to_sandbox(SendFollowupToSandboxInput(run_id="run-1", message="hi", message_id="m-1"))
assert exc_info.value.non_retryable is True
- _patches["error"].assert_called_once_with("run-1", DENIED_PERMISSION_STOP_MESSAGE, False)
+ _patches["error"].assert_called_once_with("run-1", DENIED_PERMISSION_STOP_MESSAGE, False, False)
def test_a_steer_never_claims_the_denial_that_ended_its_turn(self, _patches):
_patches["denial_state"].update(
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 8a13476bf0b5..4600bb27473e 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -72,6 +72,7 @@ from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamEntryOrKeepalive,
get_task_run_stream_key,
+ get_task_run_stream_watched_key,
)
from products.tasks.backend.models import (
TASK_OWNERSHIP_VERSION_STATE_KEY,
@@ -5395,6 +5396,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"use_modal_vm_sandbox": False,
"agent_otel_telemetry_enabled": False,
"sandbox_event_ingest_enabled": False,
+ "stream_presence_gated": True,
"snapshot_external_id": "im-real",
"snapshot_kind": "directory",
"snapshot_mount_path": "/tmp",
@@ -5449,6 +5451,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"use_modal_vm_sandbox": True,
"agent_otel_telemetry_enabled": True,
"sandbox_event_ingest_enabled": True,
+ "stream_presence_gated": False,
"snapshot_external_id": "im-attacker",
"snapshot_kind": "directory",
"snapshot_mount_path": "/tmp/workspace",
@@ -5507,6 +5510,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
assert run.state["use_modal_vm_sandbox"] is False
assert run.state["agent_otel_telemetry_enabled"] is False
assert run.state["sandbox_event_ingest_enabled"] is False
+ assert run.state["stream_presence_gated"] is True
assert run.state["snapshot_external_id"] == "im-real"
assert run.state["snapshot_kind"] == "directory"
assert run.state["snapshot_mount_path"] == "/tmp"
@@ -5544,6 +5548,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
"state_remove_keys": [
"github_credential_source",
"agent_otel_telemetry_enabled",
+ "stream_presence_gated",
"sandbox_id",
"use_modal_directory_resume_snapshots",
"use_modal_vm_sandbox",
@@ -5579,6 +5584,7 @@ class TestTaskRunAPI(BaseTaskAPITest):
run.refresh_from_db()
assert run.state["github_credential_source"] == "caller_token" # protected key survives removal
assert run.state["agent_otel_telemetry_enabled"] is False # protected key survives removal
+ assert run.state["stream_presence_gated"] is True # protected key survives removal
assert run.state["sandbox_id"] == "sb-real" # protected key survives removal
assert run.state["use_modal_directory_resume_snapshots"] is True # protected key survives removal
assert run.state["use_modal_vm_sandbox"] is False # protected key survives removal
@@ -9094,6 +9100,46 @@ class TestTaskRunStreamAPI(BaseTaskAPITest):
self.assertEqual(data_events[-1]["data"]["notification"]["params"]["message"], "late hello")
self.assertEqual(events[-1]["event"], "stream-end")
+ @override_settings(TASK_RUN_STREAM_PRESENCE_GATED_ORIGINS=["user_created"])
+ def test_stream_presence_gated_run_reads_missing_stream_instead_of_erroring(self):
+ task = self.create_task()
+ run = task.create_run()
+ self.assertIs(run.state["stream_presence_gated"], True)
+
+ captured: dict = {}
+
+ async def fake_read(
+ redis_stream: TaskRunRedisStream, start_id: str = "0", **kwargs
+ ) -> AsyncGenerator[TaskRunStreamEntryOrKeepalive]:
+ captured["start_id"] = start_id
+ yield (
+ "1-1",
+ {
+ "type": "notification",
+ "notification": {"jsonrpc": "2.0", "method": "_posthog/console", "params": {}},
+ },
+ )
+
+ with (
+ patch.object(TaskRunRedisStream, "read_stream_entries", fake_read),
+ patch.object(TaskRunRedisStream, "get_latest_stream_id", AsyncMock(return_value="5-5")) as mock_latest,
+ patch("products.tasks.backend.presentation.views.api.TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS", 0.2),
+ ):
+ response = self.client.get(self._stream_url(task, run) + "?start=latest")
+ events = self._collect_sse_events(response)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual([event for event in events if event["event"] == "error"], [])
+ self.assertEqual(captured["start_id"], "0")
+ mock_latest.assert_not_awaited()
+
+ async def _watched() -> bool:
+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(run.id)))
+ watched_key = get_task_run_stream_watched_key(get_task_run_stream_key(str(run.id)))
+ return bool(await redis_stream._redis_client.exists(watched_key))
+
+ self.assertTrue(asyncio.run(_watched()))
+
class TestTaskRunRedisStreamKeepalive(TestCase):
def test_read_stream_entries_yields_keepalive_sentinel_when_idle(self):
diff --git a/products/tasks/backend/tests/test_connection_token.py b/products/tasks/backend/tests/test_connection_token.py
index 2e811fca0430..adf54a1ec82f 100644
--- a/products/tasks/backend/tests/test_connection_token.py
+++ b/products/tasks/backend/tests/test_connection_token.py
@@ -11,11 +11,13 @@ import jwt
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
+from parameterized import parameterized
from products.tasks.backend.logic.services.connection_token import (
SANDBOX_CONNECTION_AUDIENCE,
SANDBOX_EVENT_INGEST_AUDIENCE,
SANDBOX_JWT_STATE_KID_KEY,
+ STREAM_READ_AUDIENCE,
_compute_kid,
_derive_public_key_pem,
create_sandbox_connection_token,
@@ -45,7 +47,7 @@ KEY_B = _generate_private_key_pem()
KID_A = _compute_kid(_derive_public_key_pem(KEY_A))
-def _fake_run(state: dict | None = None) -> TaskRun:
+def _fake_run(state: dict | None = None, origin_product: str = "user_created") -> TaskRun:
# Only the attributes the token helpers read are needed, so a lightweight stand-in
# avoids the DB; cast keeps the call sites type-correct.
return cast(
@@ -56,6 +58,7 @@ def _fake_run(state: dict | None = None) -> TaskRun:
team_id=1,
mode="background",
state={"sandbox_id": "sandbox-1", **(state or {})},
+ task=SimpleNamespace(origin_product=origin_product),
),
)
@@ -149,6 +152,47 @@ class TestSandboxJwtRotation(SimpleTestCase):
self.assertEqual(payload.run_id, str(run.id))
self.assertIsNone(payload.sandbox_id)
+ self.assertIs(payload.presence_gated, False)
+
+ @parameterized.expand([(True,), (False,)])
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)
+ def test_ingest_token_carries_pinned_presence_gating(self, gated: bool) -> None:
+ reset_sandbox_jwt_key_cache()
+ token = create_sandbox_event_ingest_token(_fake_run({"stream_presence_gated": gated}))
+
+ self.assertIs(validate_sandbox_event_ingest_token(token).presence_gated, gated)
+
+ @parameterized.expand([(True,), (False,)])
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)
+ def test_stream_read_token_carries_pinned_presence_gating(self, gated: bool) -> None:
+ reset_sandbox_jwt_key_cache()
+ token = create_stream_read_token(_fake_run({"stream_presence_gated": gated}))
+
+ self.assertIs(validate_stream_read_token(token).presence_gated, gated)
+
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=KEY_A, SANDBOX_JWT_PRIVATE_KEY_SECONDARY=None)
+ def test_legacy_stream_read_token_without_presence_claim_remains_valid(self) -> None:
+ reset_sandbox_jwt_key_cache()
+ run = _fake_run()
+ now = datetime.now(tz=UTC)
+ token = jwt.encode(
+ {
+ "run_id": str(run.id),
+ "task_id": str(run.task_id),
+ "team_id": run.team_id,
+ "iat": now,
+ "exp": now + timedelta(minutes=5),
+ "aud": STREAM_READ_AUDIENCE,
+ },
+ KEY_A,
+ algorithm="RS256",
+ headers={"kid": KID_A},
+ )
+
+ payload = validate_stream_read_token(token)
+
+ self.assertEqual(payload.run_id, str(run.id))
+ self.assertIs(payload.presence_gated, False)
def test_ingest_token_validates_after_primary_rotation(self) -> None:
# Ingest is rotation-safe: a token signed under the old primary keeps validating after the
@@ -217,7 +261,7 @@ _RUN_ID = "11111111-1111-1111-1111-111111111111"
_TASK_ID = "22222222-2222-2222-2222-222222222222"
-def _fake_task_run() -> TaskRun:
+def _fake_task_run(origin_product: str = "user_created") -> TaskRun:
return cast(
TaskRun,
SimpleNamespace(
@@ -225,6 +269,7 @@ def _fake_task_run() -> TaskRun:
task_id=_TASK_ID,
team_id=7,
state={"sandbox_id": "sandbox-1"},
+ task=SimpleNamespace(origin_product=origin_product),
),
)
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index cfd336f04ef8..172aa3abe761 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -501,6 +501,27 @@ class TestTaskRunEventIngest(TestCase):
self.assertEqual(body["last_accepted_seq"], 2)
self.assertEqual(self._read_notification_methods(), ["first", "second"])
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_presence_gated_ingest_accepts_events_without_mirroring_them(self) -> None:
+ self.task_run.state = {**(self.task_run.state or {}), "stream_presence_gated": True}
+ self.task_run.save(update_fields=["state", "updated_at"])
+ token = self._create_token()
+
+ with patch.object(TaskRun, "heartbeat_workflow"):
+ status, body = self._call_ingest(
+ token,
+ [
+ {"seq": 1, "event": {"type": "notification", "notification": {"method": "first"}}},
+ {"seq": 2, "event": {"type": "notification", "notification": {"method": "second"}}},
+ ],
+ )
+
+ self.assertEqual(status, 200)
+ self.assertEqual(body["accepted"], 2)
+ self.assertEqual(body["duplicate"], 0)
+ self.assertEqual(body["last_accepted_seq"], 2)
+ self.assertEqual(self._read_stream_events(), [])
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_duplicate_terminal_sequence_does_not_complete_without_completion_line(self) -> None:
token = self._create_token()
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 6175e181e9d4..359c100cd266 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -2305,6 +2305,8 @@ export const getTasksRunsStreamRetrieveUrl = (
*
* The server caps each connection at 900 seconds: it emits `event: end` with `data: {"type": "rotated"}` and closes. This does NOT mean the run finished — reconnect with the `Last-Event-ID` header set to the last received event id to resume without gaps or duplicates. Only treat the stream as complete when the run itself reaches a terminal status.
*
+ * Resume guarantees cover mirrored events only: on runs where live mirroring is presence-gated, events produced while no viewer was connected are not in the live stream. Reload the run's session logs to recover the agent's output; run-state and progress frames are not in those logs, so refetch the run itself for its current state.
+ *
* `?start=latest` consumers must also carry `Last-Event-ID` across reconnects: reconnecting without it re-resolves to the then-current latest event, silently skipping anything published while disconnected.
*
* **SDK consumers**: do not call the generated fetch wrapper for this path — it will buffer the entire stream. Use the URL builder (`getTasksRunsStreamRetrieveUrl`) with a streaming `fetch`/`EventSource`-style consumer and the `Last-Event-ID` header instead.
diff --git a/services/agent-proxy/docs/SECURITY.md b/services/agent-proxy/docs/SECURITY.md
index 182afa1fc5f4..f7d84afd72c6 100644
--- a/services/agent-proxy/docs/SECURITY.md
+++ b/services/agent-proxy/docs/SECURITY.md
@@ -33,6 +33,13 @@ cryptographic, not a matter of which token each party happens to hold.
Beyond audience, both handlers bind the token to the URL: the `run_id`, `task_id` and `team_id`
claims must match the path, else `403`. A token for run A cannot touch run B.
+Both tokens may also carry an optional `presence_gated` boolean. It is a mirroring hint, not
+a grant: on the ingest leg, when it is true and no reader is attached, ingested events advance
+the run's sequence but are not written into the Redis stream; on the read leg it tells the SSE
+handler that a missing stream is normal (no viewer marked presence yet), so it starts reading
+instead of reporting the stream unavailable. It must be a boolean if present; an absent claim
+means false, so tokens minted before the claim existed keep validating.
+
Credential delivery:
- The browser gets its read token from Django's `stream_token` endpoint, which is
diff --git a/services/agent-proxy/src/hono/app.ts b/services/agent-proxy/src/hono/app.ts
index 71c58149639d..2a34f137aa98 100644
--- a/services/agent-proxy/src/hono/app.ts
+++ b/services/agent-proxy/src/hono/app.ts
@@ -122,6 +122,7 @@ export function createApp(redis: Redis, config: Config, publicKeys: CryptoKey[])
originProduct: 'unknown',
lastEventId,
startLatest,
+ presenceGated: claims.presenceGated,
})
// Race each generator chunk against the client-disconnect abort signal.
diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.ts
index eafea3e316f8..9e3812a65808 100644
--- a/services/agent-proxy/src/hono/ingest-handler.ts
+++ b/services/agent-proxy/src/hono/ingest-handler.ts
@@ -42,7 +42,7 @@ import {
type EventIngestResult,
type SandboxEventIngestTokenPayload,
} from '../lib/types.js'
-import { observeIngestClientDisconnect, observeStreamIngestEvents } from './metrics.js'
+import { observeIngestClientDisconnect, observeStreamIngestEvents, observeStreamWriteSkipped } from './metrics.js'
// Diagnostic (temporary): records when request-body chunks arrive at the Node
// process, to tell a live upload (chunks spread across the request lifetime)
@@ -105,7 +105,7 @@ export async function handleIngest(
// NDJSON body parsing + Redis writes.
const streamKey = getStreamKey(claims.runId)
- const redisStream = new TaskRunRedisStream(streamKey, redis)
+ const redisStream = new TaskRunRedisStream(streamKey, redis, { presenceGated: claims.presenceGated })
const bodyTiming: IngestBodyTiming = {
startedAt: Date.now(),
@@ -244,15 +244,19 @@ async function ingestEventLines(
}
const { seq, event } = eventLine
- const streamId = await redisStream.writeEventWithSequence(event, seq)
+ const write = await redisStream.writeEventWithSequence(event, seq)
- if (streamId === null) {
+ if (!write.accepted) {
// Duplicate: advance last_accepted_seq to whatever Redis has.
result.duplicate++
result.last_accepted_seq = Math.max(result.last_accepted_seq, await redisStream.getLastSequence())
continue
}
+ if (write.streamId === null) {
+ observeStreamWriteSkipped('ingest')
+ }
+
result.accepted++
result.last_accepted_seq = seq
diff --git a/services/agent-proxy/src/hono/metrics.ts b/services/agent-proxy/src/hono/metrics.ts
index d744d93a8fe3..fd8ea7150e1f 100644
--- a/services/agent-proxy/src/hono/metrics.ts
+++ b/services/agent-proxy/src/hono/metrics.ts
@@ -10,7 +10,7 @@
import { Counter, Gauge, Histogram, Registry, collectDefaultMetrics } from 'prom-client'
-import type { DisconnectClassification, StreamConnectionOutcome } from '../lib/types.js'
+import type { DisconnectClassification, StreamConnectionOutcome, StreamWriteSkippedPath } from '../lib/types.js'
export const register = new Registry()
@@ -83,6 +83,13 @@ export const streamIngestEventsTotal = new Counter({
registers: [register],
})
+export const taskRunStreamWriteSkippedTotal = new Counter({
+ name: 'posthog_tasks_task_run_stream_write_skipped_total',
+ help: 'Task-run events not mirrored into Redis because presence gating found no attached reader',
+ labelNames: ['path'],
+ registers: [register],
+})
+
// 'run_over'/'idle' are expected sandbox teardown; 'mid_turn' is a genuine cut worth alerting on.
export const ingestClientDisconnectsTotal = new Counter({
name: 'agent_proxy_ingest_client_disconnects_total',
@@ -189,6 +196,10 @@ export function observeStreamIngestEvents(opts: { accepted: number; duplicate: n
}
}
+export function observeStreamWriteSkipped(path: StreamWriteSkippedPath): void {
+ taskRunStreamWriteSkippedTotal.labels({ path }).inc()
+}
+
export function observeIngestClientDisconnect(classification: DisconnectClassification): void {
ingestClientDisconnectsTotal.labels({ classification }).inc()
}
diff --git a/services/agent-proxy/src/hono/sse-handler.ts b/services/agent-proxy/src/hono/sse-handler.ts
index d7f80c0350b0..727ce0b4987c 100644
--- a/services/agent-proxy/src/hono/sse-handler.ts
+++ b/services/agent-proxy/src/hono/sse-handler.ts
@@ -15,22 +15,27 @@
// Normal stream event — no eventName, id = Redis stream ID
// Keepalive — eventName='keepalive', data={"type":"keepalive"}
// Terminal — eventName='stream-end', data={"status":"complete"}
+// Rotation — eventName='end', data={"type":"rotated"}
// Stream error — eventName='error', data={"error":"<msg>"}
// Stream unavailable — eventName='error', data={"error":"Stream not available"}
import type { Redis } from 'ioredis'
import {
+ CONNECTION_MAX_MS,
KEEPALIVE_INTERVAL_MS,
+ SSE_EVENT_END,
SSE_EVENT_ERROR,
SSE_EVENT_KEEPALIVE,
SSE_EVENT_STREAM_END,
SSE_PAYLOAD_KEEPALIVE,
+ SSE_PAYLOAD_ROTATED,
SSE_PAYLOAD_STREAM_END,
WAIT_DELAY_INCREMENT_MS,
WAIT_INITIAL_DELAY_MS,
WAIT_MAX_DELAY_MS,
WAIT_TIMEOUT_MS,
+ WATCHED_REFRESH_INTERVAL_MS,
makeSseErrorPayload,
} from '../lib/constants.js'
import { logger } from '../lib/logging.js'
@@ -101,11 +106,13 @@ export async function* streamTaskRunEvents(
originProduct?: string
lastEventId?: string | null
startLatest?: boolean
+ presenceGated?: boolean
}
): AsyncGenerator<Buffer, void, unknown> {
const originProduct = opts.originProduct ?? 'unknown'
const lastEventId = opts.lastEventId ?? null
const startLatest = opts.startLatest ?? false
+ const presenceGated = opts.presenceGated ?? false
const redisStream = new TaskRunRedisStream(streamKey, redis)
const connectionStartedAt = Date.now()
@@ -117,23 +124,46 @@ export async function* streamTaskRunEvents(
// generator exits (completion, error, or client disconnect).
let dedupRedis: Redis | undefined
+ let lastWatchedRefreshAt: number | null = null
+ const refreshWatched = async (now: number): Promise<void> => {
+ if (lastWatchedRefreshAt !== null && now - lastWatchedRefreshAt < WATCHED_REFRESH_INTERVAL_MS) {
+ return
+ }
+ try {
+ await redisStream.markWatched()
+ lastWatchedRefreshAt = now
+ } catch (err) {
+ logger.warn('stream:mark_watched_failed', {
+ streamKey,
+ error: err instanceof Error ? err.message : String(err),
+ })
+ }
+ }
+
try {
observeStreamConnectionOpened(originProduct)
opened = true
+ await refreshWatched(Date.now())
+
// -- Wait-for-stream loop --
let delay = WAIT_INITIAL_DELAY_MS
const waitStartedAt = Date.now()
let lastKeepaliveAt = waitStartedAt
let waitedForStream = false
while (!(await redisStream.exists())) {
- const now = Date.now()
-
if (!waitedForStream) {
waitedForStream = true
logger.debug('stream:waiting', { streamKey })
}
+ if (presenceGated) {
+ break
+ }
+
+ const now = Date.now()
+ await refreshWatched(now)
+
if (now - waitStartedAt >= WAIT_TIMEOUT_MS) {
outcome = 'unavailable'
logger.warn('stream:unavailable', { streamKey, waitedMs: now - waitStartedAt })
@@ -215,14 +245,21 @@ export async function* streamTaskRunEvents(
keepaliveIntervalMs: KEEPALIVE_INTERVAL_MS,
blockingRedis: dedupRedis,
})) {
+ await refreshWatched(Date.now())
+
if (streamItem === null) {
// Idle keepalive signal from readStreamEntries
yield formatSseEvent(SSE_PAYLOAD_KEEPALIVE, { eventName: SSE_EVENT_KEEPALIVE })
- continue
+ } else {
+ const [eventId, event] = streamItem
+ yield formatSseEvent(event, { eventId })
}
- const [eventId, event] = streamItem
- yield formatSseEvent(event, { eventId })
+ if (Date.now() - connectionStartedAt >= CONNECTION_MAX_MS) {
+ outcome = 'rotated'
+ yield formatSseEvent(SSE_PAYLOAD_ROTATED, { eventName: SSE_EVENT_END })
+ return
+ }
}
// Generator returned normally — completion sentinel was consumed.
diff --git a/services/agent-proxy/src/lib/constants.ts b/services/agent-proxy/src/lib/constants.ts
index abb1f13577e2..276b942dafb6 100644
--- a/services/agent-proxy/src/lib/constants.ts
+++ b/services/agent-proxy/src/lib/constants.ts
@@ -17,6 +17,10 @@ export const SEQUENCE_TTL_SECONDS = STREAM_TTL_SECONDS + 3600 // 25200
// (mirrors TASK_RUN_STREAM_COMPLETED_TIMEOUT in redis_stream.py).
export const STREAM_COMPLETED_TTL_SECONDS = Math.min(30 * 60, Math.floor(STREAM_TTL_SECONDS / 3)) // 1800
+export const STREAM_WATCHED_TTL_SECONDS = 5 * 60
+
+export const WATCHED_REFRESH_INTERVAL_MS = 120_000
+
// Redis XADD MAXLEN ~ (approximate trim, not exact).
export const STREAM_MAX_LENGTH = 5_000
@@ -33,6 +37,10 @@ export const WAIT_TIMEOUT_MS = 300_000
// Idle threshold before emitting a keepalive SSE event
export const KEEPALIVE_INTERVAL_MS = 20_000
+// Per-connection cap before a graceful rotation
+// (mirrors TASK_RUN_STREAM_CONNECTION_MAX_SECONDS in api.py)
+export const CONNECTION_MAX_MS = 15 * 60 * 1000
+
// Redis SET NX EX throttle window for the Temporal heartbeat callback (seconds)
export const HEARTBEAT_THROTTLE_SECONDS = 30
@@ -93,11 +101,13 @@ export const SANDBOX_EVENT_INGEST_AUDIENCE = 'posthog:sandbox_event_ingest'
// normal stream events do not — they carry only "id:" and "data:").
export const SSE_EVENT_KEEPALIVE = 'keepalive'
export const SSE_EVENT_STREAM_END = 'stream-end'
+export const SSE_EVENT_END = 'end'
export const SSE_EVENT_ERROR = 'error'
// SSE payload shapes (byte-identical to Python format_sse_event call sites)
export const SSE_PAYLOAD_KEEPALIVE: Record<string, string> = { type: 'keepalive' }
export const SSE_PAYLOAD_STREAM_END: Record<string, string> = { status: 'complete' }
+export const SSE_PAYLOAD_ROTATED: Record<string, string> = { type: 'rotated' }
export function makeSseErrorPayload(error: string): Record<string, string> {
return { error }
diff --git a/services/agent-proxy/src/lib/jwt.ts b/services/agent-proxy/src/lib/jwt.ts
index 499dce1c1534..add6d2584289 100644
--- a/services/agent-proxy/src/lib/jwt.ts
+++ b/services/agent-proxy/src/lib/jwt.ts
@@ -60,6 +60,14 @@ function assertStreamClaims(payload: Record<string, unknown>): { runId: string;
return { runId, taskId, teamId: teamId as number }
}
+function assertPresenceGatedClaim(payload: Record<string, unknown>): boolean {
+ const presenceGated = payload['presence_gated']
+ if (presenceGated !== undefined && typeof presenceGated !== 'boolean') {
+ throw new Error('Token has invalid claim: presence_gated must be a boolean')
+ }
+ return presenceGated ?? false
+}
+
// Verify a token against every configured public key, returning the payload from the first key
// whose signature validates. Only a signature mismatch advances to the next key; expiry, wrong
// audience and malformed claims are key-independent and fail fast. This is what makes a
@@ -87,6 +95,7 @@ async function verifyWithKeys(token: string, publicKeys: CryptoKey[], audience:
// Audience: posthog:stream_read
// Required claims: run_id (string), task_id (string), team_id (integer)
+// Optional claim: presence_gated (boolean, absent means false)
// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)
//
// Throws jose error subtypes (JWTExpired, JWTInvalid, JWSSignatureVerificationFailed,
@@ -94,7 +103,8 @@ async function verifyWithKeys(token: string, publicKeys: CryptoKey[], audience:
// a plain Error on malformed claim types. The server maps all of these to 401.
export async function validateStreamReadToken(token: string, publicKeys: CryptoKey[]): Promise<StreamReadTokenPayload> {
const payload = await verifyWithKeys(token, publicKeys, STREAM_READ_AUDIENCE)
- return assertStreamClaims(payload as Record<string, unknown>)
+ const claims = payload as Record<string, unknown>
+ return { ...assertStreamClaims(claims), presenceGated: assertPresenceGatedClaim(claims) }
}
// ---------------------------------------------------------------------------
@@ -103,6 +113,7 @@ export async function validateStreamReadToken(token: string, publicKeys: CryptoK
// Audience: posthog:sandbox_event_ingest
// Required claims: run_id (string), task_id (string), team_id (integer)
+// Optional claim: presence_gated (boolean, absent means false)
// Algorithm: RS256, no clockTolerance (matches Python leeway=0 default)
//
// Same error semantics as validateStreamReadToken.
@@ -111,5 +122,6 @@ export async function validateSandboxEventIngestToken(
publicKeys: CryptoKey[]
): Promise<SandboxEventIngestTokenPayload> {
const payload = await verifyWithKeys(token, publicKeys, SANDBOX_EVENT_INGEST_AUDIENCE)
- return assertStreamClaims(payload as Record<string, unknown>)
+ const claims = payload as Record<string, unknown>
+ return { ...assertStreamClaims(claims), presenceGated: assertPresenceGatedClaim(claims) }
}
diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.ts
index 04b9cb13e171..aada93ac399d 100644
--- a/services/agent-proxy/src/lib/redis-stream.ts
+++ b/services/agent-proxy/src/lib/redis-stream.ts
@@ -16,17 +16,20 @@ import {
STREAM_MAX_LENGTH,
STREAM_PREFIX,
STREAM_TTL_SECONDS,
+ STREAM_WATCHED_TTL_SECONDS,
WAIT_DELAY_INCREMENT_MS,
WAIT_INITIAL_DELAY_MS,
WAIT_MAX_DELAY_MS,
WAIT_TIMEOUT_MS,
} from './constants.js'
-import type { ReadStreamEntriesOptions, ResumeGap, StreamEntryOrKeepalive } from './types.js'
+import type { ReadStreamEntriesOptions, ResumeGap, StreamEntryOrKeepalive, TaskRunStreamWriteResult } from './types.js'
import {
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
TaskRunStreamError,
TaskRunStreamSequenceGap,
+ WRITE_RESULT_DUPLICATE,
+ WRITE_RESULT_SKIPPED,
} from './types.js'
// ---------------------------------------------------------------------------
@@ -61,6 +64,10 @@ export function getFirstActivityKey(streamKey: string): string {
return `${streamKey}:ingest-first-agent-activity`
}
+export function getWatchedKey(streamKey: string): string {
+ return `${streamKey}:watched`
+}
+
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
@@ -129,6 +136,7 @@ export class TaskRunRedisStream {
private readonly sequenceTimeout: number
private readonly completedTimeout: number
private readonly maxLength: number
+ private readonly presenceGated: boolean
constructor(
streamKey: string,
@@ -136,6 +144,7 @@ export class TaskRunRedisStream {
opts?: {
timeout?: number
maxLength?: number
+ presenceGated?: boolean
}
) {
this.streamKey = streamKey
@@ -145,6 +154,7 @@ export class TaskRunRedisStream {
this.sequenceTimeout = Math.max(this.timeout, SEQUENCE_TTL_SECONDS)
this.completedTimeout = Math.min(this.timeout, STREAM_COMPLETED_TTL_SECONDS)
this.maxLength = opts?.maxLength ?? STREAM_MAX_LENGTH
+ this.presenceGated = opts?.presenceGated ?? false
}
// SET EXPIRE on the stream key; does not create it.
@@ -364,6 +374,10 @@ export class TaskRunRedisStream {
return normalizeRedisInt(raw)
}
+ async markWatched(): Promise<void> {
+ await this.redis.set(getWatchedKey(this.streamKey), '1', 'EX', STREAM_WATCHED_TTL_SECONDS)
+ }
+
// SET agent-active-key ('1'|'0') EX STREAM_TTL_SECONDS
async setAgentActive(active: boolean): Promise<void> {
await this.redis.set(getAgentActiveKey(this.streamKey), active ? '1' : '0', 'EX', this.timeout)
@@ -405,21 +419,25 @@ export class TaskRunRedisStream {
}
// WATCH/MULTI optimistic retry loop (never the TEST shortcut).
- // Returns stream ID string on accept, null on duplicate.
// Throws TaskRunStreamSequenceGap, TaskRunStreamAlreadyCompleted.
//
// Sequences start at 1; sequence 0 is the initial sentinel treated as accepted.
// seq == last+1 -> accept (XADD, set last-seq, refresh TTLs, return stream ID)
- // seq <= last -> duplicate (return null)
+ // seq <= last -> duplicate (accepted false, no stream ID)
// seq > last+1 -> TaskRunStreamSequenceGap
// completed key present -> TaskRunStreamAlreadyCompleted
- async writeEventWithSequence(event: Record<string, unknown>, sequence: number): Promise<string | null> {
+ // presence-gated with no attached reader -> accepted, no stream ID
+ async writeEventWithSequence(event: Record<string, unknown>, sequence: number): Promise<TaskRunStreamWriteResult> {
const sequenceKey = getSequenceKey(this.streamKey)
const completedKey = getCompletedKey(this.streamKey)
- const raw = JSON.stringify(event)
+ const watchedKey = getWatchedKey(this.streamKey)
for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
- await this.redis.watch(sequenceKey, completedKey)
+ if (this.presenceGated) {
+ await this.redis.watch(sequenceKey, completedKey, watchedKey)
+ } else {
+ await this.redis.watch(sequenceKey, completedKey)
+ }
const lastSeqRaw = await this.redis.get(sequenceKey)
const lastSequence = normalizeRedisInt(lastSeqRaw)
@@ -432,7 +450,7 @@ export class TaskRunRedisStream {
if (sequence <= lastSequence) {
await this.redis.unwatch()
- return null
+ return WRITE_RESULT_DUPLICATE
}
if (sequence !== lastSequence + 1) {
@@ -440,9 +458,13 @@ export class TaskRunRedisStream {
throw new TaskRunStreamSequenceGap(lastSequence + 1, sequence, lastSequence)
}
+ const mirror = !this.presenceGated || (await this.redis.exists(watchedKey)) > 0
+
const pipeline = this.redis.multi()
- pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
- pipeline.expire(this.streamKey, this.timeout)
+ if (mirror) {
+ pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', JSON.stringify(event))
+ pipeline.expire(this.streamKey, this.timeout)
+ }
pipeline.set(sequenceKey, String(sequence), 'EX', this.sequenceTimeout)
const results = await pipeline.exec()
@@ -451,12 +473,16 @@ export class TaskRunRedisStream {
continue
}
+ if (!mirror) {
+ return WRITE_RESULT_SKIPPED
+ }
+
// results[0] is [error, streamId]
const [xaddErr, streamId] = results[0] ?? [null, null]
if (xaddErr) {
throw new TaskRunStreamError(`XADD failed: ${String(xaddErr)}`)
}
- return normalizeStreamId(streamId)
+ return { accepted: true, streamId: normalizeStreamId(streamId) }
}
throw new TaskRunStreamError('writeEventWithSequence: too many WATCH conflicts')
@@ -559,6 +585,7 @@ export class TaskRunRedisStream {
const heartbeatKey = getHeartbeatKey(this.streamKey)
const firstCommandKey = getFirstCommandKey(this.streamKey)
const firstActivityKey = getFirstActivityKey(this.streamKey)
+ const watchedKey = getWatchedKey(this.streamKey)
const deleted = await this.redis.del(
this.streamKey,
sequenceKey,
@@ -566,7 +593,8 @@ export class TaskRunRedisStream {
agentActiveKey,
heartbeatKey,
firstCommandKey,
- firstActivityKey
+ firstActivityKey,
+ watchedKey
)
return deleted > 0
} catch {
diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.ts
index 3824789af373..15aedd4f7c11 100644
--- a/services/agent-proxy/src/lib/types.ts
+++ b/services/agent-proxy/src/lib/types.ts
@@ -77,6 +77,14 @@ export class ClientDisconnected extends Error {
// Redis stream types
// ---------------------------------------------------------------------------
+export interface TaskRunStreamWriteResult {
+ readonly accepted: boolean
+ readonly streamId: string | null
+}
+
+export const WRITE_RESULT_DUPLICATE: TaskRunStreamWriteResult = { accepted: false, streamId: null }
+export const WRITE_RESULT_SKIPPED: TaskRunStreamWriteResult = { accepted: true, streamId: null }
+
// Returned by detectResumeGap when the client's Last-Event-ID has been trimmed.
// S3 hydration is out of scope; callers log and continue from oldestAvailableId.
export interface ResumeGap {
@@ -93,6 +101,7 @@ export interface StreamReadTokenPayload {
runId: string
taskId: string
teamId: number
+ presenceGated: boolean
}
// Claims extracted from a posthog:sandbox_event_ingest JWT (POST /v1/runs/:run/ingest leg)
@@ -100,16 +109,19 @@ export interface SandboxEventIngestTokenPayload {
runId: string
taskId: string
teamId: number
+ presenceGated: boolean
}
// ---------------------------------------------------------------------------
// SSE stream connection outcome (matches Python StreamConnectionOutcome values)
// ---------------------------------------------------------------------------
-export type StreamConnectionOutcome = 'completed' | 'stream_error' | 'unavailable' | 'client_disconnect'
+export type StreamConnectionOutcome = 'completed' | 'stream_error' | 'unavailable' | 'client_disconnect' | 'rotated'
export type DisconnectClassification = 'run_over' | 'idle' | 'mid_turn'
+export type StreamWriteSkippedPath = 'ingest'
+
// ---------------------------------------------------------------------------
// Ingest HTTP response shape (200 OK body)
// ---------------------------------------------------------------------------
diff --git a/services/agent-proxy/tests/hono/app.test.ts b/services/agent-proxy/tests/hono/app.test.ts
index da213b83795a..4bbae82f74d4 100644
--- a/services/agent-proxy/tests/hono/app.test.ts
+++ b/services/agent-proxy/tests/hono/app.test.ts
@@ -35,7 +35,7 @@ function makeConfig(): Config {
describe('app onError', () => {
beforeEach(() => {
vi.clearAllMocks()
- mockValidate.mockResolvedValue({ runId: 'run-123', taskId: 'task-abc', teamId: 42 })
+ mockValidate.mockResolvedValue({ runId: 'run-123', taskId: 'task-abc', teamId: 42, presenceGated: false })
})
it('logs unexpected route errors with request context and returns JSON 500', async () => {
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index 470b2c2b5320..1b6c574e9588 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -26,7 +26,7 @@ import {
HEARTBEAT_THROTTLE_SECONDS,
} from '@/lib/constants.js'
import { logger } from '@/lib/logging.js'
-import { TaskRunRedisStream, getCompletedKey, getStreamKey } from '@/lib/redis-stream.js'
+import { TaskRunRedisStream, getCompletedKey, getStreamKey, getWatchedKey } from '@/lib/redis-stream.js'
import { heartbeatWorkflowIfNeeded } from '@/lib/side-effects.js'
import type { SandboxEventIngestTokenPayload } from '@/lib/types.js'
@@ -303,6 +303,7 @@ function makeClaims(overrides?: Partial<SandboxEventIngestTokenPayload>): Sandbo
runId: 'run-123',
taskId: 'task-abc',
teamId: 42,
+ presenceGated: false,
...overrides,
}
}
@@ -462,6 +463,48 @@ describe('ingest-handler', () => {
expect(body).toMatchObject({ accepted: 1, duplicate: 0, last_accepted_seq: 1 })
})
+ // -----------------------------------------------------------------------
+ // Presence gating
+ // -----------------------------------------------------------------------
+
+ it.each([
+ { name: 'skips the mirror when no reader is attached', watched: false, expectedEntries: 0 },
+ { name: 'mirrors when a reader is attached', watched: true, expectedEntries: 1 },
+ ])('presence-gated ingest $name', async ({ watched, expectedEntries }) => {
+ mockValidate.mockResolvedValue(makeClaims({ presenceGated: true }))
+ if (watched) {
+ await fakeRedis.set(getWatchedKey(getStreamKey(RUN_ID)), '1', 'EX', 300)
+ }
+ const config = makeConfig()
+ const ndjson = JSON.stringify({ seq: 1, event: { type: 'message' } }) + '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+
+ expect(res.status).toBe(200)
+ expect(await decodeJson(res)).toMatchObject({ accepted: 1, duplicate: 0, last_accepted_seq: 1 })
+ expect(await redisStream.getLastSequence()).toBe(1)
+ expect(await fakeRedis.xrange(getStreamKey(RUN_ID))).toHaveLength(expectedEntries)
+ })
+
+ it('still writes the completion sentinel for a presence-gated run with no reader', async () => {
+ mockValidate.mockResolvedValue(makeClaims({ presenceGated: true }))
+ const config = makeConfig()
+ const ndjson =
+ JSON.stringify({ seq: 1, event: { type: 'message' } }) +
+ '\n' +
+ JSON.stringify({ type: '_posthog/stream_complete', final_seq: 1 }) +
+ '\n'
+ const ctx = makeContext({ body: makeStringBody(ndjson) })
+
+ const res = await handleIngest(ctx, fakeRedis as unknown as Redis, config, [] as CryptoKey[])
+
+ expect(res.status).toBe(200)
+ const entries = await fakeRedis.xrange(getStreamKey(RUN_ID))
+ expect(entries).toHaveLength(1)
+ expect(JSON.parse(entries[0]![1]['data']!)).toEqual({ type: 'STREAM_STATUS', status: 'complete' })
+ })
+
it('writes complete NDJSON lines before the request body closes', async () => {
const config = makeConfig()
const encoder = new TextEncoder()
diff --git a/services/agent-proxy/tests/hono/sse-handler.test.ts b/services/agent-proxy/tests/hono/sse-handler.test.ts
index 9fb6367b0687..ce1c7b432a5f 100644
--- a/services/agent-proxy/tests/hono/sse-handler.test.ts
+++ b/services/agent-proxy/tests/hono/sse-handler.test.ts
@@ -13,12 +13,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { formatSseEvent, streamTaskRunEvents } from '@/hono/sse-handler.js'
import {
+ CONNECTION_MAX_MS,
KEEPALIVE_INTERVAL_MS,
+ SSE_EVENT_END,
SSE_EVENT_ERROR,
SSE_EVENT_KEEPALIVE,
SSE_EVENT_STREAM_END,
WAIT_TIMEOUT_MS,
} from '@/lib/constants.js'
+import { getWatchedKey } from '@/lib/redis-stream.js'
// ---------------------------------------------------------------------------
// Minimal in-memory fake Redis
@@ -489,6 +492,92 @@ describe('sse-handler', () => {
// streamTaskRunEvents — terminal stream-end event framing
// -------------------------------------------------------------------------
+ describe('streamTaskRunEvents — reader presence', () => {
+ it('marks the stream watched as soon as the connection is accepted', async () => {
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'hello' })
+ xaddComplete(redis, streamKey)
+
+ await collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+
+ expect(await redis.get(getWatchedKey(streamKey))).toBe('1')
+ })
+
+ it('marks the stream watched before it exists so a gated writer starts mirroring', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ const bodyPromise = collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+ await vi.advanceTimersByTimeAsync(1)
+
+ expect(await redis.get(getWatchedKey(streamKey))).toBe('1')
+
+ xaddComplete(redis, streamKey)
+ await vi.advanceTimersByTimeAsync(2_000)
+ await bodyPromise
+ })
+
+ it('retries a failed watched-key write on the next refresh instead of waiting out the interval', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+ vi.spyOn(redis, 'set').mockRejectedValueOnce(new Error('redis unavailable'))
+
+ const bodyPromise = collect(streamTaskRunEvents(streamKey, redis as unknown as Redis, {}))
+ await vi.advanceTimersByTimeAsync(1_000)
+
+ expect(await redis.get(getWatchedKey(streamKey))).toBe('1')
+
+ xaddComplete(redis, streamKey)
+ await vi.advanceTimersByTimeAsync(2_000)
+ await bodyPromise
+ })
+
+ it('presence-gated connect reads a missing stream from the start instead of erroring', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ const bodyPromise = collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, {
+ presenceGated: true,
+ startLatest: true,
+ })
+ )
+ await vi.advanceTimersByTimeAsync(1_000)
+
+ xaddData(redis, streamKey, { type: 'notification', msg: 'first gated event' })
+ xaddComplete(redis, streamKey)
+ await vi.advanceTimersByTimeAsync(5_000)
+
+ const body = await bodyPromise
+ expect(body).toContain('"first gated event"')
+ expect(body).not.toContain('Stream not available')
+ })
+
+ it('rotates a presence-gated connection on a missing stream instead of holding it open', async () => {
+ vi.useFakeTimers()
+
+ const runId = uniqueRunId()
+ const streamKey = makeStreamKey(runId)
+
+ const bodyPromise = collect(
+ streamTaskRunEvents(streamKey, redis as unknown as Redis, { presenceGated: true })
+ )
+ await vi.advanceTimersByTimeAsync(CONNECTION_MAX_MS + KEEPALIVE_INTERVAL_MS + 1_000)
+
+ const body = await bodyPromise
+ expect(body).toContain(`event: ${SSE_EVENT_END}\ndata: {"type":"rotated"}`)
+ expect(body).not.toContain('Stream not available')
+ })
+ })
+
describe('streamTaskRunEvents — terminal stream-end event', () => {
it('terminal event is named stream-end and carries {status:complete}', async () => {
const runId = uniqueRunId()
@@ -644,8 +733,7 @@ describe('sse-handler', () => {
streamTaskRunEvents(streamKey, redis as unknown as Redis, { startLatest: true })
)
- await Promise.resolve()
- await Promise.resolve()
+ await vi.advanceTimersByTimeAsync(1)
xaddData(redis, streamKey, { type: 'notification', msg: 'first-after-wait' })
xaddComplete(redis, streamKey)
await vi.advanceTimersByTimeAsync(100)
diff --git a/services/agent-proxy/tests/lib/jwt.test.ts b/services/agent-proxy/tests/lib/jwt.test.ts
index 53c60002565e..458552610e9f 100644
--- a/services/agent-proxy/tests/lib/jwt.test.ts
+++ b/services/agent-proxy/tests/lib/jwt.test.ts
@@ -57,6 +57,7 @@ interface TokenOptions {
expiresIn?: string
omitExp?: boolean
signingKey?: CryptoKey
+ presenceGated?: unknown
}
async function signToken(opts: TokenOptions = {}): Promise<string> {
@@ -68,9 +69,15 @@ async function signToken(opts: TokenOptions = {}): Promise<string> {
expiresIn = '1h',
omitExp = false,
signingKey,
+ presenceGated,
} = opts
- const builder = new SignJWT({ run_id: runId, task_id: taskId, team_id: teamId }).setProtectedHeader({
+ const claims: Record<string, unknown> = { run_id: runId, task_id: taskId, team_id: teamId }
+ if (presenceGated !== undefined) {
+ claims['presence_gated'] = presenceGated
+ }
+
+ const builder = new SignJWT(claims).setProtectedHeader({
alg: 'RS256',
})
@@ -97,8 +104,30 @@ describe('jwt', () => {
expect(payload.runId).toBe('run-abc-123')
expect(payload.taskId).toBe('task-abc-123')
expect(payload.teamId).toBe(42)
+ expect(payload.presenceGated).toBe(false)
})
+ it.each([
+ { name: 'true', claim: true, expected: true },
+ { name: 'false', claim: false, expected: false },
+ ])('carries a presence_gated claim of $name', async ({ claim, expected }) => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, presenceGated: claim })
+ const payload = await validateStreamReadToken(token, keys.publicKeys)
+
+ expect(payload.presenceGated).toBe(expected)
+ })
+
+ it.each([{ claim: 'yes' }, { claim: 1 }, { claim: null }])(
+ 'rejects a non-boolean presence_gated claim ($claim)',
+ async ({ claim }) => {
+ const token = await signToken({ audience: STREAM_READ_AUDIENCE, presenceGated: claim })
+
+ await expect(validateStreamReadToken(token, keys.publicKeys)).rejects.toThrow(
+ 'presence_gated must be a boolean'
+ )
+ }
+ )
+
it('rejects a token with the wrong audience (sandbox_event_ingest)', async () => {
const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE })
@@ -174,8 +203,30 @@ describe('jwt', () => {
expect(payload.runId).toBe('run-abc-123')
expect(payload.taskId).toBe('task-abc-123')
expect(payload.teamId).toBe(42)
+ expect(payload.presenceGated).toBe(false)
})
+ it.each([
+ { name: 'true', claim: true, expected: true },
+ { name: 'false', claim: false, expected: false },
+ ])('carries a presence_gated claim of $name', async ({ claim, expected }) => {
+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE, presenceGated: claim })
+ const payload = await validateSandboxEventIngestToken(token, keys.publicKeys)
+
+ expect(payload.presenceGated).toBe(expected)
+ })
+
+ it.each([{ claim: 'yes' }, { claim: 1 }, { claim: null }])(
+ 'rejects a non-boolean presence_gated claim ($claim)',
+ async ({ claim }) => {
+ const token = await signToken({ audience: SANDBOX_EVENT_INGEST_AUDIENCE, presenceGated: claim })
+
+ await expect(validateSandboxEventIngestToken(token, keys.publicKeys)).rejects.toThrow(
+ 'presence_gated must be a boolean'
+ )
+ }
+ )
+
it('rejects a token with the wrong audience (stream_read)', async () => {
const token = await signToken({ audience: STREAM_READ_AUDIENCE })
diff --git a/services/agent-proxy/tests/lib/redis-stream.test.ts b/services/agent-proxy/tests/lib/redis-stream.test.ts
index 0bba0402f775..21dba6ed5021 100644
--- a/services/agent-proxy/tests/lib/redis-stream.test.ts
+++ b/services/agent-proxy/tests/lib/redis-stream.test.ts
@@ -11,7 +11,7 @@
import { describe, it, expect } from 'vitest'
-import { STREAM_COMPLETED_TTL_SECONDS } from '@/lib/constants.js'
+import { STREAM_COMPLETED_TTL_SECONDS, STREAM_WATCHED_TTL_SECONDS } from '@/lib/constants.js'
import {
TaskRunRedisStream,
getStreamKey,
@@ -21,6 +21,7 @@ import {
getHeartbeatKey,
getFirstCommandKey,
getFirstActivityKey,
+ getWatchedKey,
} from '@/lib/redis-stream.js'
import {
TaskRunStreamError,
@@ -427,12 +428,18 @@ class FakePipeline {
let _runCounter = 0
-function newStream(redis?: FakeRedis): { stream: TaskRunRedisStream; redis: FakeRedis; streamKey: string } {
+function newStream(
+ redis?: FakeRedis,
+ opts?: { presenceGated?: boolean }
+): { stream: TaskRunRedisStream; redis: FakeRedis; streamKey: string } {
const r = redis ?? new FakeRedis()
_runCounter++
const runId = `test-run-${_runCounter}`
const streamKey = getStreamKey(runId)
- const stream = new TaskRunRedisStream(streamKey, r as unknown as import('ioredis').Redis, { timeout: 60 })
+ const stream = new TaskRunRedisStream(streamKey, r as unknown as import('ioredis').Redis, {
+ timeout: 60,
+ presenceGated: opts?.presenceGated ?? false,
+ })
return { stream, redis: r, streamKey }
}
@@ -484,11 +491,11 @@ describe('redis-stream', () => {
it('accepts seq=1 as the first event (seq=0 is the initial sentinel)', async () => {
const { stream, redis, streamKey } = newStream()
- const id = await stream.writeEventWithSequence({ type: 'msg' }, 1)
+ const write = await stream.writeEventWithSequence({ type: 'msg' }, 1)
- expect(id).not.toBeNull()
- expect(typeof id).toBe('string')
- expect(id!.length).toBeGreaterThan(0)
+ expect(write.accepted).toBe(true)
+ expect(typeof write.streamId).toBe('string')
+ expect(write.streamId!.length).toBeGreaterThan(0)
// last-seq key updated
expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('1')
// event written to stream
@@ -504,21 +511,22 @@ describe('redis-stream', () => {
const id2 = await stream.writeEventWithSequence({ type: 'b' }, 2)
const id3 = await stream.writeEventWithSequence({ type: 'c' }, 3)
- expect(id1).not.toBeNull()
- expect(id2).not.toBeNull()
- expect(id3).not.toBeNull()
+ expect(id1.streamId).not.toBeNull()
+ expect(id2.streamId).not.toBeNull()
+ expect(id3.streamId).not.toBeNull()
expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('3')
expect(redis.readStreamData(streamKey)).toHaveLength(3)
})
- it('returns null for a duplicate sequence (already accepted)', async () => {
+ it('reports not-accepted for a duplicate sequence (already accepted)', async () => {
const { stream, redis, streamKey } = newStream()
const first = await stream.writeEventWithSequence({ type: 'first' }, 1)
const dup = await stream.writeEventWithSequence({ type: 'duplicate' }, 1)
- expect(first).not.toBeNull()
- expect(dup).toBeNull()
+ expect(first.streamId).not.toBeNull()
+ expect(dup.accepted).toBe(false)
+ expect(dup.streamId).toBeNull()
// Only the original event in stream
const data = redis.readStreamData(streamKey)
expect(data).toHaveLength(1)
@@ -526,12 +534,13 @@ describe('redis-stream', () => {
expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('1')
})
- it('returns null for seq=0 (treated as already accepted / initial sentinel)', async () => {
+ it('reports not-accepted for seq=0 (treated as already accepted / initial sentinel)', async () => {
const { stream } = newStream()
const result = await stream.writeEventWithSequence({ type: 'zero' }, 0)
- expect(result).toBeNull()
+ expect(result.accepted).toBe(false)
+ expect(result.streamId).toBeNull()
})
it('throws TaskRunStreamSequenceGap when seq skips ahead', async () => {
@@ -635,6 +644,80 @@ describe('redis-stream', () => {
})
})
+ // -----------------------------------------------------------------------
+ // presence gating
+ // -----------------------------------------------------------------------
+
+ describe('presence gating', () => {
+ it.each([
+ { name: 'gated and unwatched skips the mirror', presenceGated: true, watched: false, mirrored: false },
+ { name: 'gated and watched mirrors', presenceGated: true, watched: true, mirrored: true },
+ { name: 'ungated always mirrors', presenceGated: false, watched: false, mirrored: true },
+ ])('$name', async ({ presenceGated, watched, mirrored }) => {
+ const { stream, redis, streamKey } = newStream(undefined, { presenceGated })
+ if (watched) {
+ await stream.markWatched()
+ }
+
+ const write = await stream.writeEventWithSequence({ type: 'msg' }, 1)
+
+ expect(write.accepted).toBe(true)
+ expect(write.streamId !== null).toBe(mirrored)
+ expect(redis.readStreamData(streamKey)).toEqual(mirrored ? [{ type: 'msg' }] : [])
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('1')
+ })
+
+ it('keeps advancing the sequence across a skip so a later watched write is not a gap', async () => {
+ const { stream, redis, streamKey } = newStream(undefined, { presenceGated: true })
+
+ const skipped = await stream.writeEventWithSequence({ type: 'first' }, 1)
+ await stream.markWatched()
+ const mirrored = await stream.writeEventWithSequence({ type: 'second' }, 2)
+
+ expect(skipped.accepted).toBe(true)
+ expect(skipped.streamId).toBeNull()
+ expect(mirrored.streamId).not.toBeNull()
+ expect(redis.readStreamData(streamKey)).toEqual([{ type: 'second' }])
+ expect(redis.getStringValue(getSequenceKey(streamKey))).toBe('2')
+ })
+
+ it('markWatched sets the watched key with the shared TTL', async () => {
+ const { stream, redis, streamKey } = newStream(undefined, { presenceGated: true })
+
+ await stream.markWatched()
+
+ expect(redis.getStringValue(getWatchedKey(streamKey))).toBe('1')
+ const expiry = redis.getExpiryMs(getWatchedKey(streamKey))
+ expect(expiry).not.toBeNull()
+ expect(expiry!).toBeLessThanOrEqual(Date.now() + STREAM_WATCHED_TTL_SECONDS * 1000)
+ })
+
+ it.each([
+ {
+ name: 'markCompleteAfterSequence',
+ write: (stream: TaskRunRedisStream) => stream.markCompleteAfterSequence(1),
+ sentinel: { type: 'STREAM_STATUS', status: 'complete' },
+ },
+ {
+ name: 'markComplete',
+ write: (stream: TaskRunRedisStream) => stream.markComplete(),
+ sentinel: { type: 'STREAM_STATUS', status: 'complete' },
+ },
+ {
+ name: 'markError',
+ write: (stream: TaskRunRedisStream) => stream.markError('boom'),
+ sentinel: { type: 'STREAM_STATUS', status: 'error', error: 'boom' },
+ },
+ ])('$name still writes its sentinel while unwatched', async ({ write, sentinel }) => {
+ const { stream, redis, streamKey } = newStream(undefined, { presenceGated: true })
+ await stream.writeEventWithSequence({ type: 'msg' }, 1)
+
+ await write(stream)
+
+ expect(redis.readStreamData(streamKey)).toEqual([sentinel])
+ })
+ })
+
// -----------------------------------------------------------------------
// markComplete
// -----------------------------------------------------------------------
diff --git a/services/agent-proxy/tests/setup.ts b/services/agent-proxy/tests/setup.ts
index 15ae78693fdf..866bae1323f4 100644
--- a/services/agent-proxy/tests/setup.ts
+++ b/services/agent-proxy/tests/setup.ts
@@ -42,6 +42,7 @@ vi.mock('@/hono/metrics.js', () => ({
taskRunStreamResumeGapTotal: mockCounter,
taskRunStreamConnectionsRejectedTotal: mockCounter,
streamIngestEventsTotal: mockCounter,
+ taskRunStreamWriteSkippedTotal: mockCounter,
ingestClientDisconnectsTotal: mockCounter,
httpRequestsTotal: mockCounter,
httpRequestDurationSeconds: mockHistogram,
@@ -54,5 +55,6 @@ vi.mock('@/hono/metrics.js', () => ({
observeStreamResumeGap: vi.fn(),
observeStreamConnectionRejected: vi.fn(),
observeStreamIngestEvents: vi.fn(),
+ observeStreamWriteSkipped: vi.fn(),
observeIngestClientDisconnect: vi.fn(),
}))