:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): add sandbox event ingest endpoint (#58133)
Alessandro Pogliaghi1ae13ee41b85
diff --git a/posthog/asgi.py b/posthog/asgi.pyindex 15f638ceaaeb..3196195f5748 100644--- a/posthog/asgi.py+++ b/posthog/asgi.py@@ -86,4 +86,16 @@ def self_capture_wrapper(func):return inner-application = lifetime_wrapper(self_capture_wrapper(get_asgi_application()))+def task_run_event_ingest_wrapper(func):+ async def inner(scope, receive, send):+ from products.tasks.backend.stream.event_ingest import handle_task_run_event_ingest++ if await handle_task_run_event_ingest(scope, receive, send):+ return++ return await func(scope, receive, send)++ return inner+++application = lifetime_wrapper(self_capture_wrapper(task_run_event_ingest_wrapper(get_asgi_application())))diff --git a/products/tasks/backend/services/connection_token.py b/products/tasks/backend/services/connection_token.pyindex ce4f5e458dac..61b795415a74 100644--- a/products/tasks/backend/services/connection_token.py+++ b/products/tasks/backend/services/connection_token.py@@ -1,5 +1,6 @@from __future__ import annotations+from dataclasses import dataclassfrom datetime import UTC, datetime, timedeltafrom functools import lru_cachefrom typing import TYPE_CHECKING@@ -10,11 +11,23 @@ import jwtfrom cryptography.hazmat.backends import default_backendfrom cryptography.hazmat.primitives import serialization+from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS+if TYPE_CHECKING:from products.tasks.backend.models import TaskRunSANDBOX_CONNECTION_AUDIENCE = "posthog:sandbox_connection"+SANDBOX_EVENT_INGEST_AUDIENCE = "posthog:sandbox_event_ingest"+SANDBOX_EVENT_INGEST_TOKEN_TTL_BUFFER = timedelta(hours=1)+SANDBOX_EVENT_INGEST_TOKEN_TTL = timedelta(seconds=SANDBOX_TTL_SECONDS) + SANDBOX_EVENT_INGEST_TOKEN_TTL_BUFFER+++@dataclass(frozen=True)+class SandboxEventIngestTokenPayload:+ run_id: str+ task_id: str+ team_id: intdef _normalize_pem_key(key: str) -> str:@@ -71,3 +84,46 @@ def create_sandbox_connection_token(task_run: TaskRun, user_id: int, distinct_id}return jwt.encode(payload, private_key, algorithm="RS256")+++def create_sandbox_event_ingest_token(task_run: TaskRun, ttl: timedelta = SANDBOX_EVENT_INGEST_TOKEN_TTL) -> str:+ """+ Create a run-scoped JWT token for sandbox-to-Django live event ingest.++ This token intentionally carries no user identity and grants one capability:+ appending ordered live events for this task run.+ """+ private_key = settings.SANDBOX_JWT_PRIVATE_KEY+ if not private_key:+ raise ValueError("SANDBOX_JWT_PRIVATE_KEY setting is required for sandbox event ingest tokens")++ private_key = _normalize_pem_key(private_key)+ now = datetime.now(tz=UTC)+ payload = {+ "run_id": str(task_run.id),+ "task_id": str(task_run.task_id),+ "team_id": task_run.team_id,+ "iat": now,+ "exp": now + ttl,+ "aud": SANDBOX_EVENT_INGEST_AUDIENCE,+ }++ return jwt.encode(payload, private_key, algorithm="RS256")+++def validate_sandbox_event_ingest_token(token: str) -> SandboxEventIngestTokenPayload:+ payload = jwt.decode(+ token,+ get_sandbox_jwt_public_key(),+ algorithms=["RS256"],+ audience=SANDBOX_EVENT_INGEST_AUDIENCE,+ )++ run_id = payload.get("run_id")+ task_id = payload.get("task_id")+ team_id = payload.get("team_id")++ 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")++ return SandboxEventIngestTokenPayload(run_id=run_id, task_id=task_id, team_id=team_id)diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.pyindex eab9162eccbf..6fb4c53b2b56 100644--- a/products/tasks/backend/services/sandbox.py+++ b/products/tasks/backend/services/sandbox.py@@ -25,6 +25,8 @@ from django.conf import settingsimport structlogfrom pydantic import BaseModel+from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS+if TYPE_CHECKING:from products.tasks.backend.temporal.process_task.utils import McpServerConfig@@ -61,12 +63,6 @@ class ExecutionStream(Protocol):def wait(self) -> ExecutionResult: ...-# Production: 6 hours (safety net; workflow inactivity timeout handles cleanup).-# Tests: 15 min so any sandbox orphaned by a crashed test auto-destroys quickly-# instead of burning Modal capacity for hours.-SANDBOX_TTL_SECONDS = 15 * 60 if settings.TEST else 6 * 60 * 60--class SandboxConfig(BaseModel):name: strtemplate: SandboxTemplate = SandboxTemplate.DEFAULT_BASEdiff --git a/products/tasks/backend/services/sandbox_config.py b/products/tasks/backend/services/sandbox_config.pynew file mode 100644index 000000000000..d332f23262c7--- /dev/null+++ b/products/tasks/backend/services/sandbox_config.py@@ -0,0 +1,6 @@+from django.conf import settings++# Production: 6 hours (safety net; workflow inactivity timeout handles cleanup).+# Tests: 15 min so any sandbox orphaned by a crashed test auto-destroys quickly+# instead of burning Modal capacity for hours.+SANDBOX_TTL_SECONDS = 15 * 60 if settings.TEST else 6 * 60 * 60diff --git a/products/tasks/backend/stream/event_ingest.py b/products/tasks/backend/stream/event_ingest.pynew file mode 100644index 000000000000..546346c77ba4--- /dev/null+++ b/products/tasks/backend/stream/event_ingest.py@@ -0,0 +1,387 @@+from __future__ import annotations++import re+import json+from collections.abc import AsyncGenerator, Awaitable, Callable+from dataclasses import dataclass+from typing import cast++import structlog+from asgiref.sync import sync_to_async+from jwt import PyJWTError++from products.tasks.backend.models import TaskRun+from products.tasks.backend.services.connection_token import (+ SandboxEventIngestTokenPayload,+ validate_sandbox_event_ingest_token,+)+from products.tasks.backend.stream.redis_stream import (+ TaskRunRedisStream,+ TaskRunStreamAlreadyCompleted,+ TaskRunStreamCompletionSequenceMismatch,+ TaskRunStreamSequenceGap,+ get_task_run_stream_key,+)++from ee.hogai.sandbox import is_turn_complete++logger = structlog.get_logger(__name__)++TASK_RUN_EVENT_INGEST_ROUTE = re.compile(+ r"^/api/projects/(?P<project_id>[^/]+)/tasks/(?P<task_id>[^/]+)/runs/(?P<run_id>[^/]+)/event_stream/?$"+)+HEARTBEAT_THROTTLE_SECONDS = 30+MAX_EVENT_LINE_BYTES = 1_000_000+MAX_REQUEST_BYTES = 5_000_000+MAX_EVENTS_PER_REQUEST = 1_000+STREAM_COMPLETE_CONTROL_TYPE = "_posthog/stream_complete"++ASGIMessage = dict[str, object]+ASGIReceive = Callable[[], Awaitable[ASGIMessage]]+ASGISend = Callable[[ASGIMessage], Awaitable[None]]+++class ClientDisconnected(Exception):+ pass+++class EventIngestBadRequest(Exception):+ pass+++class EventIngestPayloadTooLarge(Exception):+ def __init__(self, message: str, last_accepted_seq: int = 0):+ super().__init__(message)+ self.last_accepted_seq = last_accepted_seq+++class EventIngestHTTPError(Exception):+ def __init__(self, status_code: int, payload: dict):+ super().__init__(payload.get("error", "Event ingest request failed"))+ self.status_code = status_code+ self.payload = payload+++@dataclass(frozen=True)+class EventIngestRoute:+ project_id: str+ task_id: str+ run_id: str+++@dataclass+class EventIngestResult:+ accepted: int = 0+ duplicate: int = 0+ last_accepted_seq: int = 0+++@dataclass+class EventIngestEventLine:+ sequence: int+ event: dict+++@dataclass+class EventIngestCompleteLine:+ final_sequence: int+++async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive, send: ASGISend) -> bool:+ """Handle sandbox-to-Django streaming event ingest before Django buffers the request body."""+ if scope.get("type") != "http":+ return False++ path = scope.get("path")+ if not isinstance(path, str):+ return False++ route = _match_event_ingest_route(path)+ if route is None:+ return False++ if scope.get("method") != "POST":+ await _send_json(send, 405, {"error": "Method not allowed"})+ return True++ try:+ claims = 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))++ try:+ result = await _ingest_event_lines(+ redis_stream,+ claims.run_id,+ receive,+ )+ except ClientDisconnected:+ logger.info("task_run_event_ingest_client_disconnected", run_id=claims.run_id)+ return True+ except EventIngestBadRequest as error:+ await _send_json(send, 400, {"error": str(error)})+ return True+ except EventIngestPayloadTooLarge as error:+ await _send_json(send, 413, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})+ return True+ except TaskRunStreamSequenceGap as error:+ await _send_json(send, 409, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})+ return True+ except TaskRunStreamAlreadyCompleted as error:+ await _send_json(send, 409, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})+ return True+ except TaskRunStreamCompletionSequenceMismatch as error:+ await _send_json(send, 409, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})+ return True++ await _send_json(+ send,+ 200,+ {+ "accepted": result.accepted,+ "duplicate": result.duplicate,+ "last_accepted_seq": result.last_accepted_seq,+ },+ )+ return True+++async def _ingest_event_lines(+ redis_stream: TaskRunRedisStream,+ run_id: str,+ receive: ASGIReceive,+) -> EventIngestResult:+ result = EventIngestResult(last_accepted_seq=await redis_stream.get_last_sequence())++ event_count = 0+ completion_line_final_sequence: int | None = None+ try:+ async for line in _iter_request_lines(receive):+ parsed_line = _parse_ingest_line(line)+ if isinstance(parsed_line, EventIngestCompleteLine):+ if completion_line_final_sequence is not None:+ raise EventIngestBadRequest("Completion line must be the final event stream line")+ completion_line_final_sequence = parsed_line.final_sequence+ continue++ if completion_line_final_sequence is not None:+ raise EventIngestBadRequest("Completion line must be the final event stream line")++ event_count += 1+ if event_count > MAX_EVENTS_PER_REQUEST:+ raise EventIngestPayloadTooLarge("Too many events in request", result.last_accepted_seq)++ sequence = parsed_line.sequence+ event = parsed_line.event+ stream_id = await redis_stream.write_event_with_sequence(event, sequence)+ if stream_id is None:+ result.duplicate += 1+ result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())+ continue++ result.accepted += 1+ result.last_accepted_seq = sequence+ await _heartbeat_workflow_if_needed(redis_stream, run_id, event)+ except EventIngestPayloadTooLarge as error:+ if result.last_accepted_seq and error.last_accepted_seq == 0:+ error.last_accepted_seq = result.last_accepted_seq+ raise++ if completion_line_final_sequence is not None:+ await redis_stream.mark_complete_after_sequence(completion_line_final_sequence)++ return result+++async def _iter_request_lines(receive: ASGIReceive) -> AsyncGenerator[str, None]:+ """Yield NDJSON request lines with bounded event-loop work per request."""+ buffer = b""+ request_size = 0++ while True:+ message = await receive()+ message_type = message.get("type")+ if message_type == "http.disconnect":+ raise ClientDisconnected+ if message_type != "http.request":+ continue++ body = message.get("body", b"")+ if isinstance(body, bytes) and body:+ request_size += len(body)+ if request_size > MAX_REQUEST_BYTES:+ raise EventIngestPayloadTooLarge("Event ingest request is too large")++ buffer += body+ if len(buffer) > MAX_EVENT_LINE_BYTES and b"\n" not in buffer:+ raise EventIngestPayloadTooLarge("Event line is too large")++ lines = buffer.split(b"\n")+ buffer = lines.pop() or b""+ for line in lines:+ if len(line) > MAX_EVENT_LINE_BYTES:+ raise EventIngestPayloadTooLarge("Event line is too large")+ stripped = line.strip()+ if stripped:+ yield _decode_line(stripped)++ if not message.get("more_body", False):+ stripped = buffer.strip()+ if stripped:+ if len(stripped) > MAX_EVENT_LINE_BYTES:+ raise EventIngestPayloadTooLarge("Event line is too large")+ yield _decode_line(stripped)+ return+++def _decode_line(line: bytes) -> str:+ try:+ return line.decode("utf-8")+ except UnicodeDecodeError as error:+ raise EventIngestBadRequest("Invalid UTF-8 in event stream") from error+++def _parse_ingest_line(line: str) -> EventIngestEventLine | EventIngestCompleteLine:+ try:+ payload = json.loads(line)+ except json.JSONDecodeError as error:+ raise EventIngestBadRequest("Invalid JSON line") from error++ if not isinstance(payload, dict):+ raise EventIngestBadRequest("Each event line must be a JSON object")++ if payload.get("type") == STREAM_COMPLETE_CONTROL_TYPE:+ final_sequence = payload.get("final_seq")+ if type(final_sequence) is not int or final_sequence < 0:+ raise EventIngestBadRequest("Completion final sequence must be a non-negative integer")+ return EventIngestCompleteLine(final_sequence=final_sequence)++ sequence = payload.get("seq")+ event = payload.get("event")+ if type(sequence) is not int or sequence < 1:+ raise EventIngestBadRequest("Event sequence must be a positive integer")+ if not isinstance(event, dict):+ raise EventIngestBadRequest("Event payload must be an object")++ return EventIngestEventLine(sequence=sequence, event=event)+++async def _heartbeat_workflow_if_needed(redis_stream: TaskRunRedisStream, run_id: str, event: dict) -> None:+ if is_turn_complete(event):+ await redis_stream.set_agent_active(False)+ return++ if _is_session_update(event):+ await redis_stream.set_agent_active(True)+ agent_active = True+ else:+ agent_active = await redis_stream.get_agent_active()++ if not agent_active:+ return++ if not await redis_stream.claim_agent_active_heartbeat(HEARTBEAT_THROTTLE_SECONDS):+ return++ await sync_to_async(_heartbeat_workflow, thread_sensitive=True)(run_id, agent_active)+++def _heartbeat_workflow(run_id: str, agent_active: bool) -> None:+ try:+ task_run = TaskRun.objects.get(id=run_id)+ except TaskRun.DoesNotExist:+ logger.warning("task_run_event_ingest_heartbeat_run_missing", run_id=run_id)+ return++ task_run.heartbeat_workflow(agent_active=agent_active)+++def _is_session_update(event: dict) -> bool:+ if event.get("type") != "notification":+ return False+ notification = event.get("notification", {})+ 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:+ return TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).exists()+++def _task_run_exists(run_id: str, task_id: str, team_id: int) -> Awaitable[bool]:+ return sync_to_async(_task_run_exists_sync, thread_sensitive=True)(run_id, task_id, team_id)+++def _get_bearer_token(scope: ASGIMessage) -> str | None:+ authorization = _get_header(scope, b"authorization")+ if authorization is None:+ return None++ prefix = "Bearer "+ if not authorization.startswith(prefix):+ return None+ token = authorization[len(prefix) :].strip()+ return token or None+++def _match_event_ingest_route(path: str) -> EventIngestRoute | None:+ route_match = TASK_RUN_EVENT_INGEST_ROUTE.match(path)+ if route_match is None:+ return None+ return EventIngestRoute(+ project_id=route_match.group("project_id"),+ task_id=route_match.group("task_id"),+ run_id=route_match.group("run_id"),+ )+++async def _authorize_event_ingest_request(+ scope: ASGIMessage, route: EventIngestRoute+) -> SandboxEventIngestTokenPayload:+ token = _get_bearer_token(scope)+ if token is None:+ raise EventIngestHTTPError(401, {"error": "Missing authorization bearer token"})++ try:+ claims = await sync_to_async(validate_sandbox_event_ingest_token, thread_sensitive=False)(token)+ except PyJWTError as error:+ raise EventIngestHTTPError(+ 401,+ {"error": "Invalid event ingest token", "code": error.__class__.__name__},+ ) from error++ if claims.task_id != route.task_id or claims.run_id != route.run_id:+ raise EventIngestHTTPError(403, {"error": "Token does not match task run"})+ 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):+ raise EventIngestHTTPError(404, {"error": "Task run not found"})++ return claims+++def _get_header(scope: ASGIMessage, header_name: bytes) -> str | None:+ raw_headers = scope.get("headers", [])+ headers = cast(list[tuple[bytes, bytes]], raw_headers)+ for name, value in headers:+ if name.lower() == header_name:+ return value.decode("utf-8")+ return None+++async def _send_json(send: ASGISend, status_code: int, payload: dict) -> None:+ body = json.dumps(payload).encode("utf-8")+ await send(+ {+ "type": "http.response.start",+ "status": status_code,+ "headers": [+ (b"content-type", b"application/json"),+ (b"content-length", str(len(body)).encode("ascii")),+ ],+ }+ )+ await send({"type": "http.response.body", "body": body})diff --git a/products/tasks/backend/stream/redis_stream.py b/products/tasks/backend/stream/redis_stream.pyindex 138ab6085d64..2f04793027b6 100644--- a/products/tasks/backend/stream/redis_stream.py+++ b/products/tasks/backend/stream/redis_stream.py@@ -11,13 +11,16 @@ from asgiref.sync import async_to_syncfrom posthog.redis import get_async_client+from products.tasks.backend.services.connection_token import SANDBOX_EVENT_INGEST_TOKEN_TTL+from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS+logger = structlog.get_logger(__name__)# Keep enough live history for users who open an in-progress run late while-# still bounding Redis growth for streams with a one-hour TTL.+# still bounding Redis growth to the sandbox lifetime.TASK_RUN_STREAM_MAX_LENGTH = 20_000-TASK_RUN_STREAM_TIMEOUT = 60 * 60 # 60 minutes-TASK_RUN_STREAM_SEQUENCE_TIMEOUT = 24 * 60 * 60 # match sandbox event-ingest token lifetime+TASK_RUN_STREAM_TIMEOUT = SANDBOX_TTL_SECONDS+TASK_RUN_STREAM_SEQUENCE_TIMEOUT = int(SANDBOX_EVENT_INGEST_TOKEN_TTL.total_seconds())TASK_RUN_STREAM_PREFIX = "task-run-stream:"TASK_RUN_STREAM_READ_COUNT = 16TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS = 0.05@@ -36,6 +39,14 @@ def _normalize_stream_id(stream_id: str | bytes) -> str:return stream_id+def _normalize_redis_int(value: bytes | str | int | None) -> int:+ if value is None:+ return 0+ if isinstance(value, bytes):+ return int(value.decode("utf-8"))+ return int(value)++class TaskRunStreamError(Exception):pass@@ -75,6 +86,14 @@ def get_task_run_stream_completed_key(stream_key: str) -> str:return f"{stream_key}:completed"+def get_task_run_stream_agent_active_key(stream_key: str) -> str:+ return f"{stream_key}:ingest-agent-active"+++def get_task_run_stream_heartbeat_key(stream_key: str) -> str:+ return f"{stream_key}:ingest-heartbeat"++class TaskRunRedisStream:"""Manages task run event streaming via Redis streams.@@ -240,7 +259,27 @@ class TaskRunRedisStream:last_sequence_raw = await self._redis_client.get(sequence_key)if last_sequence_raw is not None:await self._redis_client.expire(sequence_key, self._sequence_timeout)- return int(last_sequence_raw or 0)+ return _normalize_redis_int(last_sequence_raw)++ async def set_agent_active(self, active: bool) -> None:+ await self._redis_client.set(+ get_task_run_stream_agent_active_key(self._stream_key),+ "1" if active else "0",+ ex=self._timeout,+ )++ async def get_agent_active(self) -> bool:+ active_raw = await self._redis_client.get(get_task_run_stream_agent_active_key(self._stream_key))+ return active_raw in (b"1", "1")++ async def claim_agent_active_heartbeat(self, throttle_seconds: int) -> bool:+ claimed = await self._redis_client.set(+ get_task_run_stream_heartbeat_key(self._stream_key),+ "1",+ ex=throttle_seconds,+ nx=True,+ )+ return bool(claimed)async def write_event_with_sequence(self, event: dict, sequence: int) -> str | None:"""Write an event if it is the next unseen sequence number.@@ -250,6 +289,9 @@ class TaskRunRedisStream:Returns the Redis stream ID for newly accepted events, or None for aduplicate sequence that was already accepted on an earlier connection."""+ if settings.TEST:+ return await self._write_event_with_sequence_for_tests(event, sequence)+sequence_key = get_task_run_stream_sequence_key(self._stream_key)completed_key = get_task_run_stream_completed_key(self._stream_key)raw = json.dumps(event)@@ -259,7 +301,7 @@ class TaskRunRedisStream:try:await pipe.watch(sequence_key, completed_key)last_sequence_raw = await pipe.get(sequence_key)- last_sequence = int(last_sequence_raw or 0)+ last_sequence = _normalize_redis_int(last_sequence_raw)if await pipe.exists(completed_key):raise TaskRunStreamAlreadyCompleted(last_accepted_seq=last_sequence)@@ -287,8 +329,35 @@ class TaskRunRedisStream:except redis_exceptions.WatchError:continue+ async def _write_event_with_sequence_for_tests(self, event: dict, sequence: int) -> str | None:+ """Apply sequencing semantics without WATCH/MULTI for fakeredis."""+ sequence_key = get_task_run_stream_sequence_key(self._stream_key)+ completed_key = get_task_run_stream_completed_key(self._stream_key)+ last_sequence = await self.get_last_sequence()++ if await self._redis_client.exists(completed_key):+ raise TaskRunStreamAlreadyCompleted(last_accepted_seq=last_sequence)++ if sequence <= last_sequence:+ return None++ if sequence != last_sequence + 1:+ raise TaskRunStreamSequenceGap(+ expected_sequence=last_sequence + 1,+ received_sequence=sequence,+ last_accepted_seq=last_sequence,+ )++ stream_id = await self.write_event(event)+ await self._redis_client.set(sequence_key, sequence, ex=self._sequence_timeout)+ return stream_id+async def mark_complete(self) -> None:"""Write a completion sentinel to signal end of stream."""+ if settings.TEST:+ await self._mark_complete_for_tests()+ return+completed_key = get_task_run_stream_completed_key(self._stream_key)raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})@@ -313,8 +382,20 @@ class TaskRunRedisStream:except redis_exceptions.WatchError:continue+ async def _mark_complete_for_tests(self) -> None:+ completed_key = get_task_run_stream_completed_key(self._stream_key)+ if await self._redis_client.exists(completed_key):+ return++ await self.write_event({"type": "STREAM_STATUS", "status": "complete"})+ await self._redis_client.set(completed_key, "1", ex=self._sequence_timeout)+async def mark_complete_after_sequence(self, final_sequence: int) -> None:"""Write a completion sentinel only after the expected final sequence is accepted."""+ if settings.TEST:+ await self._mark_complete_after_sequence_for_tests(final_sequence)+ return+sequence_key = get_task_run_stream_sequence_key(self._stream_key)completed_key = get_task_run_stream_completed_key(self._stream_key)raw = json.dumps({"type": "STREAM_STATUS", "status": "complete"})@@ -324,7 +405,7 @@ class TaskRunRedisStream:try:await pipe.watch(sequence_key, completed_key)last_sequence_raw = await pipe.get(sequence_key)- last_sequence = int(last_sequence_raw or 0)+ last_sequence = _normalize_redis_int(last_sequence_raw)if await pipe.exists(completed_key):return@@ -350,6 +431,26 @@ class TaskRunRedisStream:except redis_exceptions.WatchError:continue+ async def _mark_complete_after_sequence_for_tests(self, final_sequence: int) -> None:+ 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)+ last_sequence = _normalize_redis_int(last_sequence_raw)++ if await self._redis_client.exists(completed_key):+ return++ if last_sequence != final_sequence:+ raise TaskRunStreamCompletionSequenceMismatch(+ final_sequence=final_sequence,+ last_accepted_seq=last_sequence,+ )++ await self.write_event({"type": "STREAM_STATUS", "status": "complete"})+ if last_sequence_raw is not None:+ await self._redis_client.expire(sequence_key, self._sequence_timeout)+ await self._redis_client.set(completed_key, "1", ex=self._sequence_timeout)+async def mark_error(self, error: str) -> None:"""Write an error sentinel to signal stream failure."""await self.write_event({"type": "STREAM_STATUS", "status": "error", "error": error[:500]})@@ -359,7 +460,12 @@ class TaskRunRedisStream:try:sequence_key = get_task_run_stream_sequence_key(self._stream_key)completed_key = get_task_run_stream_completed_key(self._stream_key)- return await self._redis_client.delete(self._stream_key, sequence_key, completed_key) > 0+ agent_active_key = get_task_run_stream_agent_active_key(self._stream_key)+ heartbeat_key = get_task_run_stream_heartbeat_key(self._stream_key)+ deleted = await self._redis_client.delete(+ self._stream_key, sequence_key, completed_key, agent_active_key, heartbeat_key+ )+ return _normalize_redis_int(deleted) > 0except Exception:logger.exception("task_run_stream_delete_failed", stream_key=self._stream_key)return Falsediff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pynew file mode 100644index 000000000000..126be0dd87c8--- /dev/null+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -0,0 +1,662 @@+import json+import asyncio+import threading+from collections.abc import Sequence++from unittest.mock import patch++from django.test import TransactionTestCase, override_settings++from parameterized import parameterized++from posthog.models import Organization, Team+from posthog.redis import TEST_clear_clients++from products.tasks.backend.models import Task, TaskRun+from products.tasks.backend.services.connection_token import (+ SANDBOX_EVENT_INGEST_TOKEN_TTL,+ create_sandbox_connection_token,+ create_sandbox_event_ingest_token,+ get_sandbox_jwt_public_key,+)+from products.tasks.backend.services.sandbox_config import SANDBOX_TTL_SECONDS+from products.tasks.backend.stream.event_ingest import (+ MAX_EVENT_LINE_BYTES,+ MAX_EVENTS_PER_REQUEST,+ STREAM_COMPLETE_CONTROL_TYPE,+ handle_task_run_event_ingest,+)+from products.tasks.backend.stream.redis_stream import (+ TASK_RUN_STREAM_SEQUENCE_TIMEOUT,+ TASK_RUN_STREAM_TIMEOUT,+ TaskRunRedisStream,+ get_task_run_stream_completed_key,+ get_task_run_stream_key,+ get_task_run_stream_sequence_key,+)+from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY+++class TestTaskRunEventIngest(TransactionTestCase):+ def setUp(self) -> None:+ super().setUp()+ TEST_clear_clients()+ get_sandbox_jwt_public_key.cache_clear()+ self.organization = Organization.objects.create(name="Test Org")+ self.team = Team.objects.create(organization=self.organization, name="Test Team")+ self.task = Task.objects.create(+ team=self.team,+ title="Test Task",+ description="Test Description",+ origin_product=Task.OriginProduct.USER_CREATED,+ )+ self.task_run: TaskRun = self.task.create_run()+ self._delete_run_stream()++ def tearDown(self) -> None:+ self._delete_run_stream()+ TEST_clear_clients()+ get_sandbox_jwt_public_key.cache_clear()+ super().tearDown()++ def _delete_run_stream(self) -> None:+ async def _delete_stream() -> None:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(self.task_run.id)))+ await redis_stream.delete_stream()++ asyncio.run(_delete_stream())++ def _ingest_url(+ self,+ task: Task | None = None,+ run: TaskRun | None = None,+ project_id: str | int | None = None,+ ) -> str:+ task = task or self.task+ run = run or self.task_run+ project_id = project_id if project_id is not None else self.team.id+ return f"/api/projects/{project_id}/tasks/{task.id}/runs/{run.id}/event_stream/"++ def _create_token(self, run: TaskRun | None = None) -> str:+ return create_sandbox_event_ingest_token(run or self.task_run)++ def _call_ingest(+ self,+ token: str,+ lines: Sequence[dict],+ path: str | None = None,+ ) -> tuple[int, dict]:+ body = "".join(json.dumps(line) + "\n" for line in lines).encode("utf-8")+ return self._call_ingest_chunks(+ token,+ [body[: len(body) // 2], body[len(body) // 2 :]],+ path=path,+ )++ def _call_ingest_chunks(+ self,+ token: str,+ chunks: Sequence[bytes],+ path: str | None = None,+ ) -> tuple[int, dict]:+ async def _call() -> tuple[int, dict]:+ messages = [+ {"type": "http.request", "body": chunk, "more_body": index < len(chunks) - 1}+ for index, chunk in enumerate(chunks)+ ]+ sent: list[dict] = []++ async def receive() -> dict:+ return messages.pop(0)++ async def send(message: dict) -> None:+ sent.append(message)++ headers = [(b"authorization", f"Bearer {token}".encode())]++ handled = await handle_task_run_event_ingest(+ {+ "type": "http",+ "method": "POST",+ "path": path or self._ingest_url(),+ "headers": headers,+ },+ receive,+ send,+ )+ self.assertTrue(handled)+ status = sent[0]["status"]+ body = json.loads(sent[1]["body"])+ return status, body++ return asyncio.run(_call())++ def _read_stream_events(self) -> list[dict]:+ async def _read() -> list[dict]:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(self.task_run.id)))+ messages = await redis_stream._redis_client.xrange(get_task_run_stream_key(str(self.task_run.id)))+ return [json.loads(message[b"data"]) for _, message in messages]++ return asyncio.run(_read())++ def _seed_stream_events(self, events: Sequence[tuple[int, dict]]) -> None:+ async def _seed() -> None:+ redis_stream = TaskRunRedisStream(get_task_run_stream_key(str(self.task_run.id)))+ for sequence, event in events:+ await redis_stream.write_event_with_sequence(event, sequence)++ asyncio.run(_seed())++ def _read_notification_methods(self) -> list[str]:+ methods: list[str] = []+ for event in self._read_stream_events():+ notification = event.get("notification")+ if isinstance(notification, dict) and isinstance(notification.get("method"), str):+ methods.append(notification["method"])+ return methods++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_streaming_ingest_writes_ordered_events_with_explicit_completion(self) -> None:+ token = self._create_token()++ with patch.object(TaskRun, "heartbeat_workflow") as heartbeat_workflow:+ status, body = self._call_ingest(+ token,+ [+ {+ "seq": 1,+ "event": {"type": "notification", "notification": {"method": "session/update"}},+ },+ {+ "seq": 2,+ "event": {"type": "notification", "notification": {"method": "_posthog/task_complete"}},+ },+ {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 2},+ ],+ )++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 2)+ self.assertEqual(body["last_accepted_seq"], 2)+ heartbeat_workflow.assert_called_once_with(agent_active=True)++ events = self._read_stream_events()+ self.assertEqual(self._read_notification_methods(), ["session/update", "_posthog/task_complete"])+ self.assertIn({"type": "STREAM_STATUS", "status": "complete"}, events)++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_current_project_path_ingests_with_token_scoped_task_run(self) -> None:+ token = self._create_token()++ status, body = self._call_ingest(+ token,+ [{"seq": 1, "event": {"type": "notification", "notification": {"method": "session/update"}}}],+ path=self._ingest_url(project_id="@current"),+ )++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ self.assertEqual(self._read_notification_methods(), ["session/update"])++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_workflow_heartbeat_does_not_block_event_loop(self) -> None:+ token = self._create_token()+ heartbeat_entered = threading.Event()+ heartbeat_released = threading.Event()+ heartbeat_timed_out = threading.Event()++ def blocking_heartbeat(_run_id: str, _agent_active: bool) -> None:+ heartbeat_entered.set()+ if not heartbeat_released.wait(timeout=1):+ heartbeat_timed_out.set()++ async def _call() -> tuple[int, dict]:+ body = (+ json.dumps(+ {+ "seq": 1,+ "event": {"type": "notification", "notification": {"method": "session/update"}},+ }+ )+ + "\n"+ ).encode("utf-8")+ messages = [{"type": "http.request", "body": body, "more_body": False}]+ sent: list[dict] = []++ async def receive() -> dict:+ return messages.pop(0)++ async def send(message: dict) -> None:+ sent.append(message)++ async def release_heartbeat_from_event_loop() -> None:+ for _ in range(1000):+ if heartbeat_entered.is_set():+ break+ await asyncio.sleep(0.001)+ heartbeat_released.set()++ await asyncio.gather(+ handle_task_run_event_ingest(+ {+ "type": "http",+ "method": "POST",+ "path": self._ingest_url(),+ "headers": [(b"authorization", f"Bearer {token}".encode())],+ },+ receive,+ send,+ ),+ release_heartbeat_from_event_loop(),+ )+ return sent[0]["status"], json.loads(sent[1]["body"])++ with patch("products.tasks.backend.stream.event_ingest._heartbeat_workflow", side_effect=blocking_heartbeat):+ status, body = asyncio.run(_call())++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ self.assertTrue(heartbeat_entered.is_set())+ self.assertFalse(heartbeat_timed_out.is_set())++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_duplicate_sequence_is_skipped_on_reconnect(self) -> None:+ token = self._create_token()++ self._seed_stream_events([(1, {"type": "notification", "notification": {"method": "first"}})])++ with patch.object(TaskRun, "heartbeat_workflow"):+ status, body = self._call_ingest(+ token,+ [+ {"seq": 1, "event": {"type": "notification", "notification": {"method": "first"}}},+ {"seq": 2, "event": {"type": "notification", "notification": {"method": "second"}}},+ ],+ )++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ self.assertEqual(body["duplicate"], 1)+ self.assertEqual(body["last_accepted_seq"], 2)+ self.assertEqual(self._read_notification_methods(), ["first", "second"])++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_duplicate_terminal_sequence_does_not_complete_without_completion_line(self) -> None:+ token = self._create_token()+ terminal_event = {"type": "notification", "notification": {"method": "_posthog/task_complete"}}++ self._seed_stream_events([(1, terminal_event)])++ with patch.object(TaskRun, "heartbeat_workflow"):+ status, body = self._call_ingest(token, [{"seq": 1, "event": terminal_event}])++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 0)+ self.assertEqual(body["duplicate"], 1)+ self.assertEqual(body["last_accepted_seq"], 1)+ self.assertNotIn({"type": "STREAM_STATUS", "status": "complete"}, self._read_stream_events())++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_duplicate_terminal_sequence_can_complete_with_completion_line(self) -> None:+ token = self._create_token()+ terminal_event = {"type": "notification", "notification": {"method": "_posthog/task_complete"}}++ self._seed_stream_events([(1, terminal_event)])++ with patch.object(TaskRun, "heartbeat_workflow"):+ status, body = self._call_ingest(+ token,+ [{"seq": 1, "event": terminal_event}, {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 1}],+ )++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 0)+ self.assertEqual(body["duplicate"], 1)+ self.assertEqual(body["last_accepted_seq"], 1)+ self.assertIn({"type": "STREAM_STATUS", "status": "complete"}, self._read_stream_events())++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_completion_control_line_completes_after_streamed_events(self) -> None:+ token = self._create_token()++ status, body = self._call_ingest(+ token,+ [+ {+ "seq": 1,+ "event": {"type": "notification", "notification": {"method": "session/update"}},+ },+ {+ "seq": 2,+ "event": {"type": "notification", "notification": {"method": "_posthog/task_complete"}},+ },+ {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 2},+ ],+ )++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 2)+ self.assertEqual(body["last_accepted_seq"], 2)+ events = self._read_stream_events()+ self.assertEqual(self._read_notification_methods(), ["session/update", "_posthog/task_complete"])+ self.assertIn({"type": "STREAM_STATUS", "status": "complete"}, events)++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_completion_control_line_rejects_unaccepted_final_sequence(self) -> None:+ token = self._create_token()++ status, body = self._call_ingest(+ token,+ [+ {+ "seq": 1,+ "event": {"type": "notification", "notification": {"method": "session/update"}},+ },+ {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 2},+ ],+ )++ self.assertEqual(status, 409)+ self.assertEqual(body["last_accepted_seq"], 1)+ self.assertNotIn({"type": "STREAM_STATUS", "status": "complete"}, self._read_stream_events())++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_completion_control_line_must_be_final_line(self) -> None:+ token = self._create_token()++ status, body = self._call_ingest(+ token,+ [+ {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": 0},+ {+ "seq": 1,+ "event": {"type": "notification", "notification": {"method": "session/update"}},+ },+ ],+ )++ self.assertEqual(status, 400)+ self.assertEqual(body["error"], "Completion line must be the final event stream line")+ self.assertNotIn({"type": "STREAM_STATUS", "status": "complete"}, self._read_stream_events())+ self.assertEqual(self._read_notification_methods(), [])++ @parameterized.expand(+ [+ ("missing_final_seq", {"type": STREAM_COMPLETE_CONTROL_TYPE}),+ ("negative_final_seq", {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": -1}),+ ("string_final_seq", {"type": STREAM_COMPLETE_CONTROL_TYPE, "final_seq": "1"}),+ ]+ )+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_completion_control_line_rejects_invalid_final_sequence(self, _case_name: str, line: dict) -> None:+ token = self._create_token()++ status, body = self._call_ingest(token, [line])++ self.assertEqual(status, 400)+ self.assertEqual(body["error"], "Completion final sequence must be a non-negative integer")++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_sequence_gap_returns_last_accepted_sequence(self) -> None:+ token = self._create_token()++ self._seed_stream_events([(1, {"type": "notification", "notification": {"method": "first"}})])++ status, body = self._call_ingest(+ token,+ [{"seq": 3, "event": {"type": "notification", "notification": {"method": "third"}}}],+ )++ self.assertEqual(status, 409)+ self.assertEqual(body["last_accepted_seq"], 1)+ self.assertEqual(self._read_notification_methods(), ["first"])++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_completed_stream_rejects_late_sequenced_events(self) -> None:+ token = self._create_token()++ async def _seed_and_complete_stream() -> None:+ stream_key = get_task_run_stream_key(str(self.task_run.id))+ redis_stream = TaskRunRedisStream(stream_key)+ # This test needs a completed stream fixture; sequencing writes are covered separately.+ await redis_stream.write_event({"type": "notification", "notification": {"method": "first"}})+ await redis_stream.write_event({"type": "STREAM_STATUS", "status": "complete"})+ await redis_stream._redis_client.set(+ get_task_run_stream_sequence_key(stream_key),+ 1,+ ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT,+ )+ await redis_stream._redis_client.set(+ get_task_run_stream_completed_key(stream_key),+ "1",+ ex=TASK_RUN_STREAM_SEQUENCE_TIMEOUT,+ )++ asyncio.run(_seed_and_complete_stream())++ status, body = self._call_ingest(+ token,+ [{"seq": 2, "event": {"type": "notification", "notification": {"method": "late"}}}],+ )++ self.assertEqual(status, 409)+ self.assertEqual(body["last_accepted_seq"], 1)+ self.assertIn({"type": "STREAM_STATUS", "status": "complete"}, self._read_stream_events())+ self.assertEqual(self._read_notification_methods(), ["first"])++ def test_live_stream_ttl_matches_sandbox_ttl(self) -> None:+ async def _write_and_get_ttl() -> int:+ stream_key = get_task_run_stream_key(str(self.task_run.id))+ redis_stream = TaskRunRedisStream(stream_key)+ await redis_stream.write_event({"type": "notification", "notification": {"method": "first"}})+ return await redis_stream._redis_client.ttl(stream_key)++ stream_ttl = asyncio.run(_write_and_get_ttl())++ self.assertEqual(TASK_RUN_STREAM_TIMEOUT, SANDBOX_TTL_SECONDS)+ self.assertGreater(stream_ttl, SANDBOX_TTL_SECONDS - 5)+ self.assertLessEqual(stream_ttl, SANDBOX_TTL_SECONDS)++ def test_sequence_key_ttl_outlives_live_stream_ttl(self) -> None:+ async def _write_and_get_ttls() -> tuple[int, int]:+ stream_key = get_task_run_stream_key(str(self.task_run.id))+ redis_stream = TaskRunRedisStream(stream_key, timeout=5)+ await redis_stream.write_event_with_sequence(+ {"type": "notification", "notification": {"method": "first"}},+ 1,+ )+ return (+ await redis_stream._redis_client.ttl(stream_key),+ await redis_stream._redis_client.ttl(get_task_run_stream_sequence_key(stream_key)),+ )++ stream_ttl, sequence_ttl = asyncio.run(_write_and_get_ttls())++ self.assertGreater(stream_ttl, 0)+ self.assertLessEqual(stream_ttl, 5)+ self.assertEqual(TASK_RUN_STREAM_SEQUENCE_TIMEOUT, int(SANDBOX_EVENT_INGEST_TOKEN_TTL.total_seconds()))+ self.assertGreater(sequence_ttl, TASK_RUN_STREAM_SEQUENCE_TIMEOUT - 5)+ self.assertLessEqual(sequence_ttl, TASK_RUN_STREAM_SEQUENCE_TIMEOUT)+ self.assertGreater(sequence_ttl, stream_ttl)++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_non_terminal_request_close_does_not_complete(self) -> None:+ token = self._create_token()++ status, body = self._call_ingest(+ token,+ [{"seq": 1, "event": {"type": "notification", "notification": {"method": "session/update"}}}],+ )++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ self.assertNotIn({"type": "STREAM_STATUS", "status": "complete"}, self._read_stream_events())++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_empty_request_returns_last_accepted_sequence(self) -> None:+ token = self._create_token()++ self._seed_stream_events(+ [+ (1, {"type": "notification", "notification": {"method": "first"}}),+ (2, {"type": "notification", "notification": {"method": "second"}}),+ ]+ )++ status, body = self._call_ingest(token, [])++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 0)+ self.assertEqual(body["last_accepted_seq"], 2)++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_multibyte_utf8_can_span_request_chunks(self) -> None:+ token = self._create_token()+ line = (+ json.dumps(+ {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {"method": "_posthog/console", "params": {"message": "hello ☃"}},+ },+ },+ ensure_ascii=False,+ )+ + "\n"+ ).encode("utf-8")+ split_at = line.index("☃".encode()) + 1++ status, body = self._call_ingest_chunks(token, [line[:split_at], line[split_at:]])++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ events = self._read_stream_events()+ notifications = [event["notification"] for event in events if "notification" in event]+ self.assertEqual(notifications[-1]["params"]["message"], "hello ☃")++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_connection_token_cannot_ingest_events(self) -> None:+ token = create_sandbox_connection_token(self.task_run, user_id=1, distinct_id="user-1")++ status, body = self._call_ingest(+ token,+ [{"seq": 1, "event": {"type": "notification", "notification": {"method": "session/update"}}}],+ )++ self.assertEqual(status, 401)+ self.assertEqual(body["error"], "Invalid event ingest token")++ @parameterized.expand(+ [+ ("single_oversized_line", False, 0, []),+ ("accepted_prefix_before_oversized_line", True, 1, ["first"]),+ ]+ )+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_rejects_oversized_event_line_cases(+ self,+ _case_name: str,+ include_accepted_prefix: bool,+ expected_last_accepted_seq: int,+ expected_notification_methods: Sequence[str],+ ) -> None:+ token = self._create_token()+ chunks: list[bytes] = []+ if include_accepted_prefix:+ chunks.append(+ (+ json.dumps({"seq": 1, "event": {"type": "notification", "notification": {"method": "first"}}})+ + "\n"+ ).encode("utf-8")+ )++ oversized_line = (+ json.dumps(+ {+ "seq": 2 if include_accepted_prefix else 1,+ "event": {+ "type": "notification",+ "notification": {+ "method": "_posthog/console",+ "params": {"message": "x" * MAX_EVENT_LINE_BYTES},+ },+ },+ },+ )+ ).encode("utf-8")+ chunks.append(oversized_line)++ status, body = self._call_ingest_chunks(token, [b"".join(chunks)])++ self.assertEqual(status, 413)+ self.assertEqual(body["error"], "Event line is too large")+ self.assertEqual(body["last_accepted_seq"], expected_last_accepted_seq)+ self.assertEqual(self._read_notification_methods(), expected_notification_methods)++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_rejects_too_many_events_in_single_request(self) -> None:+ token = self._create_token()+ lines = [+ {"seq": sequence, "event": {"type": "notification", "notification": {"method": "session/update"}}}+ for sequence in range(1, MAX_EVENTS_PER_REQUEST + 2)+ ]++ status, body = self._call_ingest(token, lines)++ self.assertEqual(status, 413)+ self.assertEqual(body["error"], "Too many events in request")+ self.assertEqual(body["last_accepted_seq"], MAX_EVENTS_PER_REQUEST)++ @parameterized.expand(+ [+ (+ "initial_console",+ [+ {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {"method": "_posthog/console", "params": {"message": "starting"}},+ },+ }+ ],+ 1,+ ),+ (+ "turn_complete_then_console",+ [+ {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {+ "method": "_posthog/turn_complete",+ "params": {"stopReason": "end_turn"},+ },+ },+ },+ {+ "seq": 2,+ "event": {+ "type": "notification",+ "notification": {"method": "_posthog/console", "params": {"message": "tail"}},+ },+ },+ ],+ 2,+ ),+ ]+ )+ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_inactive_agent_events_do_not_heartbeat_workflow(+ self, _case_name: str, lines: Sequence[dict], expected_accepted: int+ ) -> None:+ token = self._create_token()++ with patch.object(TaskRun, "heartbeat_workflow") as heartbeat_workflow:+ status, body = self._call_ingest(token, lines)++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], expected_accepted)+ heartbeat_workflow.assert_not_called()