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.

fix(tasks): isolate streams across task resumes (#118449)

Alessandro Pogliaghic54766909b8f
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index 2b8e6cb1cc45..a0c3d2f6cb06 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -147,6 +147,20 @@ checkpoint without pruning the live workspace. Directory names such as `.cache`
`.venv` do not establish that their contents can be rebuilt. The legacy
`allow_pruning` activity field remains readable but no longer enables deletion.
+`TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED` defaults to `false` during rollout.
+Deploy generation-aware token issuers and ingest handlers everywhere before enabling it.
+Leave rotation off until old workers drain; otherwise a resumed sandbox can receive
+an old-format token that the new ingest handlers reject. Already rotated streams
+keep their generation if rotation is disabled again.
+Stream completion is bound to the workflow's stream generation. A resume replaces
+that generation atomically with the stream reset, so late cleanup cannot close it.
+Dispatch saves the generation on the run and workflow input before context loading.
+Cancellation can tear down the sandbox without Redis and retains that generation across completion retries.
+Sandbox ingest tokens carry the same generation. Django and agent-proxy check it
+atomically when accepting events or completion, rejecting stale senders with HTTP 403
+and `stream_generation_mismatch`. The sender discards its buffer and stops on this code.
+Tokens issued before generation tracking remain valid only until the stream resets.
+
## Running via the UI
This is very minimal at the moment, but the tasks page can be used to see what
diff --git a/packages/agent/packages/agent/src/server/event-stream-sender.test.ts b/packages/agent/packages/agent/src/server/event-stream-sender.test.ts
index 24fee1467ed9..05322c326060 100644
--- a/packages/agent/packages/agent/src/server/event-stream-sender.test.ts
+++ b/packages/agent/packages/agent/src/server/event-stream-sender.test.ts
@@ -129,6 +129,35 @@ describe("TaskRunEventStreamSender", () => {
vi.unstubAllGlobals();
});
+ it.each(["sync", "upload"])(
+ "stops a superseded sender during %s",
+ async (phase) => {
+ vi.useFakeTimers();
+ try {
+ const fetchMock = vi.fn(
+ async (_url: string | URL | Request, init?: RequestInit) => {
+ const body = await readRequestBody(init);
+ if (phase === "upload" && !body) return responseForBody(body);
+ return new Response(
+ JSON.stringify({ code: "stream_generation_mismatch" }),
+ { status: 403 },
+ );
+ },
+ );
+ vi.stubGlobal("fetch", fetchMock);
+ const sender = createSender({ keepProxyStreamOpen: false });
+ sender.enqueue({ type: "old-event" });
+ await vi.advanceTimersByTimeAsync(100);
+ sender.enqueue({ type: "later-event" });
+ await vi.advanceTimersByTimeAsync(2000);
+ await sender.stop();
+ expect(fetchMock).toHaveBeenCalledTimes(phase === "sync" ? 1 : 2);
+ } finally {
+ vi.useRealTimers();
+ }
+ },
+ );
+
it.each([true, false])(
"streams ordered NDJSON events with complete=%s",
async (complete) => {
diff --git a/packages/agent/packages/agent/src/server/event-stream-sender.ts b/packages/agent/packages/agent/src/server/event-stream-sender.ts
index 596334f8709a..4d7273bdfd19 100644
--- a/packages/agent/packages/agent/src/server/event-stream-sender.ts
+++ b/packages/agent/packages/agent/src/server/event-stream-sender.ts
@@ -34,6 +34,7 @@ interface EventEnvelope {
}
interface IngestResponse {
+ code?: unknown;
last_accepted_seq?: unknown;
}
@@ -212,6 +213,7 @@ export class TaskRunEventStreamSender {
try {
await this.flush();
+ if (this.transportCompleted) return;
if (complete) {
await this.writeCompletionLine();
}
@@ -230,6 +232,7 @@ export class TaskRunEventStreamSender {
);
}
+ if (this.transportCompleted) return;
const madeProgress =
this.bufferedEvents.length < previousLength ||
this.bufferRevision !== previousRevision;
@@ -708,7 +711,19 @@ export class TaskRunEventStreamSender {
}
try {
- return { parsed: JSON.parse(text) as IngestResponse, text };
+ const parsed = JSON.parse(text) as IngestResponse;
+ if (
+ response.status === 403 &&
+ parsed?.code === "stream_generation_mismatch"
+ ) {
+ this.stopped = true;
+ this.transportCompleted = true;
+ this.bufferedEvents = [];
+ if (this.flushTimer) clearTimeout(this.flushTimer);
+ this.flushTimer = null;
+ await this.abortActiveStream();
+ }
+ return { parsed, text };
} catch {
return { parsed: null, text };
}
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index 13428bdccf87..ac01c27a185c 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -81,6 +81,10 @@ TEMPORAL_LOG_LEVEL: str = os.getenv("TEMPORAL_LOG_LEVEL", "INFO")
TEMPORAL_OTEL_PLUGIN_ENABLED: bool = get_from_env("TEMPORAL_OTEL_PLUGIN_ENABLED", False, type_cast=str_to_bool)
TEMPORAL_OTEL_LIBRARIES_TO_INSTRUMENT: list[str] = get_list(os.getenv("TEMPORAL_OTEL_LIBRARIES_TO_INSTRUMENT", ""))
+TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED: bool = get_from_env(
+ "TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED", False, type_cast=str_to_bool
+)
+
SANDBOX_PROVIDER: str | None = get_from_env(
"SANDBOX_PROVIDER", None, optional=True
) # When not set: defaults to "docker" in DEBUG mode, "modal" in production
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index d1fa6786831d..d274eb82ef4d 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -2914,6 +2914,8 @@ _PROTECTED_RUN_STATE_KEYS = frozenset(
"cancel_requested_by_user_id",
"cancel_source",
"cancel_fallback_cleanup_complete",
+ "cancel_fallback_stream_generation",
+ "stream_generation",
"pending_external_followups",
"pending_external_followups_generation",
"pending_external_followups_checkpoint",
diff --git a/products/tasks/backend/facade/cancellation.py b/products/tasks/backend/facade/cancellation.py
index dd76641142ce..2546a3687372 100644
--- a/products/tasks/backend/facade/cancellation.py
+++ b/products/tasks/backend/facade/cancellation.py
@@ -11,7 +11,12 @@ from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.client import sync_connect
from products.tasks.backend import push_dispatcher
+from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_INITIAL_GENERATION,
+ get_task_run_stream_generation,
+)
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.process_task.activities.cleanup_sandbox import (
CleanupSandboxInput,
cleanup_sandbox_now,
@@ -85,7 +90,9 @@ def _publish_cancel_fallback_completion(run: TaskRun) -> bool:
return True
try:
- publish_run_stream_completion(str(run.id))
+ publish_run_stream_completion(
+ str(run.id), stream_generation=(run.state or {}).get("cancel_fallback_stream_generation")
+ )
TaskRun.update_state_atomic(run.id, updates={"cancel_fallback_cleanup_complete": False})
except Exception:
logger.warning("Failed to complete stream for cancelled run %s", run.id, exc_info=True)
@@ -200,9 +207,19 @@ def cancel_task_run(
return "not_found", None
if run.is_terminal:
return "already_terminal", tasks_api._task_run_detail_to_dto(run)
+ stream_generation = (run.state or {}).get("stream_generation")
+ if not isinstance(stream_generation, str) or not stream_generation:
+ try:
+ stream_generation = get_task_run_stream_generation(str(run.id), run_uses_dedicated_stream(run.state))
+ except Exception:
+ logger.warning("Failed to read stream generation for cancelled run %s", run.id, exc_info=True)
+ stream_generation = TASK_RUN_STREAM_INITIAL_GENERATION
if not _cleanup_run_without_workflow(run):
return "unavailable", tasks_api._task_run_detail_to_dto(run)
- TaskRun.update_state_atomic(run.id, updates={"cancel_fallback_cleanup_complete": True})
+ TaskRun.update_state_atomic(
+ run.id,
+ updates={"cancel_fallback_cleanup_complete": True, "cancel_fallback_stream_generation": stream_generation},
+ )
dto = tasks_api.update_task_run(
run.id,
task_id,
diff --git a/products/tasks/backend/logic/services/connection_token.py b/products/tasks/backend/logic/services/connection_token.py
index 27a090cc12bd..39d376799d81 100644
--- a/products/tasks/backend/logic/services/connection_token.py
+++ b/products/tasks/backend/logic/services/connection_token.py
@@ -14,6 +14,7 @@ from cryptography.hazmat.primitives import serialization
from products.tasks.backend.feature_flags import run_stream_presence_gated, run_stream_thin_tail
from products.tasks.backend.logic.services.sandbox_config import SANDBOX_TTL_SECONDS
+from products.tasks.backend.redis import run_uses_dedicated_stream
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
@@ -45,6 +46,7 @@ class SandboxEventIngestTokenPayload:
presence_gated: bool = False
thin_tail: bool = False
origin_product: str | None = None
+ stream_generation: str | None = None
@dataclass(frozen=True)
@@ -266,6 +268,7 @@ def create_sandbox_event_ingest_token(
ttl: timedelta = SANDBOX_EVENT_INGEST_TOKEN_TTL,
*,
sandbox_id: str | None = None,
+ stream_generation: str | None = None,
) -> str:
"""
Create a run-scoped JWT token for sandbox-to-Django live event ingest.
@@ -273,6 +276,8 @@ def create_sandbox_event_ingest_token(
This token intentionally carries no user identity and grants one capability:
appending ordered live events for this task run.
"""
+ from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_generation
+
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")
@@ -287,6 +292,8 @@ def create_sandbox_event_ingest_token(
"presence_gated": presence_gated,
"thin_tail": thin_tail,
"origin_product": task_run.task.origin_product,
+ "stream_generation": stream_generation
+ or get_task_run_stream_generation(str(task_run.id), run_uses_dedicated_stream(task_run.state)),
},
)
@@ -301,6 +308,7 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPa
presence_gated = payload.get("presence_gated", False)
thin_tail = payload.get("thin_tail", False)
origin_product = payload.get("origin_product")
+ stream_generation = payload.get("stream_generation")
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")
@@ -312,6 +320,8 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPa
raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
if origin_product is not None and not isinstance(origin_product, str):
raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
+ if "stream_generation" in payload and (not isinstance(stream_generation, str) or not stream_generation):
+ raise jwt.InvalidTokenError("Sandbox event ingest token has invalid claims")
return SandboxEventIngestTokenPayload(
run_id=run_id,
@@ -321,6 +331,7 @@ def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPa
presence_gated=presence_gated,
thin_tail=thin_tail,
origin_product=origin_product,
+ stream_generation=stream_generation,
)
diff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.py
index e21a68d65a3f..395640fbd27b 100644
--- a/products/tasks/backend/logic/stream/event_ingest.py
+++ b/products/tasks/backend/logic/stream/event_ingest.py
@@ -33,14 +33,17 @@ from products.tasks.backend.logic.services.process_killed import (
from products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_event
from products.tasks.backend.logic.stream.budget_steer import BudgetSteerCapture
from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_INITIAL_GENERATION,
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
+ TaskRunStreamGenerationMismatch,
TaskRunStreamSequenceGap,
get_task_run_stream_key,
)
from products.tasks.backend.metrics import observe_sandbox_process_killed, observe_stream_write_skipped
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.turn_completed import dispatch_turn_completed
from ee.hogai.sandbox import (
@@ -144,16 +147,18 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,
return True
try:
- claims = await _authorize_event_ingest_request(scope, route)
+ claims, use_dedicated = await _authorize_event_ingest_request(scope, route)
except EventIngestHTTPError as error:
await _send_json(send, error.status_code, error.payload)
return True
redis_stream = TaskRunRedisStream(
get_task_run_stream_key(claims.run_id),
+ use_dedicated=use_dedicated,
presence_gated=claims.presence_gated,
thin_tail=claims.thin_tail,
origin_product=claims.origin_product,
+ expected_generation=claims.stream_generation or TASK_RUN_STREAM_INITIAL_GENERATION,
)
try:
@@ -174,6 +179,9 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,
except EventIngestCaptureError:
await _send_json(send, 503, {"error": "Failed to capture RTK savings; retry the request"})
return True
+ except TaskRunStreamGenerationMismatch as error:
+ await _send_json(send, 403, {"error": str(error), "code": "stream_generation_mismatch"})
+ return True
except TaskRunStreamSequenceGap as error:
await _send_json(send, 409, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})
return True
@@ -694,18 +702,18 @@ def _is_session_update(event: dict) -> bool:
return isinstance(notification, dict) and notification.get("method") == "session/update"
-def _task_run_exists_sync(run_id: str, task_id: str, team_id: int) -> bool:
+def _task_run_state_sync(run_id: str, task_id: str, team_id: int) -> dict | None:
if not settings.TEST:
close_old_connections()
- return TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).exists()
+ return TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).values_list("state", flat=True).first()
-async def _task_run_exists(run_id: str, task_id: str, team_id: int) -> bool:
+async def _task_run_state(run_id: str, task_id: str, team_id: int) -> dict | None:
"""Existence check on a sync_to_async thread whose pooled connection Django never
health-checks. `close_old_connections()` clears a stale connection before the read; a
single retry recovers a transparent reconnect since this is a side-effect-free read.
An uncaught OperationalError here would otherwise crash the whole ingest request."""
- run_check = sync_to_async(_task_run_exists_sync, thread_sensitive=True)
+ run_check = sync_to_async(_task_run_state_sync, thread_sensitive=True)
try:
return await run_check(run_id, task_id, team_id)
except (OperationalError, InterfaceError):
@@ -738,7 +746,7 @@ def _match_event_ingest_route(path: str) -> EventIngestRoute | None:
async def _authorize_event_ingest_request(
scope: ASGIMessage, route: EventIngestRoute
-) -> SandboxEventIngestTokenPayload:
+) -> tuple[SandboxEventIngestTokenPayload, bool]:
token = _get_bearer_token(scope)
if token is None:
raise EventIngestHTTPError(401, {"error": "Missing authorization bearer token"})
@@ -756,10 +764,11 @@ async def _authorize_event_ingest_request(
if route.project_id != "@current" and (not route.project_id.isdigit() or int(route.project_id) != claims.team_id):
raise EventIngestHTTPError(403, {"error": "Token does not match project"})
- if not await _task_run_exists(claims.run_id, claims.task_id, claims.team_id):
+ state = await _task_run_state(claims.run_id, claims.task_id, claims.team_id)
+ if state is None:
raise EventIngestHTTPError(404, {"error": "Task run not found"})
- return claims
+ return claims, run_uses_dedicated_stream(state)
def _get_header(scope: ASGIMessage, header_name: bytes) -> str | None:
diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.py
index b044fee9a974..868455c113ef 100644
--- a/products/tasks/backend/logic/stream/redis_stream.py
+++ b/products/tasks/backend/logic/stream/redis_stream.py
@@ -3,6 +3,7 @@ import time
import asyncio
from collections.abc import AsyncGenerator, Iterator
from typing import TYPE_CHECKING, Optional
+from uuid import uuid4
from django.conf import settings
@@ -35,6 +36,7 @@ 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_INITIAL_GENERATION = "initial"
TASK_RUN_STREAM_READ_COUNT = 16
# XREAD BLOCK is push-based (XADD wakes the blocked client immediately), so a
# longer block only cuts idle polling — it never delays delivery. Keep it under
@@ -98,6 +100,10 @@ class TaskRunStreamError(Exception):
pass
+class TaskRunStreamGenerationMismatch(Exception):
+ pass
+
+
class TaskRunStreamSequenceGap(Exception):
def __init__(self, *, expected_sequence: int, received_sequence: int, last_accepted_seq: int):
self.expected_sequence = expected_sequence
@@ -172,6 +178,16 @@ def get_task_run_stream_completed_key(stream_key: str) -> str:
return f"{stream_key}:completed"
+def get_task_run_stream_generation(run_id: str, use_dedicated: bool = False) -> str:
+ client = get_tasks_stream_redis_sync(use_dedicated)
+ key = f"{get_task_run_stream_key(run_id)}:generation"
+ client.set(key, TASK_RUN_STREAM_INITIAL_GENERATION, nx=True, ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
+ generation = client.get(key)
+ if generation is None:
+ raise RuntimeError("Task run stream generation is unavailable")
+ return _normalize_stream_id(generation)
+
+
def get_task_run_stream_agent_active_key(stream_key: str) -> str:
return f"{stream_key}:ingest-agent-active"
@@ -216,6 +232,7 @@ class TaskRunRedisStream:
presence_gated: bool = False,
thin_tail: bool = False,
origin_product: str | None = None,
+ expected_generation: str | None = None,
):
self._stream_key = stream_key
self._redis_client = get_tasks_stream_redis_async(use_dedicated)
@@ -226,6 +243,7 @@ class TaskRunRedisStream:
self._presence_gated = presence_gated
self._thin_tail = thin_tail
self._origin_product = origin_product
+ self._expected_generation = expected_generation
self._watched_cached_until = 0.0
self._last_watched_refresh_at: float | None = None
@@ -374,16 +392,29 @@ class TaskRunRedisStream:
return TASK_RUN_STREAM_THIN_MAX_LENGTH
return self._max_length
- async def _xadd_event(self, event: dict, *, ttl: int | None = None) -> str:
+ async def _xadd_event(self, event: dict, *, ttl: int | None = None, complete: bool = False) -> str:
raw = json.dumps(event)
- stream_id = await self._redis_client.xadd(
- self._stream_key,
- {DATA_KEY: raw},
- maxlen=self._maxlen_for_event(event),
- approximate=True,
- )
- await self._redis_client.expire(self._stream_key, self._timeout if ttl is None else ttl)
- return _normalize_stream_id(stream_id)
+ generation_key = f"{self._stream_key}:generation"
+ while True:
+ async with self._redis_client.pipeline(transaction=True) as pipe:
+ try:
+ await pipe.watch(generation_key)
+ self._check_generation(await pipe.get(generation_key))
+ pipe.multi()
+ pipe.xadd(
+ self._stream_key,
+ {DATA_KEY: raw},
+ maxlen=self._maxlen_for_event(event),
+ approximate=True,
+ )
+ pipe.expire(self._stream_key, self._timeout if ttl is None else ttl)
+ pipe.expire(generation_key, self._sequence_timeout)
+ if complete:
+ pipe.set(get_task_run_stream_completed_key(self._stream_key), "1", ex=self._sequence_timeout)
+ results = await pipe.execute()
+ return _normalize_stream_id(results[0])
+ except redis_exceptions.WatchError:
+ continue
async def _is_watched(self) -> bool:
"""Return whether a reader is attached, caching only a positive answer."""
@@ -407,6 +438,7 @@ class TaskRunRedisStream:
Terminal sentinels bypass this gate.
"""
if self._presence_gated and not await self._is_watched():
+ self._check_generation(await self._redis_client.get(f"{self._stream_key}:generation"))
observe_stream_write_skipped("relay", self._origin_product)
return None
return await self._xadd_event(event, ttl=ttl)
@@ -525,7 +557,8 @@ class TaskRunRedisStream:
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)
- watch_keys = [sequence_key, completed_key]
+ generation_key = f"{self._stream_key}:generation"
+ watch_keys = [sequence_key, completed_key, generation_key]
if self._presence_gated:
watch_keys.append(watched_key)
@@ -533,6 +566,7 @@ class TaskRunRedisStream:
async with self._redis_client.pipeline(transaction=True) as pipe:
try:
await pipe.watch(*watch_keys)
+ self._check_generation(await pipe.get(generation_key))
last_sequence = _normalize_redis_int(await pipe.get(sequence_key))
completed = bool(await pipe.exists(completed_key))
if not _check_next_sequence(sequence, last_sequence, completed=completed):
@@ -549,6 +583,13 @@ class TaskRunRedisStream:
except redis_exceptions.WatchError:
continue
+ def _check_generation(self, generation: bytes | str | None) -> None:
+ if (
+ self._expected_generation is not None
+ and _normalize_stream_id(generation or TASK_RUN_STREAM_INITIAL_GENERATION) != self._expected_generation
+ ):
+ raise TaskRunStreamGenerationMismatch("Task run stream generation has changed")
+
def _queue_sequenced_write(
self, pipe: "Pipeline", event: dict, sequence: int, *, mirror: bool, pending_side_effect: str | None
) -> None:
@@ -565,6 +606,7 @@ class TaskRunRedisStream:
)
pipe.expire(self._stream_key, self._timeout)
pipe.set(get_task_run_stream_sequence_key(self._stream_key), sequence, ex=self._sequence_timeout)
+ pipe.expire(f"{self._stream_key}:generation", 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)
pipe.set(pending_key, "1", ex=self._sequence_timeout)
@@ -573,6 +615,7 @@ class TaskRunRedisStream:
self, event: dict, sequence: int, pending_side_effect: str | None = None
) -> TaskRunStreamWriteResult:
"""Apply sequencing semantics without WATCH/MULTI for fakeredis."""
+ self._check_generation(await self._redis_client.get(f"{self._stream_key}:generation"))
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)
@@ -596,12 +639,14 @@ class TaskRunRedisStream:
return
completed_key = get_task_run_stream_completed_key(self._stream_key)
+ generation_key = f"{self._stream_key}:generation"
raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})
while True:
async with self._redis_client.pipeline(transaction=True) as pipe:
try:
- await pipe.watch(completed_key)
+ await pipe.watch(completed_key, generation_key)
+ self._check_generation(await pipe.get(generation_key))
if await pipe.exists(completed_key):
await self._redis_client.expire(self._stream_key, self._completed_timeout)
return
@@ -615,12 +660,14 @@ class TaskRunRedisStream:
)
pipe.expire(self._stream_key, self._completed_timeout)
pipe.set(completed_key, "1", ex=self._sequence_timeout)
+ pipe.expire(generation_key, self._sequence_timeout)
await pipe.execute()
return
except redis_exceptions.WatchError:
continue
async def _mark_complete_for_tests(self) -> None:
+ self._check_generation(await self._redis_client.get(f"{self._stream_key}:generation"))
completed_key = get_task_run_stream_completed_key(self._stream_key)
if await self._redis_client.exists(completed_key):
await self._redis_client.expire(self._stream_key, self._completed_timeout)
@@ -637,12 +684,14 @@ class TaskRunRedisStream:
sequence_key = get_task_run_stream_sequence_key(self._stream_key)
completed_key = get_task_run_stream_completed_key(self._stream_key)
+ generation_key = f"{self._stream_key}:generation"
raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})
while True:
async with self._redis_client.pipeline(transaction=True) as pipe:
try:
- await pipe.watch(sequence_key, completed_key)
+ await pipe.watch(sequence_key, completed_key, generation_key)
+ self._check_generation(await pipe.get(generation_key))
last_sequence_raw = await pipe.get(sequence_key)
last_sequence = _normalize_redis_int(last_sequence_raw)
if await pipe.exists(completed_key):
@@ -672,6 +721,7 @@ class TaskRunRedisStream:
continue
async def _mark_complete_after_sequence_for_tests(self, final_sequence: int) -> None:
+ self._check_generation(await self._redis_client.get(f"{self._stream_key}:generation"))
sequence_key = get_task_run_stream_sequence_key(self._stream_key)
completed_key = get_task_run_stream_completed_key(self._stream_key)
last_sequence_raw = await self._redis_client.get(sequence_key)
@@ -695,10 +745,9 @@ class TaskRunRedisStream:
async def mark_error(self, error: str) -> None:
"""Write an error sentinel to signal stream failure."""
await self._xadd_event(
- {"type": "STREAM_STATUS", "status": "error", "error": error[:500]}, ttl=self._completed_timeout
- )
- await self._redis_client.set(
- get_task_run_stream_completed_key(self._stream_key), "1", ex=self._sequence_timeout
+ {"type": "STREAM_STATUS", "status": "error", "error": error[:500]},
+ ttl=self._completed_timeout,
+ complete=True,
)
async def delete_stream(self) -> bool:
@@ -720,6 +769,7 @@ class TaskRunRedisStream:
first_command_key,
first_activity_key,
watched_key,
+ f"{self._stream_key}:generation",
)
return _normalize_redis_int(deleted) > 0
except Exception:
@@ -739,15 +789,19 @@ def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:
client = get_tasks_stream_redis_sync(use_dedicated)
try:
- client.delete(
- stream_key,
- sequence_key,
- completed_key,
- agent_active_key,
- heartbeat_key,
- first_command_key,
- first_activity_key,
- )
+ with client.pipeline(transaction=True) as pipe:
+ pipe.delete(
+ stream_key,
+ sequence_key,
+ completed_key,
+ agent_active_key,
+ heartbeat_key,
+ first_command_key,
+ first_activity_key,
+ )
+ if settings.TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED:
+ pipe.set(f"{stream_key}:generation", uuid4().hex, ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
+ pipe.execute()
return True
except Exception:
logger.exception("task_run_stream_reset_failed", run_id=run_id)
@@ -795,16 +849,20 @@ def publish_task_run_stream_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)
+ client.expire(f"{stream_key}:generation", TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
return _normalize_stream_id(stream_id)
except Exception:
logger.exception("task_run_stream_publish_failed", run_id=run_id)
return None
-def publish_task_run_stream_complete(run_id: str, use_dedicated: bool = False) -> bool:
+def publish_task_run_stream_complete(
+ run_id: str, use_dedicated: bool = False, *, expected_generation: str | None = None
+) -> bool:
"""Synchronously publish a completion sentinel for a task-run stream."""
stream_key = get_task_run_stream_key(run_id)
completed_key = get_task_run_stream_completed_key(stream_key)
+ generation_key = f"{stream_key}:generation"
client = get_tasks_stream_redis_sync(use_dedicated)
raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})
@@ -812,6 +870,12 @@ def publish_task_run_stream_complete(run_id: str, use_dedicated: bool = False) -
if settings.TEST:
# fakeredis doesn't support WATCH/MULTI; the sequencing race the
# transaction guards against can't happen under the test harness.
+ if (
+ expected_generation is not None
+ and (client.get(generation_key) or TASK_RUN_STREAM_INITIAL_GENERATION.encode())
+ != expected_generation.encode()
+ ):
+ return True
if client.exists(completed_key):
client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
return True
@@ -823,15 +887,20 @@ def publish_task_run_stream_complete(run_id: str, use_dedicated: bool = False) -
with client.pipeline(transaction=True) as pipe:
while True:
try:
- pipe.watch(completed_key)
- if pipe.exists(completed_key):
+ pipe.watch(completed_key, generation_key)
+ if (
+ expected_generation is not None
+ and (pipe.get(generation_key) or TASK_RUN_STREAM_INITIAL_GENERATION.encode())
+ != expected_generation.encode()
+ ):
pipe.reset()
- client.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
return True
+ completed = pipe.exists(completed_key)
pipe.multi()
- pipe.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)
+ if not completed:
+ pipe.xadd(stream_key, {DATA_KEY: raw}, maxlen=TASK_RUN_STREAM_MAX_LENGTH, approximate=True)
+ pipe.set(completed_key, "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
pipe.expire(stream_key, TASK_RUN_STREAM_COMPLETED_TIMEOUT)
- pipe.set(completed_key, "1", ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT)
pipe.execute()
return True
except redis_exceptions.WatchError:
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 5a5e2e70030d..4d19255f6900 100644
--- a/products/tasks/backend/logic/stream/tests/test_redis_stream.py
+++ b/products/tasks/backend/logic/stream/tests/test_redis_stream.py
@@ -5,6 +5,10 @@ from uuid import uuid4
import pytest
from unittest.mock import patch
+from django.test import override_settings
+
+from redis.asyncio.client import Pipeline
+
from products.tasks.backend.logic.stream.redis_stream import (
DATA_KEY,
TASK_RUN_STREAM_COMPLETED_TIMEOUT,
@@ -14,9 +18,11 @@ from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
+ TaskRunStreamGenerationMismatch,
TaskRunStreamSequenceGap,
_stream_id_sort_key,
get_task_run_stream_completed_key,
+ get_task_run_stream_generation,
get_task_run_stream_key,
get_task_run_stream_watched_key,
publish_task_run_stream_complete,
@@ -49,6 +55,45 @@ async def test_write_event_with_sequence_accepts_next_sequence() -> None:
await redis_stream.delete_stream()
+ "write",
+ [
+ pytest.param(lambda stream: stream.write_event_with_sequence({"type": "late"}, 1), id="ingest"),
+ pytest.param(lambda stream: stream.mark_complete_after_sequence(0), id="ingest_complete"),
+ pytest.param(lambda stream: stream.write_event({"type": "late"}), id="relay"),
+ pytest.param(lambda stream: stream.mark_complete(), id="relay_complete"),
+ pytest.param(lambda stream: stream.mark_error("late"), id="relay_error"),
+ ],
+)
[email protected]("reset_during_write", [False, True])
+async def test_stream_generation_check_is_atomic(
+ write: Callable[[TaskRunRedisStream], Awaitable[object]], reset_during_write: bool
+) -> None:
+ redis_stream = _new_stream()
+ redis_stream._expected_generation = "original"
+ client = redis_stream._redis_client
+ generation_key = f"{redis_stream._stream_key}:generation"
+ await client.set(generation_key, "original" if reset_during_write else "replacement")
+ get = Pipeline.get
+
+ async def reset_after_read(pipe: Pipeline, key: str) -> bytes | str | None:
+ value = await get(pipe, key)
+ if key == generation_key and value == b"original":
+ await client.set(generation_key, "replacement")
+ return value
+
+ try:
+ with patch("django.conf.settings.TEST", False), patch.object(Pipeline, "get", reset_after_read):
+ with pytest.raises(TaskRunStreamGenerationMismatch):
+ await write(redis_stream)
+ assert await _read_stream_events(redis_stream) == []
+ assert await redis_stream.get_last_sequence() == 0
+ assert not await client.exists(get_task_run_stream_completed_key(redis_stream._stream_key))
+ finally:
+ await redis_stream.delete_stream()
+
+
@pytest.mark.asyncio
async def test_write_event_with_sequence_rejects_sequence_gap() -> None:
redis_stream = _new_stream()
@@ -244,6 +289,7 @@ def test_publish_task_run_stream_event_honors_presence_gating(watched: bool) ->
reset_task_run_stream(run_id)
+@override_settings(TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED=True)
def test_reset_task_run_stream_keeps_watched_lease() -> None:
run_id = f"test:{uuid4()}"
stream_key = get_task_run_stream_key(run_id)
@@ -252,10 +298,14 @@ def test_reset_task_run_stream_keeps_watched_lease() -> None:
try:
client.set(watched_key, "1", ex=TASK_RUN_STREAM_WATCHED_TIMEOUT)
client.xadd(stream_key, {"data": "{}"})
+ generation = get_task_run_stream_generation(run_id)
assert reset_task_run_stream(run_id)
+ assert get_task_run_stream_generation(run_id) != generation
+ assert publish_task_run_stream_complete(run_id, expected_generation=generation)
assert not client.exists(stream_key)
+ assert not client.exists(get_task_run_stream_completed_key(stream_key))
assert client.exists(watched_key)
finally:
client.delete(watched_key)
diff --git a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
index 1c38fa18a5fa..66258165a54f 100644
--- a/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
+++ b/products/tasks/backend/management/commands/run_task_workflow_dispatcher.py
@@ -270,9 +270,6 @@ class Command(BaseCommand):
await sync_to_async(mark_dead)(dispatch.id, instance_id, usage_error, "usage_limit")
WORKFLOW_DISPATCH_ATTEMPT_TOTAL.labels(kind=dispatch.dispatch_kind, outcome="dead").inc()
return
- run_state = await sync_to_async(_capture_run_feature_flags_in_worker_thread, thread_sensitive=False)(
- str(run.id)
- )
if is_restart:
from products.tasks.backend.facade.streams import reset_task_run_stream # noqa: PLC0415
from products.tasks.backend.redis import run_uses_dedicated_stream # noqa: PLC0415
@@ -282,6 +279,9 @@ class Command(BaseCommand):
)
if not reset:
raise RuntimeError("Failed to reset task run event stream")
+ run_state = await sync_to_async(_capture_run_feature_flags_in_worker_thread, thread_sensitive=False)(
+ str(run.id)
+ )
workflow_input = ProcessTaskInput(
run_id=str(run.id),
create_pr=options.create_pr if options else True,
diff --git a/products/tasks/backend/temporal/client.py b/products/tasks/backend/temporal/client.py
index e520af89dbbf..92916d550604 100644
--- a/products/tasks/backend/temporal/client.py
+++ b/products/tasks/backend/temporal/client.py
@@ -37,8 +37,13 @@ from products.tasks.backend.logic.services.dev_stack_image_refresh import reconc
from products.tasks.backend.logic.services.dev_stack_image_state import DevStackImageState
from products.tasks.backend.logic.services.run_actor import get_actor_distinct_id, get_task_run_credential_user
from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_for_run
+from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_INITIAL_GENERATION,
+ get_task_run_stream_generation,
+)
from products.tasks.backend.metrics import AGENT_OTEL_TELEMETRY_STAMPED_TOTAL, observe_task_run_workflow_start
from products.tasks.backend.models import TaskRun
+from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.bake_dev_stack_image.workflow import BakeDevStackImageInput
from products.tasks.backend.temporal.build_image.workflow import BuildSandboxImageInput
from products.tasks.backend.temporal.constants import (
@@ -186,6 +191,11 @@ def _capture_run_feature_flags(run_id: str) -> dict[str, Any]:
return {}
state = task_run.state or {}
+ generation = get_task_run_stream_generation(run_id, run_uses_dedicated_stream(state))
+ if state.get("stream_generation") != generation:
+ TaskRun.update_state_atomic(run_id, updates={"stream_generation": generation})
+ state = {**state, "stream_generation": generation}
+
need_event_ingest = not isinstance(state.get("sandbox_event_ingest_enabled"), bool)
need_otel_telemetry = not isinstance(state.get(AGENT_OTEL_TELEMETRY_STATE_KEY), bool)
pending_boot_flags = [
@@ -272,6 +282,11 @@ async def start_process_task_workflow(
run_state: dict[str, Any],
rpc_timeout: timedelta | None = None,
) -> None:
+ if workflow_input.stream_generation is None:
+ generation = run_state.get("stream_generation")
+ workflow_input.stream_generation = (
+ generation if isinstance(generation, str) else TASK_RUN_STREAM_INITIAL_GENERATION
+ )
with run_trace_context(workflow_input.run_id, enabled=agent_otel_telemetry_enabled_for_state(run_state)):
await client.start_workflow(
"process-task",
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index bd8b8697968c..81324a8422e3 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -1457,6 +1457,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
team_id=self.context.team_id,
distinct_id=self.context.distinct_id,
sandbox_id=sandbox_id,
+ stream_generation=self.context.stream_generation,
),
start_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
schedule_to_close_timeout=RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT,
diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
index 923eceae9c5d..24c6f0ba422d 100644
--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py
@@ -14,7 +14,10 @@ from products.tasks.backend.logic.services.sandbox_usage import (
measure_sandbox_billed_cpu_usage,
measure_sandbox_cpu_usage,
)
-from products.tasks.backend.logic.stream.redis_stream import publish_task_run_stream_complete
+from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_INITIAL_GENERATION,
+ publish_task_run_stream_complete,
+)
from products.tasks.backend.models import SandboxSession, TaskRun
from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.observability import log_activity_execution
@@ -22,23 +25,30 @@ from products.tasks.backend.temporal.observability import log_activity_execution
logger = logging.getLogger(__name__)
-@dataclass
+@dataclass(frozen=False)
class CleanupSandboxInput:
sandbox_id: str
run_id: str | None = None
complete_stream_on_cleanup: bool = False
stop_agent_server_on_cleanup: bool = False
raise_on_error: bool = False
+ stream_generation: str | None = None
-@dataclass
+@dataclass(frozen=True)
class CompleteRunStreamInput:
run_id: str
+ stream_generation: str | None = None
-def publish_run_stream_completion(run_id: str) -> None:
+def publish_run_stream_completion(run_id: str, *, stream_generation: str | None = None) -> None:
state = TaskRun.objects.filter(id=run_id).values_list("state", flat=True).first()
- if not publish_task_run_stream_complete(run_id, run_uses_dedicated_stream(state)):
+ published = publish_task_run_stream_complete(
+ run_id,
+ run_uses_dedicated_stream(state),
+ expected_generation=stream_generation or TASK_RUN_STREAM_INITIAL_GENERATION,
+ )
+ if not published:
raise RuntimeError(f"Failed to complete task run stream {run_id}")
@@ -134,7 +144,7 @@ def cleanup_sandbox_now(input: CleanupSandboxInput) -> None:
if input.complete_stream_on_cleanup and input.run_id and stream_completion_safe:
try:
- publish_run_stream_completion(input.run_id)
+ publish_run_stream_completion(input.run_id, stream_generation=input.stream_generation)
except Exception:
logger.warning("cleanup_sandbox_stream_completion_failed", extra={"run_id": input.run_id}, exc_info=True)
raise
@@ -163,4 +173,4 @@ def cleanup_sandbox(input: CleanupSandboxInput) -> None:
@asyncify
def complete_run_stream(input: CompleteRunStreamInput) -> None:
with log_activity_execution("complete_run_stream", run_id=input.run_id):
- publish_run_stream_completion(input.run_id)
+ publish_run_stream_completion(input.run_id, stream_generation=input.stream_generation)
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index ab4d20838edb..f4b310358ce3 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -75,7 +75,9 @@ from products.tasks.backend.logic.services.sandbox_config import (
MAX_SANDBOX_TTL_SECONDS,
)
from products.tasks.backend.logic.services.store_skills import resolve_store_skills
+from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_generation
from products.tasks.backend.models import SandboxCustomImage, SandboxEnvironment, Task, TaskRun
+from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.constants import resolve_inactivity_timeout, resolve_max_run_duration
from products.tasks.backend.temporal.metrics import StepTimer, sandbox_runtime_label
from products.tasks.backend.temporal.oauth import is_interactive_signals_run
@@ -96,6 +98,7 @@ class GetTaskProcessingContextInput:
create_pr: bool = True
resumed_sandbox_id: str | None = None
resumed_sandbox_backend: str | None = None
+ stream_generation: str | None = None
@dataclass(frozen=False)
@@ -124,6 +127,7 @@ class TaskProcessingContext:
pr_babysit_enabled: bool = False
context_layer_enabled: bool = False
state: dict | None = None
+ stream_generation: str | None = None
_branch: str | None = None
sandbox_environment_name: str | None = None
allowed_domains: list[str] | None = None
@@ -1725,6 +1729,8 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
pr_babysit_enabled=pr_babysit_enabled,
context_layer_enabled=context_layer_enabled,
state=state,
+ stream_generation=input.stream_generation
+ or get_task_run_stream_generation(run_id, run_uses_dedicated_stream(state)),
_branch=task_run.branch,
sandbox_environment_name=sandbox_environment_name,
allowed_domains=allowed_domains,
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 379e72686d2c..27483aeea995 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
@@ -3,7 +3,6 @@ from __future__ import annotations
import json
import time
import asyncio
-from dataclasses import dataclass
from typing import Any
from django.conf import settings
@@ -17,6 +16,7 @@ from asgiref.sync import sync_to_async
from temporalio import activity
from temporalio.exceptions import ApplicationError
+from posthog.dataclasses import frozen
from posthog.temporal.common.utils import close_db_connections
from products.slack_app.backend.facade.api import agent_plan_steps, phase_for_tool_call, tool_call_from_acp_update
@@ -40,7 +40,12 @@ from products.tasks.backend.logic.services.process_killed import (
)
from products.tasks.backend.logic.services.workflow_step_resume import resume_workflow_step_after_final_message
from products.tasks.backend.logic.stream.agent_events import is_agent_command_dispatched, is_agent_generation_event
-from products.tasks.backend.logic.stream.redis_stream import TaskRunRedisStream, get_task_run_stream_key
+from products.tasks.backend.logic.stream.redis_stream import (
+ TASK_RUN_STREAM_INITIAL_GENERATION,
+ TaskRunRedisStream,
+ TaskRunStreamGenerationMismatch,
+ get_task_run_stream_key,
+)
from products.tasks.backend.models import (
Task as TaskModel,
TaskRun as TaskRunModel,
@@ -125,7 +130,7 @@ class FinalMessageTracker:
self._current_turn_parts.clear()
-@dataclass
+@frozen
class RelaySandboxEventsInput:
run_id: str
task_id: str
@@ -138,6 +143,7 @@ class RelaySandboxEventsInput:
# to the parent to drive SlackAgentDesignRelayWorkflow children.
slack_thread_context: dict[str, Any] | None = None
is_agent_design_enabled: bool = False
+ stream_generation: str | None = None
@activity.defn
@@ -181,6 +187,7 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_stre
presence_gated=run_stream_presence_gated(task_run.state),
origin_product=origin_product,
thin_tail=run_stream_thin_tail(task_run.state),
+ expected_generation=input.stream_generation or TASK_RUN_STREAM_INITIAL_GENERATION,
)
await redis_stream.initialize()
@@ -240,13 +247,18 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_stre
is_agent_design_enabled=input.is_agent_design_enabled,
finalize_stream_on_exit=finalize_stream_on_exit,
)
+ except TaskRunStreamGenerationMismatch:
+ return False
except asyncio.CancelledError:
logger.info("relay_sandbox_events_cancelled", run_id=input.run_id)
# Cancellation is expected when the workflow finishes or is replaced.
# Do not emit an error sentinel: it makes clients treat a still-valid
# task run as unrecoverably disconnected.
if finalize_stream_on_exit:
- await redis_stream.mark_complete()
+ try:
+ await redis_stream.mark_complete()
+ except TaskRunStreamGenerationMismatch:
+ pass
raise
except RuntimeError as e:
# Interpreter-shutdown race: asyncio uses the default ThreadPoolExecutor
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index 4b045dfd107f..71355ca6e410 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -499,7 +499,9 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
task_run_session_token: str | None = None
if event_stream_ingest_enabled or task.runtime == Task.Runtime.PI:
try:
- run_token = create_sandbox_event_ingest_token(task_run, sandbox_id=sandbox_id)
+ run_token = create_sandbox_event_ingest_token(
+ task_run, sandbox_id=sandbox_id, stream_generation=ctx.stream_generation
+ )
except Exception as e:
raise SandboxExecutionError(
"Failed to create sandbox task run token",
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
index cf552bec6460..5549a94af4c8 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_cleanup_sandbox.py
@@ -293,7 +293,7 @@ def test_cleanup_sandbox_completes_stream_when_requested(mocker, test_task_run,
sandbox.execute.assert_not_called()
sandbox.destroy.assert_called_once_with()
- publish_complete.assert_called_once_with(run_id, False)
+ publish_complete.assert_called_once_with(run_id, False, expected_generation="initial")
test_task_run.refresh_from_db()
assert test_task_run.state == (
{"other": "preserved", **accounting_state}
@@ -352,7 +352,7 @@ def test_cleanup_sandbox_completes_stream_when_sandbox_is_already_gone(activity_
),
)
- publish_complete.assert_called_once_with(run_id, False)
+ publish_complete.assert_called_once_with(run_id, False, expected_generation="initial")
@pytest.mark.skipif(
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index 5168e3ed4b72..2774608104e5 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -309,6 +309,7 @@ class TestGetTaskProcessingContextActivity:
assert result.startup_requested_at == (
task_run.queued_at.isoformat() if resume else task_run.state["startup_requested_at"]
)
+ assert result.stream_generation is not None
assert result.team_id == test_task.team_id
assert result.github_integration_id == test_task.github_integration_id
assert result.repository == "posthog/posthog-js"
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 f0284afe1b9e..6aecd28caa82 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
@@ -5,6 +5,7 @@ import importlib
from collections.abc import Callable
from types import SimpleNamespace
from typing import cast
+from uuid import uuid4
import pytest
from unittest.mock import AsyncMock, MagicMock, call
@@ -485,33 +486,13 @@ class TestAgentActiveReactivation:
class TestRelaySandboxEventsCancellation:
- async def test_cancelled_relay_marks_stream_complete_without_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
- redis_stream = SimpleNamespace(
- initialize=AsyncMock(),
- mark_complete=AsyncMock(),
- mark_error=AsyncMock(),
- )
-
- class StubTaskRunRedisStream:
- def __init__(
- self,
- stream_key: str,
- use_dedicated: bool = False,
- *,
- presence_gated: bool = False,
- origin_product: str | None = None,
- thin_tail: bool = False,
- ) -> None:
- self.stream_key = stream_key
-
- async def initialize(self) -> None:
- await redis_stream.initialize()
-
- async def mark_complete(self) -> None:
- await redis_stream.mark_complete()
-
- async def mark_error(self, error: str) -> None:
- await redis_stream.mark_error(error)
+ @pytest.mark.parametrize("replaced", [False, True])
+ async def test_cancelled_relay_only_completes_its_own_stream(
+ self, monkeypatch: pytest.MonkeyPatch, replaced: bool
+ ) -> None:
+ stream_key = f"task-run-stream:test:{uuid4()}"
+ redis_stream = TaskRunRedisStream(stream_key)
+ await redis_stream._redis_client.set(f"{stream_key}:generation", "original")
class StubTaskRunQuerySet:
def select_related(self, *_args: str) -> "StubTaskRunQuerySet":
@@ -523,9 +504,15 @@ class TestRelaySandboxEventsCancellation:
)
async def fake_relay_loop(**_kwargs: object) -> None:
+ if replaced:
+ await redis_stream._redis_client.set(f"{stream_key}:generation", "replacement")
raise asyncio.CancelledError
- monkeypatch.setattr(relay_sandbox_events_module, "TaskRunRedisStream", StubTaskRunRedisStream)
+ monkeypatch.setattr(
+ relay_sandbox_events_module,
+ "TaskRunRedisStream",
+ lambda _key, use_dedicated=False, **kwargs: TaskRunRedisStream(stream_key, use_dedicated, **kwargs),
+ )
monkeypatch.setattr(
relay_sandbox_events_module,
"TaskRunModel",
@@ -535,20 +522,26 @@ class TestRelaySandboxEventsCancellation:
monkeypatch.setattr(relay_sandbox_events_module, "validate_sandbox_url", lambda _url: None)
monkeypatch.setattr(relay_sandbox_events_module, "_relay_loop", fake_relay_loop)
- with pytest.raises(asyncio.CancelledError):
- 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",
+ try:
+ with pytest.raises(asyncio.CancelledError):
+ 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",
+ stream_generation="original",
+ )
)
- )
- redis_stream.mark_complete.assert_awaited_once()
- redis_stream.mark_error.assert_not_awaited()
+ events = await redis_stream._redis_client.xrange(stream_key)
+ assert [json.loads(data[b"data"]) for _, data in events] == (
+ [] if replaced else [{"type": "STREAM_STATUS", "status": "complete"}]
+ )
+ finally:
+ await redis_stream.delete_stream()
class TestRelaySandboxEventsPresenceGating:
@@ -578,6 +571,7 @@ class TestRelaySandboxEventsPresenceGating:
presence_gated: bool = False,
origin_product: str | None = None,
thin_tail: bool = False,
+ expected_generation: str | None = None,
) -> None:
constructed.append((presence_gated, thin_tail))
@@ -647,6 +641,7 @@ class TestRelaySandboxEventsMissingActor:
presence_gated: bool = False,
origin_product: str | None = None,
thin_tail: bool = False,
+ expected_generation: str | None = None,
) -> None:
self.stream_key = stream_key
@@ -1520,6 +1515,7 @@ class TestRelaySandboxEventsErrorHandling:
presence_gated: bool = False,
origin_product: str | None = None,
thin_tail: bool = False,
+ expected_generation: str | None = None,
) -> None:
self.stream_key = stream_key
@@ -1597,6 +1593,7 @@ class TestRelaySandboxEventsWorkflowOptions:
create_pr=True,
state={},
_branch="feature-branch",
+ stream_generation="replacement",
)
execute_activity_mock = AsyncMock()
execute_activity_mock.return_value = True
@@ -1612,6 +1609,7 @@ class TestRelaySandboxEventsWorkflowOptions:
assert execute_activity_mock.await_args is not None
args, kwargs = execute_activity_mock.await_args
assert args[0] is relay_sandbox_events_module.relay_sandbox_events_deferred_completion
+ assert args[1].stream_generation == "replacement"
assert kwargs["start_to_close_timeout"] == RELAY_SANDBOX_EVENTS_START_TO_CLOSE_TIMEOUT
assert workflow._sandbox_gone is True
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index 522c845ece28..34320302c33a 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -1187,7 +1187,10 @@ async def test_start_agent_server_uses_captured_sandbox_event_ingest_flag(
assert result.shadow_launched is True
shadow_result_reader.assert_not_called()
create_event_ingest_token.assert_called_once()
- assert create_event_ingest_token.call_args.kwargs == {"sandbox_id": "sandbox-id"}
+ assert create_event_ingest_token.call_args.kwargs == {
+ "sandbox_id": "sandbox-id",
+ "stream_generation": context.stream_generation,
+ }
task_queryset.get.assert_called_once_with(id="task-id")
get_user_mcp_configs.assert_called_once_with(
token="oauth-token",
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index 192eaa7753d5..6a14657ec8bd 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -2416,15 +2416,15 @@ class TestProcessTaskWorkflowUnit:
update_task_run_status_mock = AsyncMock()
track_workflow_event_mock = AsyncMock()
post_slack_update_mock = AsyncMock()
- complete_run_stream_mock = AsyncMock()
+ execute_activity = AsyncMock()
monkeypatch.setattr(workflow, "_get_task_processing_context", get_task_processing_context_mock)
monkeypatch.setattr(workflow, "_update_task_run_status", update_task_run_status_mock)
monkeypatch.setattr(workflow, "_track_workflow_event", track_workflow_event_mock)
monkeypatch.setattr(workflow, "_post_slack_update", post_slack_update_mock)
- monkeypatch.setattr(workflow, "_complete_run_stream", complete_run_stream_mock)
+ monkeypatch.setattr(process_task_workflow_module.workflow, "execute_activity", execute_activity)
- result = await workflow.run(ProcessTaskInput(run_id="run-id"))
+ result = await workflow.run(ProcessTaskInput(run_id="run-id", stream_generation="resumed-generation"))
assert result.success is False
assert result.error == "database connection closed"
@@ -2437,7 +2437,9 @@ class TestProcessTaskWorkflowUnit:
)
track_workflow_event_mock.assert_not_awaited()
post_slack_update_mock.assert_not_awaited()
- complete_run_stream_mock.assert_awaited_once_with("run-id")
+ assert execute_activity.call_args.args[1] == CompleteRunStreamInput(
+ run_id="run-id", stream_generation="resumed-generation"
+ )
async def test_run_persists_activity_failure_cause_not_the_wrapper(self, monkeypatch):
workflow = ProcessTaskWorkflow()
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 842fa1a1ba60..f2e2553cbcf5 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -201,6 +201,7 @@ class ResumedSandboxState:
connect_token: Optional[str]
ci_repetitions: int
jwt_kid: Optional[str] = None
+ stream_generation: str | None = None
pr_fingerprint: Optional[str]
pr_progress_emitted: bool
first_user_message_received: bool
@@ -262,7 +263,7 @@ class SandboxRotation:
reason: str = "none"
-@dataclass
+@dataclass(frozen=False)
class ProcessTaskInput:
run_id: str
create_pr: bool = True
@@ -272,6 +273,7 @@ class ProcessTaskInput:
initial_message: Optional["PendingFollowup"] = None
# Set only on a continue_as_new continuation, to skip provisioning and re-attach.
resumed_sandbox: Optional[ResumedSandboxState] = None
+ stream_generation: str | None = None
@dataclass
@@ -544,6 +546,7 @@ def _progress_emit_nonblocking() -> bool:
class ProcessTaskWorkflow(PostHogWorkflow):
def __init__(self) -> None:
self._context: Optional[TaskProcessingContext] = None
+ self._stream_generation: str | None = None
self._slack_thread_context: Optional[dict[str, Any]] = None
self._opening_person_message: Optional[str] = None
self._posthog_mcp_scopes: PosthogMcpScopes = "read_only"
@@ -1319,6 +1322,9 @@ class ProcessTaskWorkflow(PostHogWorkflow):
# Handing the live sandbox to the next execution — the finally must not tear it down.
continuing_as_new = False
run_id = input.run_id
+ self._stream_generation = (
+ input.resumed_sandbox.stream_generation if input.resumed_sandbox else input.stream_generation
+ )
self._sandbox_id_for_cleanup = None
self._slack_thread_context = input.slack_thread_context
# Taken off the context, so the mention rides in the first turn's relay only, not in every
@@ -1336,6 +1342,8 @@ class ProcessTaskWorkflow(PostHogWorkflow):
)
try:
self._context = await self._get_task_processing_context(input)
+ if self._stream_generation is not None:
+ self._context.stream_generation = self._stream_generation
if self._startup_worker_started_at is not None:
self._startup_context_loaded_at = workflow.now()
self._posthog_mcp_scopes = input.posthog_mcp_scopes
@@ -2070,6 +2078,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_url=self._sandbox_url or "",
connect_token=self._sandbox_connect_token,
jwt_kid=self._sandbox_jwt_kid,
+ stream_generation=self.context.stream_generation,
ci_repetitions=self._ci_repetitions,
ci_idle_skips=self._ci_idle_skips,
pr_fingerprint=self._pr_fingerprint,
@@ -2166,6 +2175,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
create_pr=input.create_pr,
resumed_sandbox_id=input.resumed_sandbox.sandbox_id if input.resumed_sandbox else None,
resumed_sandbox_backend=input.resumed_sandbox.sandbox_backend if input.resumed_sandbox else None,
+ stream_generation=self._stream_generation,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
@@ -2509,6 +2519,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_id=sandbox_id,
run_id=context.run_id if context else None,
complete_stream_on_cleanup=bool(context and complete_stream),
+ stream_generation=context.stream_generation if context else self._stream_generation,
)
try:
await workflow.execute_activity(
@@ -2525,7 +2536,10 @@ class ProcessTaskWorkflow(PostHogWorkflow):
async def _complete_run_stream(self, run_id: str) -> None:
await workflow.execute_activity(
complete_run_stream,
- CompleteRunStreamInput(run_id=run_id),
+ CompleteRunStreamInput(
+ run_id=run_id,
+ stream_generation=self._context.stream_generation if self._context else self._stream_generation,
+ ),
start_to_close_timeout=timedelta(seconds=30),
retry_policy=RetryPolicy(maximum_attempts=3),
)
@@ -3423,6 +3437,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
sandbox_id=sandbox_id,
slack_thread_context=self._slack_thread_context,
is_agent_design_enabled=self._is_agent_design_enabled,
+ stream_generation=self.context.stream_generation,
)
relay_activity = (
relay_sandbox_events_deferred_completion if _defer_run_stream_completion() else relay_sandbox_events
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index 324b7ce8863f..6d87d8f6f05e 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -87,8 +87,11 @@ from products.tasks.backend.logic.services.workflow_dispatch import materialize_
from products.tasks.backend.logic.stream.redis_stream import (
TaskRunRedisStream,
TaskRunStreamEntryOrKeepalive,
+ get_task_run_stream_completed_key,
+ get_task_run_stream_generation,
get_task_run_stream_key,
get_task_run_stream_watched_key,
+ reset_task_run_stream,
)
from products.tasks.backend.models import (
TASK_OWNERSHIP_VERSION_STATE_KEY,
@@ -116,7 +119,7 @@ from products.tasks.backend.presentation.serializers import (
TaskSerializer,
)
from products.tasks.backend.presentation.views import api as views_api
-from products.tasks.backend.redis import get_tasks_cache
+from products.tasks.backend.redis import get_tasks_cache, get_tasks_stream_redis_sync
from products.tasks.backend.temporal.process_task.utils import get_cached_github_user_token
from ee.billing.quota_limiting import QuotaResource
@@ -11450,7 +11453,8 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
extra_state={"pending_dispatch": {"user_id": self.user.id, "posthog_mcp_scopes": "read_only"}},
)
- def complete_stream(run_id: str, use_dedicated: bool) -> bool:
+ def complete_stream(run_id: str, use_dedicated: bool, *, expected_generation: str) -> bool:
+ assert expected_generation == "initial"
self.assertEqual(len(connection.atomic_blocks), transaction_depth)
cancelled_run = TaskRun.objects.get(id=run_id)
assert cancelled_run.status == TaskRun.Status.CANCELLED
@@ -11550,16 +11554,11 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
)
sandbox = MagicMock()
sandbox.stop_agent_server.return_value.exit_code = 0
+ assert reset_task_run_stream(str(run.id))
- with (
- patch(
- "products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.get_sandbox_class_for_sandbox_id",
- **{"return_value.get_by_id.return_value": sandbox},
- ),
- patch(
- "products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete",
- return_value=True,
- ) as publish_complete,
+ with patch(
+ "products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.get_sandbox_class_for_sandbox_id",
+ **{"return_value.get_by_id.return_value": sandbox},
):
response = self.client.post(self._cancel_url(task, run), {}, format="json")
@@ -11573,7 +11572,13 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
call.destroy(),
],
)
- publish_complete.assert_called_once_with(str(run.id), False)
+ redis = get_tasks_stream_redis_sync()
+ stream_key = get_task_run_stream_key(str(run.id))
+ assert redis.exists(get_task_run_stream_completed_key(stream_key))
+ assert json.loads(redis.xrevrange(stream_key, count=1)[0][1][b"data"]) == {
+ "type": "STREAM_STATUS",
+ "status": "complete",
+ }
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.CANCELLED)
self.assertIsNotNone(run.completed_at)
@@ -11615,27 +11620,43 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.IN_PROGRESS)
+ @parameterized.expand([False, True])
+ @override_settings(TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED=True)
@patch("products.tasks.backend.facade.api.create_sandbox_connection_token", return_value="token")
@patch("products.tasks.backend.facade.api.send_cancel")
@patch("products.tasks.backend.facade.cancellation._signal_complete_task", return_value="workflow_gone")
- def test_cancel_retry_repairs_stream_after_workflow_gone(self, _mock_signal, _mock_send_cancel, _mock_token):
+ def test_cancel_retry_repairs_stream_after_workflow_gone(
+ self, resume_before_retry, _mock_signal, _mock_send_cancel, _mock_token
+ ):
task = self.create_task()
run = self._create_run(task, state={"sandbox_id": "sandbox-123"})
sandbox = MagicMock()
sandbox.stop_agent_server.return_value.exit_code = 0
+ assert reset_task_run_stream(str(run.id))
+ generation = get_task_run_stream_generation(str(run.id))
+ TaskRun.update_state_atomic(run.id, updates={"stream_generation": generation})
with (
+ patch(
+ "products.tasks.backend.facade.cancellation.get_task_run_stream_generation",
+ side_effect=ConnectionError("Redis unavailable"),
+ ),
patch(
"products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.get_sandbox_class_for_sandbox_id",
**{"return_value.get_by_id.return_value": sandbox},
),
patch(
"products.tasks.backend.temporal.process_task.activities.cleanup_sandbox.publish_task_run_stream_complete",
- side_effect=[False, True],
- ) as publish_complete,
+ return_value=False,
+ ),
):
first_response = self.client.post(self._cancel_url(task, run), {}, format="json")
- second_response = self.client.post(self._cancel_url(task, run), {}, format="json")
+ run.refresh_from_db()
+ assert run.state["cancel_fallback_stream_generation"] == generation
+ assert run.status == TaskRun.Status.CANCELLED
+ if resume_before_retry:
+ assert reset_task_run_stream(str(run.id))
+ second_response = self.client.post(self._cancel_url(task, run), {}, format="json")
self.assertEqual(first_response.status_code, status.HTTP_503_SERVICE_UNAVAILABLE)
self.assertEqual(second_response.status_code, status.HTTP_200_OK)
@@ -11648,7 +11669,8 @@ class TestTaskRunCancelAPI(BaseTaskAPITest):
call.destroy(),
],
)
- self.assertEqual(publish_complete.call_count, 2)
+ completed_key = get_task_run_stream_completed_key(get_task_run_stream_key(str(run.id)))
+ self.assertEqual(bool(get_tasks_stream_redis_sync().exists(completed_key)), not resume_before_retry)
run.refresh_from_db()
self.assertEqual(run.status, TaskRun.Status.CANCELLED)
self.assertFalse(run.state["cancel_fallback_cleanup_complete"])
diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.py
index 4b9d4a0a2150..d3a050604ad6 100644
--- a/products/tasks/backend/tests/test_event_ingest.py
+++ b/products/tasks/backend/tests/test_event_ingest.py
@@ -8,9 +8,11 @@ from uuid import NAMESPACE_URL, uuid5
from unittest.mock import call, patch
+from django.conf import settings
from django.db import OperationalError
from django.test import SimpleTestCase, TestCase, override_settings
+import jwt
from asgiref.sync import async_to_sync
from parameterized import parameterized
from prometheus_client import REGISTRY
@@ -40,8 +42,10 @@ from products.tasks.backend.logic.stream.redis_stream import (
get_task_run_stream_completed_key,
get_task_run_stream_key,
get_task_run_stream_sequence_key,
+ reset_task_run_stream,
)
from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.redis import get_tasks_stream_redis_sync
from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
@@ -947,6 +951,61 @@ class TestTaskRunEventIngest(TestCase):
self.assertEqual(body["last_accepted_seq"], 1)
self.assertEqual(self._read_notification_methods(), ["first"])
+ @parameterized.expand(
+ [
+ ("event", {"seq": 1, "event": {"type": "notification", "notification": {"method": "late"}}}, False, True),
+ ("completion", {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 0}, False, True),
+ (
+ "legacy_event",
+ {"seq": 1, "event": {"type": "notification", "notification": {"method": "late"}}},
+ True,
+ True,
+ ),
+ ("legacy_completion", {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 0}, True, True),
+ (
+ "rollout_event",
+ {"seq": 1, "event": {"type": "notification", "notification": {"method": "late"}}},
+ True,
+ False,
+ ),
+ ("rollout_completion", {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 0}, True, False),
+ ("dedicated", {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 0}, False, True, True),
+ ]
+ )
+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
+ def test_resumed_stream_rejects_previous_ingest_token(
+ self, _name: str, line: dict, legacy: bool, rotation_enabled: bool, dedicated: bool = False
+ ) -> None:
+ if dedicated:
+ self.task_run.state["use_dedicated_stream"] = True
+ self.task_run.save(update_fields=["state"])
+ self.enterContext(override_settings(TASKS_REDIS_URL=settings.REDIS_URL.rsplit("/", 1)[0] + "/14"))
+ self.addCleanup(
+ get_tasks_stream_redis_sync(True).delete,
+ get_task_run_stream_key(str(self.task_run.id)),
+ get_task_run_stream_key(str(self.task_run.id)) + ":generation",
+ get_task_run_stream_completed_key(get_task_run_stream_key(str(self.task_run.id))),
+ )
+ token = self._create_token()
+ if legacy:
+ claims = jwt.decode(token, options={"verify_signature": False})
+ del claims["stream_generation"]
+ token = jwt.encode(claims, TEST_RSA_PRIVATE_KEY, algorithm="RS256")
+ status, _ = self._call_ingest(token, [line])
+ self.assertEqual(status, 200)
+ with override_settings(TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED=rotation_enabled):
+ reset_task_run_stream(str(self.task_run.id), use_dedicated=dedicated)
+
+ status, body = self._call_ingest(token, [line])
+
+ self.assertEqual(status, 403 if rotation_enabled else 200)
+ if rotation_enabled:
+ self.assertEqual(body["code"], "stream_generation_mismatch")
+ self.assertNotIn("last_accepted_seq", body)
+ self.assertEqual(self._read_stream_events(), [])
+ status, _ = self._call_ingest(self._create_token(), [line])
+ self.assertEqual(status, 200)
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
def test_completed_stream_rejects_late_sequenced_events(self) -> None:
token = self._create_token()
@@ -1093,8 +1152,8 @@ class TestTaskRunEventIngest(TestCase):
self.assertTrue(real_exists)
with patch(
- "products.tasks.backend.logic.stream.event_ingest._task_run_exists_sync",
- side_effect=[OperationalError("server closed the connection unexpectedly"), True],
+ "products.tasks.backend.logic.stream.event_ingest._task_run_state_sync",
+ side_effect=[OperationalError("server closed the connection unexpectedly"), {}],
) as exists_sync:
status, body = self._call_ingest(
token,
diff --git a/products/tasks/backend/tests/test_temporal_client.py b/products/tasks/backend/tests/test_temporal_client.py
index 88209b5f541f..0a9e6c42d7e2 100644
--- a/products/tasks/backend/tests/test_temporal_client.py
+++ b/products/tasks/backend/tests/test_temporal_client.py
@@ -11,6 +11,7 @@ from temporalio.exceptions import WorkflowAlreadyStartedError
from posthog.models import Organization, Team
from posthog.models.user import User
+from products.tasks.backend.logic.stream.redis_stream import get_task_run_stream_generation, reset_task_run_stream
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.client import (
execute_task_processing_workflow,
@@ -338,8 +339,11 @@ class TestExecuteTaskProcessingWorkflow(TestCase):
self.assertEqual(run.state["sandbox_event_ingest_enabled"], True)
self.assertEqual(run.state["agent_otel_telemetry_enabled"], True)
+ @override_settings(TASK_RUN_STREAM_GENERATION_ROTATION_ENABLED=True)
def test_captures_sandbox_event_ingest_flag_before_resuming_workflow(self) -> None:
run = self._create_run()
+ reset_task_run_stream(str(run.id))
+ generation = get_task_run_stream_generation(str(run.id))
client = Mock()
client.start_workflow = AsyncMock()
@@ -352,6 +356,9 @@ class TestExecuteTaskProcessingWorkflow(TestCase):
run.refresh_from_db()
self.assertEqual(run.state["sandbox_event_ingest_enabled"], True)
+ self.assertEqual(run.state["stream_generation"], generation)
+ self.assertEqual(client.start_workflow.call_args.args[1].stream_generation, generation)
+
@parameterized.expand([("sync",), ("async",)])
def test_captures_sandbox_event_ingest_flag_without_clobbering_concurrent_state(self, executor: str) -> None:
run = self._create_run()
diff --git a/services/agent-proxy/src/hono/ingest-handler.ts b/services/agent-proxy/src/hono/ingest-handler.ts
index fcb058e4e8a6..9b3fadb4914e 100644
--- a/services/agent-proxy/src/hono/ingest-handler.ts
+++ b/services/agent-proxy/src/hono/ingest-handler.ts
@@ -23,6 +23,7 @@ import {
MAX_REQUEST_BYTES,
MAX_EVENTS_PER_REQUEST,
STREAM_COMPLETE_CONTROL_TYPE,
+ STREAM_INITIAL_GENERATION,
} from '../lib/constants.js'
import { validateSandboxEventIngestToken } from '../lib/jwt.js'
import { logger } from '../lib/logging.js'
@@ -38,6 +39,7 @@ import {
EventIngestPayloadTooLarge,
TaskRunStreamSequenceGap,
TaskRunStreamAlreadyCompleted,
+ TaskRunStreamGenerationMismatch,
TaskRunStreamCompletionSequenceMismatch,
type DisconnectClassification,
type IngestEventLine,
@@ -112,6 +114,7 @@ export async function handleIngest(
const redisStream = new TaskRunRedisStream(streamKey, redis, {
presenceGated: claims.presenceGated,
thinTail: claims.thinTail,
+ expectedGeneration: claims.streamGeneration ?? STREAM_INITIAL_GENERATION,
})
const bodyTiming: IngestBodyTiming = {
@@ -153,6 +156,9 @@ export async function handleIngest(
if (err instanceof EventIngestPayloadTooLarge) {
return c.json({ error: err.message, last_accepted_seq: err.lastAcceptedSeq }, 413)
}
+ if (err instanceof TaskRunStreamGenerationMismatch) {
+ return c.json({ error: err.message, code: 'stream_generation_mismatch' }, 403)
+ }
if (err instanceof TaskRunStreamSequenceGap) {
return c.json({ error: err.message, last_accepted_seq: err.lastAcceptedSeq }, 409)
}
diff --git a/services/agent-proxy/src/lib/constants.ts b/services/agent-proxy/src/lib/constants.ts
index 4bcd705abd9b..d7f9382056f3 100644
--- a/services/agent-proxy/src/lib/constants.ts
+++ b/services/agent-proxy/src/lib/constants.ts
@@ -51,6 +51,7 @@ export const HEARTBEAT_THROTTLE_SECONDS = 30
// Redis key prefix (byte-identical to TASK_RUN_STREAM_PREFIX in Python)
export const STREAM_PREFIX = 'task-run-stream:'
+export const STREAM_INITIAL_GENERATION = 'initial'
// Redis key builder functions (byte-identical to Python get_task_run_stream_*_key)
diff --git a/services/agent-proxy/src/lib/jwt.ts b/services/agent-proxy/src/lib/jwt.ts
index 559f78c10d69..4c1e51aacc55 100644
--- a/services/agent-proxy/src/lib/jwt.ts
+++ b/services/agent-proxy/src/lib/jwt.ts
@@ -156,10 +156,15 @@ export async function validateSandboxEventIngestToken(
): Promise<SandboxEventIngestTokenPayload> {
const payload = await verifyWithKeys(token, publicKeys, SANDBOX_EVENT_INGEST_AUDIENCE)
const claims = payload as Record<string, unknown>
+ const streamGeneration = claims['stream_generation']
+ if (streamGeneration !== undefined && (typeof streamGeneration !== 'string' || !streamGeneration)) {
+ throw new Error('Token has invalid claim: stream_generation must be a nonempty string')
+ }
return {
...assertStreamClaims(claims),
presenceGated: assertPresenceGatedClaim(claims),
thinTail: assertThinTailClaim(claims),
originProduct: assertOriginProductClaim(claims),
+ ...(streamGeneration === undefined ? {} : { streamGeneration }),
}
}
diff --git a/services/agent-proxy/src/lib/redis-stream.ts b/services/agent-proxy/src/lib/redis-stream.ts
index 9d708195a761..98f2463b54a1 100644
--- a/services/agent-proxy/src/lib/redis-stream.ts
+++ b/services/agent-proxy/src/lib/redis-stream.ts
@@ -16,6 +16,7 @@ import {
STREAM_MAX_LENGTH,
STREAM_THIN_MAX_LENGTH,
STREAM_PREFIX,
+ STREAM_INITIAL_GENERATION,
STREAM_TTL_SECONDS,
STREAM_WATCHED_TTL_SECONDS,
WAIT_DELAY_INCREMENT_MS,
@@ -23,12 +24,14 @@ import {
WAIT_MAX_DELAY_MS,
WAIT_TIMEOUT_MS,
} from './constants.js'
+import { logger } from './logging.js'
import type { ReadStreamEntriesOptions, ResumeGap, StreamEntryOrKeepalive, TaskRunStreamWriteResult } from './types.js'
import {
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
TaskRunStreamCursorTrimmedError,
TaskRunStreamError,
+ TaskRunStreamGenerationMismatch,
TaskRunStreamSequenceGap,
WRITE_RESULT_DUPLICATE,
WRITE_RESULT_SKIPPED,
@@ -130,6 +133,50 @@ function sleep(ms: number): Promise<void> {
// unsafe in Node. 100 iterations is far beyond what real contention
// requires — if a slot is genuinely that contested something is wrong.
const MAX_WATCH_RETRIES = 100
+interface RedisTransactionSlot {
+ client: Redis
+ tail: Promise<void>
+ pending: number
+}
+
+const redisTransactionPools = new WeakMap<Redis, RedisTransactionSlot[]>()
+
+async function withExclusiveRedisTransaction<T>(redis: Redis, operation: (client: Redis) => Promise<T>): Promise<T> {
+ let pool = redisTransactionPools.get(redis)
+ if (!pool) {
+ pool = [{ client: redis, tail: Promise.resolve(), pending: 0 }]
+ redisTransactionPools.set(redis, pool)
+ }
+ let slot = pool.reduce((least, candidate) => (candidate.pending < least.pending ? candidate : least))
+ if (slot.pending > 0 && pool.length < 8) {
+ const client = redis.duplicate({ lazyConnect: true })
+ client.on('error', (error: Error) => logger.error('redis:transaction_error', { error: error.message }))
+ redis.once('end', () => client.disconnect())
+ slot = { client, tail: Promise.resolve(), pending: 0 }
+ pool.push(slot)
+ }
+ const leased = slot
+ leased.pending++
+ const transaction = leased.tail.then(async () => {
+ try {
+ if (leased.client.status === 'wait') {
+ await leased.client.connect()
+ }
+ return await operation(leased.client)
+ } finally {
+ try {
+ await leased.client.unwatch()
+ } finally {
+ leased.pending--
+ }
+ }
+ })
+ leased.tail = transaction.then(
+ () => undefined,
+ () => undefined
+ )
+ return transaction
+}
export class TaskRunRedisStream {
private readonly streamKey: string
@@ -140,6 +187,7 @@ export class TaskRunRedisStream {
private readonly maxLength: number
private readonly presenceGated: boolean
private readonly thinTail: boolean
+ private readonly expectedGeneration: string | undefined
constructor(
streamKey: string,
@@ -149,6 +197,7 @@ export class TaskRunRedisStream {
maxLength?: number
presenceGated?: boolean
thinTail?: boolean
+ expectedGeneration?: string
}
) {
this.streamKey = streamKey
@@ -160,6 +209,7 @@ export class TaskRunRedisStream {
this.maxLength = opts?.maxLength ?? STREAM_MAX_LENGTH
this.presenceGated = opts?.presenceGated ?? false
this.thinTail = opts?.thinTail ?? false
+ this.expectedGeneration = opts?.expectedGeneration
}
private maxlenForEvent(event: Record<string, unknown>): number {
@@ -490,39 +540,51 @@ export class TaskRunRedisStream {
// completed key present -> TaskRunStreamAlreadyCompleted
// presence-gated with no attached reader -> accepted, no stream ID
async writeEventWithSequence(event: Record<string, unknown>, sequence: number): Promise<TaskRunStreamWriteResult> {
+ return withExclusiveRedisTransaction(this.redis, (client) =>
+ this.writeEventWithSequenceTransaction(client, event, sequence)
+ )
+ }
+
+ private async writeEventWithSequenceTransaction(
+ client: Redis,
+ event: Record<string, unknown>,
+ sequence: number
+ ): Promise<TaskRunStreamWriteResult> {
const sequenceKey = getSequenceKey(this.streamKey)
const completedKey = getCompletedKey(this.streamKey)
const watchedKey = getWatchedKey(this.streamKey)
+ const generationKey = `${this.streamKey}:generation`
for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
if (this.presenceGated) {
- await this.redis.watch(sequenceKey, completedKey, watchedKey)
+ await client.watch(sequenceKey, completedKey, watchedKey, generationKey)
} else {
- await this.redis.watch(sequenceKey, completedKey)
+ await client.watch(sequenceKey, completedKey, generationKey)
}
+ await this.checkGeneration(client, generationKey)
- const lastSeqRaw = await this.redis.get(sequenceKey)
+ const lastSeqRaw = await client.get(sequenceKey)
const lastSequence = normalizeRedisInt(lastSeqRaw)
- const completedExists = (await this.redis.exists(completedKey)) > 0
+ const completedExists = (await client.exists(completedKey)) > 0
if (completedExists) {
- await this.redis.unwatch()
+ await client.unwatch()
throw new TaskRunStreamAlreadyCompleted(lastSequence)
}
if (sequence <= lastSequence) {
- await this.redis.unwatch()
+ await client.unwatch()
return WRITE_RESULT_DUPLICATE
}
if (sequence !== lastSequence + 1) {
- await this.redis.unwatch()
+ await client.unwatch()
throw new TaskRunStreamSequenceGap(lastSequence + 1, sequence, lastSequence)
}
- const mirror = !this.presenceGated || (await this.redis.exists(watchedKey)) > 0
+ const mirror = !this.presenceGated || (await client.exists(watchedKey)) > 0
- const pipeline = this.redis.multi()
+ const pipeline = client.multi()
if (mirror) {
pipeline.xadd(
this.streamKey,
@@ -536,6 +598,7 @@ export class TaskRunRedisStream {
pipeline.expire(this.streamKey, this.timeout)
}
pipeline.set(sequenceKey, String(sequence), 'EX', this.sequenceTimeout)
+ pipeline.expire(generationKey, this.sequenceTimeout)
const results = await pipeline.exec()
if (results === null) {
@@ -560,23 +623,30 @@ export class TaskRunRedisStream {
// WATCH/MULTI on completed_key. Idempotent: returns if already completed.
async markComplete(): Promise<void> {
+ return withExclusiveRedisTransaction(this.redis, (client) => this.markCompleteTransaction(client))
+ }
+
+ private async markCompleteTransaction(client: Redis): Promise<void> {
const completedKey = getCompletedKey(this.streamKey)
+ const generationKey = `${this.streamKey}:generation`
const raw = JSON.stringify({ type: 'STREAM_STATUS', status: 'complete' })
for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
- await this.redis.watch(completedKey)
+ await client.watch(completedKey, generationKey)
+ await this.checkGeneration(client, generationKey)
- const completedExists = (await this.redis.exists(completedKey)) > 0
+ const completedExists = (await client.exists(completedKey)) > 0
if (completedExists) {
- await this.redis.unwatch()
- await this.redis.expire(this.streamKey, this.completedTimeout)
+ await client.unwatch()
+ await client.expire(this.streamKey, this.completedTimeout)
return
}
- const pipeline = this.redis.multi()
+ const pipeline = client.multi()
pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
pipeline.expire(this.streamKey, this.completedTimeout)
pipeline.set(completedKey, '1', 'EX', this.sequenceTimeout)
+ pipeline.expire(generationKey, this.sequenceTimeout)
const results = await pipeline.exec()
if (results === null) {
@@ -589,35 +659,53 @@ export class TaskRunRedisStream {
throw new TaskRunStreamError('markComplete: too many WATCH conflicts')
}
+ private async checkGeneration(client: Redis, generationKey: string): Promise<void> {
+ if (
+ this.expectedGeneration !== undefined &&
+ ((await client.get(generationKey)) ?? STREAM_INITIAL_GENERATION) !== this.expectedGeneration
+ ) {
+ await client.unwatch()
+ throw new TaskRunStreamGenerationMismatch('Task run stream generation has changed')
+ }
+ }
+
// WATCH/MULTI on sequence_key + completed_key.
// Throws TaskRunStreamCompletionSequenceMismatch if last_seq != finalSequence.
// EXPIRE sequence_key only if it existed before (lastSeqRaw !== null).
async markCompleteAfterSequence(finalSequence: number): Promise<void> {
+ return withExclusiveRedisTransaction(this.redis, (client) =>
+ this.markCompleteAfterSequenceTransaction(client, finalSequence)
+ )
+ }
+
+ private async markCompleteAfterSequenceTransaction(client: Redis, finalSequence: number): Promise<void> {
const sequenceKey = getSequenceKey(this.streamKey)
const completedKey = getCompletedKey(this.streamKey)
+ const generationKey = `${this.streamKey}:generation`
const raw = JSON.stringify({ type: 'STREAM_STATUS', status: 'complete' })
for (let attempt = 0; attempt < MAX_WATCH_RETRIES; attempt++) {
- await this.redis.watch(sequenceKey, completedKey)
+ await client.watch(sequenceKey, completedKey, generationKey)
+ await this.checkGeneration(client, generationKey)
- const lastSeqRaw = await this.redis.get(sequenceKey)
+ const lastSeqRaw = await client.get(sequenceKey)
const lastSequence = normalizeRedisInt(lastSeqRaw)
- const completedExists = (await this.redis.exists(completedKey)) > 0
+ const completedExists = (await client.exists(completedKey)) > 0
if (completedExists) {
- await this.redis.unwatch()
- await this.redis.expire(this.streamKey, this.completedTimeout)
+ await client.unwatch()
+ await client.expire(this.streamKey, this.completedTimeout)
return
}
if (lastSequence !== finalSequence) {
- await this.redis.unwatch()
+ await client.unwatch()
throw new TaskRunStreamCompletionSequenceMismatch(finalSequence, lastSequence)
}
const seqKeyExisted = lastSeqRaw !== null
- const pipeline = this.redis.multi()
+ const pipeline = client.multi()
pipeline.xadd(this.streamKey, 'MAXLEN', '~', this.maxLength, '*', 'data', raw)
pipeline.expire(this.streamKey, this.completedTimeout)
// Only EXPIRE the sequence key if it existed before the transaction;
diff --git a/services/agent-proxy/src/lib/types.ts b/services/agent-proxy/src/lib/types.ts
index bd91b6ff1e3a..4da8409af7cb 100644
--- a/services/agent-proxy/src/lib/types.ts
+++ b/services/agent-proxy/src/lib/types.ts
@@ -17,6 +17,8 @@ export class TaskRunStreamError extends Error {
}
}
+export class TaskRunStreamGenerationMismatch extends Error {}
+
export class TaskRunStreamCursorTrimmedError extends Error {
constructor(public readonly cursor: string) {
super(`Stream cursor ${cursor} was trimmed`)
@@ -121,6 +123,7 @@ export interface SandboxEventIngestTokenPayload {
presenceGated: boolean
thinTail: boolean
originProduct: string
+ streamGeneration?: string
}
// ---------------------------------------------------------------------------
diff --git a/services/agent-proxy/tests/hono/ingest-handler.test.ts b/services/agent-proxy/tests/hono/ingest-handler.test.ts
index b53db05170c8..5daf00592305 100644
--- a/services/agent-proxy/tests/hono/ingest-handler.test.ts
+++ b/services/agent-proxy/tests/hono/ingest-handler.test.ts
@@ -419,6 +419,35 @@ describe('ingest-handler', () => {
mockValidate.mockResolvedValue(makeClaims())
})
+ it.each([
+ { line: { seq: 1, event: { type: 'notification', notification: { method: 'late' } } }, legacy: false },
+ { line: { type: '_posthog/stream_complete', final_seq: 0 }, legacy: false },
+ { line: { seq: 1, event: { type: 'notification', notification: { method: 'late' } } }, legacy: true },
+ { line: { type: '_posthog/stream_complete', final_seq: 0 }, legacy: true },
+ ])('rejects an old sender after the stream resumes: %j', async ({ line, legacy }) => {
+ mockValidate.mockResolvedValue({ ...makeClaims(), ...(legacy ? {} : { streamGeneration: 'initial' }) })
+ await fakeRedis.set(`${getStreamKey(RUN_ID)}:generation`, 'initial')
+ const initial = await handleIngest(
+ makeContext({ body: makeStringBody(JSON.stringify(line) + '\n') }),
+ fakeRedis as unknown as Redis,
+ makeConfig(),
+ []
+ )
+ expect(initial.status).toBe(200)
+ await redisStream.deleteStream()
+ await fakeRedis.set(`${getStreamKey(RUN_ID)}:generation`, 'replacement')
+ const response = await handleIngest(
+ makeContext({ body: makeStringBody(JSON.stringify(line) + '\n') }),
+ fakeRedis as unknown as Redis,
+ makeConfig(),
+ []
+ )
+ expect(response.status).toBe(403)
+ expect(await response.json()).not.toHaveProperty('last_accepted_seq')
+ expect(await redisStream.getLastSequence()).toBe(0)
+ expect(await redisStream.isComplete()).toBe(false)
+ })
+
// -----------------------------------------------------------------------
// Auth / routing guards
// -----------------------------------------------------------------------
diff --git a/services/agent-proxy/tests/lib/redis-stream.test.ts b/services/agent-proxy/tests/lib/redis-stream.test.ts
index 333e351715aa..0f95225955e0 100644
--- a/services/agent-proxy/tests/lib/redis-stream.test.ts
+++ b/services/agent-proxy/tests/lib/redis-stream.test.ts
@@ -9,7 +9,7 @@
// TaskRunRedisStream calls (XADD, XRANGE, XREVRANGE, XREAD, XLEN, GET, SET,
// EXISTS, EXPIRE, DEL, WATCH, UNWATCH, MULTI/EXEC).
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, vi } from 'vitest'
import { STREAM_COMPLETED_TTL_SECONDS, STREAM_WATCHED_TTL_SECONDS } from '@/lib/constants.js'
import {
@@ -28,6 +28,7 @@ import {
TaskRunStreamSequenceGap,
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
+ TaskRunStreamGenerationMismatch,
} from '@/lib/types.js'
// ---------------------------------------------------------------------------
@@ -53,6 +54,21 @@ class FakeRedis {
private _expireCallCount = 0
private _xaddMaxlens: number[] = []
+ duplicate(): FakeRedis {
+ const connection = Object.create(this) as FakeRedis
+ connection._watchedKeys = new Set()
+ connection._watchDirty = false
+ return connection
+ }
+
+ on(): this {
+ return this
+ }
+
+ once(): this {
+ return this
+ }
+
// Counters exposed for TTL/MAXLEN assertions
get xaddCallCount(): number {
return this._xaddCallCount
@@ -473,6 +489,43 @@ async function drainEntries(
// ---------------------------------------------------------------------------
describe('redis-stream', () => {
+ it.each([
+ { name: 'ingest', write: (stream: TaskRunRedisStream) => stream.writeEventWithSequence({ type: 'late' }, 1) },
+ { name: 'ingest completion', write: (stream: TaskRunRedisStream) => stream.markCompleteAfterSequence(0) },
+ { name: 'relay completion', write: (stream: TaskRunRedisStream) => stream.markComplete() },
+ ])('rejects a concurrent generation reset ($name)', async ({ write }) => {
+ const { redis, streamKey } = newStream()
+ const generationKey = `${streamKey}:generation`
+ await redis.set(generationKey, 'original')
+ const stream = new TaskRunRedisStream(streamKey, redis as unknown as import('ioredis').Redis, {
+ expectedGeneration: 'original',
+ })
+ const concurrentStream = new TaskRunRedisStream(streamKey, redis as unknown as import('ioredis').Redis, {
+ expectedGeneration: 'original',
+ })
+ const independentStream = new TaskRunRedisStream(
+ `${streamKey}:independent`,
+ redis as unknown as import('ioredis').Redis
+ )
+ let concurrentRequest: Promise<unknown> | undefined
+ const get = redis.get.bind(redis)
+ vi.spyOn(redis, 'get').mockImplementation(async (key) => {
+ const value = await get(key)
+ if (key === generationKey && value === 'original') {
+ await redis.set(generationKey, 'replacement')
+ redis._markKeyDirty(generationKey)
+ concurrentRequest = concurrentStream.markCompleteAfterSequence(0).catch((error: unknown) => error)
+ expect((await independentStream.writeEventWithSequence({ type: 'independent' }, 1)).accepted).toBe(true)
+ }
+ return value
+ })
+ await expect(write(stream)).rejects.toBeInstanceOf(TaskRunStreamGenerationMismatch)
+ expect(concurrentRequest).not.toBeUndefined()
+ expect(await concurrentRequest).toBeInstanceOf(TaskRunStreamGenerationMismatch)
+ expect(redis.getStreamEntries(streamKey)).toEqual([])
+ expect(await stream.getLastSequence()).toBe(0)
+ expect(await stream.isComplete()).toBe(false)
+ })
// -----------------------------------------------------------------------
// Key helpers
// -----------------------------------------------------------------------
diff --git a/services/agent-proxy/types.d.ts b/services/agent-proxy/types.d.ts
index 65c5e3000a9c..cc50904de84c 100644
--- a/services/agent-proxy/types.d.ts
+++ b/services/agent-proxy/types.d.ts
@@ -17,7 +17,8 @@ declare module 'ioredis' {
quit(): Promise<string>
// ioredis v4 disconnect() is synchronous and returns void (not a Promise).
disconnect(): void
- duplicate(): Redis
+ duplicate(options?: { lazyConnect?: boolean }): Redis
+ once(event: string, listener: (...args: any[]) => void): this
on(event: string, listener: (...args: any[]) => void): this
get(key: string): Promise<string | null>
set(key: string, value: string | number, ...args: any[]): Promise<any>