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.

chore(tasks): add cloud-run stream and credential-refresh metrics (#61099)

Alessandro Pogliaghie7a1a369023b
diff --git a/products/tasks/backend/api.py b/products/tasks/backend/api.py
index 5f0c5c7f0b8e..bb184a7aa51e 100644
--- a/products/tasks/backend/api.py
+++ b/products/tasks/backend/api.py
@@ -54,6 +54,14 @@ from .automation_service import (
sync_automation_schedule,
update_automation_run_result,
)
+from .metrics import (
+ StreamConnectionOutcome,
+ observe_stream_connection_closed,
+ observe_stream_connection_opened,
+ observe_stream_length_on_connect,
+ observe_stream_resume_gap,
+ origin_product_label,
+)
from .models import (
TASK_PRESENCE_TTL_SECONDS,
CodeInvite,
@@ -2680,51 +2688,90 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
last_event_id = request.headers.get("Last-Event-ID")
start_latest = request.GET.get("start") == "latest"
format_sse_event = self._format_sse_event
+ origin_product = origin_product_label(task_run)
async def async_stream() -> AsyncGenerator[bytes, None]:
redis_stream = TaskRunRedisStream(stream_key)
- delay = TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS
- wait_started_at = asyncio.get_running_loop().time()
- last_keepalive_at = wait_started_at
-
- while not await redis_stream.exists():
- now = asyncio.get_running_loop().time()
- if now - wait_started_at >= TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS:
- yield format_sse_event({"error": "Stream not available"}, event_name="error")
- return
-
- if now - last_keepalive_at >= TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS:
- last_keepalive_at = now
- yield format_sse_event(
- TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
- event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
- )
-
- await asyncio.sleep(delay)
- delay = min(
- delay + TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
- TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
- )
-
- start_id = last_event_id or "0"
- if not last_event_id and start_latest:
- start_id = await redis_stream.get_latest_stream_id() or "0"
+ connection_started_at = asyncio.get_running_loop().time()
+ # Default to client_disconnect: any exit that isn't an explicit
+ # completion/error/unavailable is the client (or proxy) going away.
+ outcome: StreamConnectionOutcome = "client_disconnect"
+ # Record opened inside the try so the closed counter only fires when
+ # the open succeeded — keeps opened/closed balanced for the
+ # active-connections gauge regardless of which increment fails.
+ opened = False
try:
- async for stream_item in redis_stream.read_stream_entries(
- start_id=start_id,
- keepalive_interval_seconds=TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS,
- ):
- if stream_item is None:
+ observe_stream_connection_opened(origin_product)
+ opened = True
+ delay = TASK_RUN_STREAM_WAIT_INITIAL_DELAY_SECONDS
+ wait_started_at = asyncio.get_running_loop().time()
+ last_keepalive_at = wait_started_at
+
+ while not await redis_stream.exists():
+ now = asyncio.get_running_loop().time()
+ if now - wait_started_at >= TASK_RUN_STREAM_WAIT_TIMEOUT_SECONDS:
+ outcome = "unavailable"
+ yield format_sse_event({"error": "Stream not available"}, event_name="error")
+ return
+
+ if now - last_keepalive_at >= TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS:
+ last_keepalive_at = now
yield format_sse_event(
TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
)
- continue
- event_id, event = stream_item
- yield format_sse_event(event, event_id=event_id)
- except TaskRunStreamError as e:
- logger.error("TaskRunRedisStream error for stream %s: %s", stream_key, e, exc_info=True)
- yield format_sse_event({"error": str(e)}, event_name="error")
+
+ await asyncio.sleep(delay)
+ delay = min(
+ delay + TASK_RUN_STREAM_WAIT_DELAY_INCREMENT_SECONDS,
+ TASK_RUN_STREAM_WAIT_MAX_DELAY_SECONDS,
+ )
+
+ # Only reconnects (Last-Event-ID set) can suffer a trimmed resume
+ # point, and that's the only case where stream depth vs the trim
+ # cap is interesting — so skip the extra Redis reads on fresh
+ # connects. Best-effort: never break the stream.
+ if last_event_id:
+ try:
+ observe_stream_length_on_connect(await redis_stream.get_length())
+ if await redis_stream.resume_point_trimmed(last_event_id):
+ observe_stream_resume_gap(origin_product)
+ logger.warning(
+ "task_run_stream_resume_gap",
+ extra={"stream_key": stream_key, "last_event_id": last_event_id},
+ )
+ except Exception:
+ logger.warning(
+ "task_run_stream_attach_observe_failed",
+ extra={"stream_key": stream_key},
+ exc_info=True,
+ )
+
+ start_id = last_event_id or "0"
+ if not last_event_id and start_latest:
+ start_id = await redis_stream.get_latest_stream_id() or "0"
+ try:
+ async for stream_item in redis_stream.read_stream_entries(
+ start_id=start_id,
+ keepalive_interval_seconds=TASK_RUN_STREAM_KEEPALIVE_INTERVAL_SECONDS,
+ ):
+ if stream_item is None:
+ yield format_sse_event(
+ TASK_RUN_STREAM_KEEPALIVE_PAYLOAD,
+ event_name=TASK_RUN_STREAM_KEEPALIVE_EVENT_NAME,
+ )
+ continue
+ event_id, event = stream_item
+ yield format_sse_event(event, event_id=event_id)
+ outcome = "completed"
+ except TaskRunStreamError as e:
+ outcome = "stream_error"
+ logger.error("TaskRunRedisStream error for stream %s: %s", stream_key, e, exc_info=True)
+ yield format_sse_event({"error": str(e)}, event_name="error")
+ finally:
+ if opened:
+ duration = asyncio.get_running_loop().time() - connection_started_at
+ observe_stream_connection_closed(origin_product, outcome, duration)
return StreamingHttpResponse(
async_stream() if settings.SERVER_GATEWAY_INTERFACE == "ASGI" else async_to_sync(lambda: async_stream()),
diff --git a/products/tasks/backend/metrics.py b/products/tasks/backend/metrics.py
index d01bd8003b30..1953b03b8ebc 100644
--- a/products/tasks/backend/metrics.py
+++ b/products/tasks/backend/metrics.py
@@ -1,12 +1,18 @@
from typing import TYPE_CHECKING, Literal
-from prometheus_client import Counter
+from prometheus_client import Counter, Histogram
if TYPE_CHECKING:
from products.tasks.backend.models import TaskRun
TaskWorkflowStartOutcome = Literal["attempted", "blocked", "failed", "started"]
+# Outcome of an SSE task-run stream connection when it closes.
+# completed — stream reached its completion sentinel
+# stream_error — Redis/stream error sentinel ended the connection
+# unavailable — stream key never appeared within the wait timeout
+# client_disconnect — client went away (GeneratorExit) before completion
+StreamConnectionOutcome = Literal["completed", "stream_error", "unavailable", "client_disconnect"]
_ALLOWED_MODES = {"background", "interactive"}
_ALLOWED_RUN_SOURCES = {"manual", "signal_report"}
_ALLOWED_RUNTIME_ADAPTERS = {"claude", "codex"}
@@ -48,6 +54,60 @@ TASK_RUN_FAILED_TOTAL = Counter(
)
+# Connection lifetimes span a few seconds (cold reconnect) to the 6h sandbox TTL.
+# The 120s bucket is deliberate: it isolates connections cut at the Envoy/Contour
+# response_timeout boundary from genuinely long-lived ones.
+STREAM_CONNECTION_DURATION_BUCKETS = [
+ 1.0,
+ 5.0,
+ 15.0,
+ 30.0,
+ 60.0,
+ 120.0,
+ 300.0,
+ 600.0,
+ 1_800.0,
+ 3_600.0,
+ 7_200.0,
+ 21_600.0,
+]
+# Stream length is capped at TASK_RUN_STREAM_MAX_LENGTH (~20k); the top buckets
+# show how close real runs get to the trim threshold.
+STREAM_LENGTH_BUCKETS = [10.0, 50.0, 100.0, 500.0, 1_000.0, 2_500.0, 5_000.0, 10_000.0, 15_000.0, 20_000.0]
+
+
+TASK_RUN_STREAM_CONNECTIONS_OPENED_TOTAL = Counter(
+ "posthog_tasks_task_run_stream_connections_opened_total",
+ "SSE task-run stream connections opened",
+ labelnames=["origin_product"],
+)
+
+TASK_RUN_STREAM_CONNECTIONS_CLOSED_TOTAL = Counter(
+ "posthog_tasks_task_run_stream_connections_closed_total",
+ "SSE task-run stream connections closed, labeled by how they ended",
+ labelnames=["origin_product", "outcome"],
+)
+
+TASK_RUN_STREAM_CONNECTION_DURATION_SECONDS = Histogram(
+ "posthog_tasks_task_run_stream_connection_duration_seconds",
+ "Lifetime of an SSE task-run stream connection",
+ labelnames=["origin_product", "outcome"],
+ buckets=STREAM_CONNECTION_DURATION_BUCKETS,
+)
+
+TASK_RUN_STREAM_LENGTH_ON_CONNECT = Histogram(
+ "posthog_tasks_task_run_stream_length_on_connect",
+ "Redis stream length observed when an SSE connection reconnects with a cursor",
+ buckets=STREAM_LENGTH_BUCKETS,
+)
+
+TASK_RUN_STREAM_RESUME_GAP_TOTAL = Counter(
+ "posthog_tasks_task_run_stream_resume_gap_total",
+ "SSE reconnects whose Last-Event-ID was already trimmed from Redis (events lost for that client)",
+ labelnames=["origin_product"],
+)
+
+
def _metric_label(value: object | None) -> str:
if value is None:
return "unknown"
@@ -82,7 +142,7 @@ def _task_run_labels(task_run: "TaskRun | None") -> dict[str, str]:
state = task_run.state if isinstance(task_run.state, dict) else {}
return {
- "origin_product": _metric_label(getattr(task_run.task, "origin_product", None)),
+ "origin_product": origin_product_label(task_run),
"run_environment": _metric_label(task_run.environment),
"mode": _bounded_metric_label(state.get("mode"), _ALLOWED_MODES),
"run_source": _bounded_metric_label(state.get("run_source"), _ALLOWED_RUN_SOURCES),
@@ -107,6 +167,34 @@ def observe_task_run_workflow_start(
).inc()
+def origin_product_label(task_run: "TaskRun | None") -> str:
+ """Bounded origin_product metric label resolved from the task run's task."""
+ if task_run is None:
+ return "unknown"
+ return _metric_label(getattr(task_run.task, "origin_product", None))
+
+
+def observe_stream_connection_opened(origin_product: str) -> None:
+ TASK_RUN_STREAM_CONNECTIONS_OPENED_TOTAL.labels(origin_product=origin_product).inc()
+
+
+def observe_stream_connection_closed(
+ origin_product: str, outcome: StreamConnectionOutcome, duration_seconds: float
+) -> None:
+ TASK_RUN_STREAM_CONNECTIONS_CLOSED_TOTAL.labels(origin_product=origin_product, outcome=outcome).inc()
+ TASK_RUN_STREAM_CONNECTION_DURATION_SECONDS.labels(origin_product=origin_product, outcome=outcome).observe(
+ duration_seconds
+ )
+
+
+def observe_stream_length_on_connect(length: int) -> None:
+ TASK_RUN_STREAM_LENGTH_ON_CONNECT.observe(length)
+
+
+def observe_stream_resume_gap(origin_product: str) -> None:
+ TASK_RUN_STREAM_RESUME_GAP_TOTAL.labels(origin_product=origin_product).inc()
+
+
def observe_task_run_failed(properties: dict[str, object]) -> None:
TASK_RUN_FAILED_TOTAL.labels(
origin_product=_metric_label(properties.get("origin_product")),
diff --git a/products/tasks/backend/stream/redis_stream.py b/products/tasks/backend/stream/redis_stream.py
index 2f04793027b6..64c761a504d9 100644
--- a/products/tasks/backend/stream/redis_stream.py
+++ b/products/tasks/backend/stream/redis_stream.py
@@ -47,6 +47,15 @@ def _normalize_redis_int(value: bytes | str | int | None) -> int:
return int(value)
+def _stream_id_sort_key(stream_id: str) -> tuple[int, int]:
+ """Parse a Redis stream ID ('<ms>-<seq>') into a comparable (ms, seq) tuple."""
+ ms_part, _, seq_part = stream_id.partition("-")
+ try:
+ return (int(ms_part), int(seq_part) if seq_part else 0)
+ except ValueError:
+ return (0, 0)
+
+
class TaskRunStreamError(Exception):
pass
@@ -155,6 +164,33 @@ class TaskRunRedisStream:
stream_id, _message = messages[0]
return _normalize_stream_id(stream_id)
+ async def get_first_stream_id(self) -> str | None:
+ """Return the oldest surviving stream ID, or None if the stream is empty."""
+ messages = await self._redis_client.xrange(self._stream_key, count=1)
+ if not messages:
+ return None
+ stream_id, _message = messages[0]
+ return _normalize_stream_id(stream_id)
+
+ async def get_length(self) -> int:
+ """Return the current number of entries in the stream."""
+ return _normalize_redis_int(await self._redis_client.xlen(self._stream_key))
+
+ async def resume_point_trimmed(self, last_event_id: str) -> bool:
+ """Return True if a reconnect from last_event_id has lost trimmed events.
+
+ A client resumes via XREAD after its Last-Event-ID, which only returns
+ entries strictly newer than that ID. If the requested ID is older than
+ the oldest surviving entry, the events immediately after it were evicted
+ by the maxlen trim and are gone for good — an undetectable gap otherwise.
+ """
+ if last_event_id in ("", "0"):
+ return False
+ first_id = await self.get_first_stream_id()
+ if first_id is None:
+ return False
+ return _stream_id_sort_key(last_event_id) < _stream_id_sort_key(first_id)
+
async def read_stream(
self,
start_id: str = "0",
diff --git a/products/tasks/backend/stream/tests/test_redis_stream.py b/products/tasks/backend/stream/tests/test_redis_stream.py
index eec91dd99183..cfebf11cdaed 100644
--- a/products/tasks/backend/stream/tests/test_redis_stream.py
+++ b/products/tasks/backend/stream/tests/test_redis_stream.py
@@ -9,6 +9,7 @@ from products.tasks.backend.stream.redis_stream import (
TaskRunStreamAlreadyCompleted,
TaskRunStreamCompletionSequenceMismatch,
TaskRunStreamSequenceGap,
+ _stream_id_sort_key,
)
@@ -106,3 +107,62 @@ async def test_mark_complete_is_idempotent() -> None:
assert await _read_stream_events(redis_stream) == [{"type": "STREAM_STATUS", "status": "complete"}]
finally:
await redis_stream.delete_stream()
+
+
+ "left,right,expected_less",
+ [
+ ("5-0", "10-0", True),
+ ("10-0", "5-0", False),
+ ("10-0", "10-1", True),
+ ("10-1", "10-0", False),
+ ("10-5", "10-5", False),
+ ("not-an-id", "10-0", True),
+ ],
+)
+def test_stream_id_sort_key_orders_ids(left: str, right: str, expected_less: bool) -> None:
+ assert (_stream_id_sort_key(left) < _stream_id_sort_key(right)) is expected_less
+
+
+async def test_get_length_and_first_stream_id() -> None:
+ redis_stream = _new_stream()
+ try:
+ assert await redis_stream.get_length() == 0
+ assert await redis_stream.get_first_stream_id() is None
+
+ first_id = await redis_stream.write_event({"type": "a"})
+ await redis_stream.write_event({"type": "b"})
+
+ assert await redis_stream.get_length() == 2
+ assert await redis_stream.get_first_stream_id() == first_id
+ finally:
+ await redis_stream.delete_stream()
+
+
+async def test_resume_point_trimmed_only_when_cursor_predates_surviving_entries() -> None:
+ redis_stream = _new_stream()
+ try:
+ first_id = await redis_stream.write_event({"type": "a"})
+ second_id = await redis_stream.write_event({"type": "b"})
+
+ # Special-case cursors and a still-present cursor are never gaps.
+ assert await redis_stream.resume_point_trimmed("0") is False
+ assert await redis_stream.resume_point_trimmed("") is False
+ assert await redis_stream.resume_point_trimmed(first_id) is False
+ assert await redis_stream.resume_point_trimmed(second_id) is False
+
+ # A cursor older than the oldest surviving entry means events were trimmed.
+ assert await redis_stream.resume_point_trimmed("1-0") is True
+ finally:
+ await redis_stream.delete_stream()
+
+
+async def test_resume_point_trimmed_false_when_stream_empty() -> None:
+ redis_stream = _new_stream()
+ try:
+ assert await redis_stream.resume_point_trimmed("123-0") is False
+ finally:
+ await redis_stream.delete_stream()
diff --git a/products/tasks/backend/temporal/metrics.py b/products/tasks/backend/temporal/metrics.py
index c75bf11e2635..b397e22baad8 100644
--- a/products/tasks/backend/temporal/metrics.py
+++ b/products/tasks/backend/temporal/metrics.py
@@ -50,6 +50,23 @@ def increment_snapshot_usage(used_snapshot: bool) -> None:
).add(1)
+def increment_credential_refresh(kind: str, outcome: str) -> None:
+ """Record a sandbox credential refresh outcome.
+
+ outcome is one of: refreshed (token re-injected), skipped (nothing to do or
+ token could not be resolved), failed (the credential raised). Best-effort:
+ a metric failure must never break the refresh loop.
+ """
+ try:
+ meter = _metric_meter({"kind": kind, "outcome": outcome})
+ meter.create_counter(
+ "tasks_sandbox_credential_refresh",
+ "Sandbox credential refresh outcomes for running cloud task runs",
+ ).add(1)
+ except Exception:
+ pass
+
+
class StepTimer:
def __init__(self, step: str, used_snapshot: bool | None = None) -> None:
self.step = step
diff --git a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
index 686d7e407709..5dff821c483a 100644
--- a/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/refresh_sandbox_credentials.py
@@ -10,6 +10,7 @@ from products.tasks.backend.services.agent_command import send_refresh_session
from products.tasks.backend.services.connection_token import create_sandbox_connection_token
from products.tasks.backend.services.sandbox import Sandbox
from products.tasks.backend.temporal.exceptions import TaskNotFoundError
+from products.tasks.backend.temporal.metrics import increment_credential_refresh
from products.tasks.backend.temporal.observability import log_activity_execution, track_event
from products.tasks.backend.temporal.process_task.sandbox_credentials import (
DEFAULT_REFRESH_INTERVAL_SECONDS,
@@ -95,7 +96,9 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
run_id=ctx.run_id,
exc_info=True,
)
+ increment_credential_refresh(credential.kind, "failed")
continue
+ increment_credential_refresh(credential.kind, "refreshed" if outcome.refreshed else "skipped")
intervals.append(outcome.next_refresh_seconds)
if outcome.refreshed:
refreshed_kinds.append(outcome.kind)