: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): capture cloud rtk savings (#70086)
Alessandro Pogliaghi86575b294923
diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 53dabd2eb71f..5d0aff13623e 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -227,6 +227,18 @@ class SandboxBase(ABC):@abstractmethoddef write_file(self, path: str, payload: bytes) -> ExecutionResult: ...+ def stop_agent_server(self) -> ExecutionResult:+ """Stop the agent server gracefully so it can flush terminal events."""+ return self.execute(+ "pkill -TERM -f '[a]gent-server' 2>/dev/null || true; "+ "for _ in $(seq 1 80); do "+ "pgrep -f '[a]gent-server' >/dev/null || exit 0; "+ "sleep 0.5; "+ "done; "+ "exit 1",+ timeout_seconds=45,+ )+def agent_server_supports_auto_publish(self) -> bool:"""Sandboxes restored from old snapshots can carry an agent-server that rejects unknownCLI options, so probe the installed binary before passing --autoPublish; unsupporteddiff --git a/products/tasks/backend/logic/stream/event_ingest.py b/products/tasks/backend/logic/stream/event_ingest.pyindex 4e243bb18ced..151c9ac6d56f 100644--- a/products/tasks/backend/logic/stream/event_ingest.py+++ b/products/tasks/backend/logic/stream/event_ingest.py@@ -2,9 +2,11 @@ from __future__ import annotationsimport reimport json+import mathfrom collections.abc import AsyncGenerator, Awaitable, Callablefrom dataclasses import dataclassfrom typing import cast+from uuid import NAMESPACE_URL, uuid5from django.conf import settingsfrom django.db import InterfaceError, OperationalError, close_old_connections@@ -14,6 +16,8 @@ import posthoganalyticsfrom asgiref.sync import sync_to_asyncfrom jwt import PyJWTError+from posthog.ph_client import ph_scoped_capture+from products.tasks.backend.constants import STREAM_VIA_PROXY_FEATURE_FLAGfrom products.tasks.backend.logic.services.connection_token import (SandboxEventIngestTokenPayload,@@ -41,6 +45,8 @@ MAX_EVENT_LINE_BYTES = 1_000_000MAX_REQUEST_BYTES = 5_000_000MAX_EVENTS_PER_REQUEST = 1_000STREAM_COMPLETE_CONTROL_TYPE = "_posthog/stream_complete"+RTK_SAVINGS_SIDE_EFFECT = "rtk-savings"+RTK_SAVINGS_CAPTURE_LOCK_SECONDS = 60ASGIMessage = dict[str, object]ASGIReceive = Callable[[], Awaitable[ASGIMessage]]@@ -61,6 +67,10 @@ class EventIngestPayloadTooLarge(Exception):self.last_accepted_seq = last_accepted_seq+class EventIngestCaptureError(Exception):+ pass++class EventIngestHTTPError(Exception):def __init__(self, status_code: int, payload: dict):super().__init__(payload.get("error", "Event ingest request failed"))@@ -121,7 +131,7 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,try:result = await _ingest_event_lines(redis_stream,- claims.run_id,+ claims,receive,)except ClientDisconnected:@@ -133,6 +143,9 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,except EventIngestPayloadTooLarge as error:await _send_json(send, 413, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})return True+ except EventIngestCaptureError:+ await _send_json(send, 503, {"error": "Failed to capture RTK savings; retry the request"})+ return Trueexcept TaskRunStreamSequenceGap as error:await _send_json(send, 409, {"error": str(error), "last_accepted_seq": error.last_accepted_seq})return True@@ -157,7 +170,7 @@ async def handle_task_run_event_ingest(scope: ASGIMessage, receive: ASGIReceive,async def _ingest_event_lines(redis_stream: TaskRunRedisStream,- run_id: str,+ claims: SandboxEventIngestTokenPayload,receive: ASGIReceive,) -> EventIngestResult:result = EventIngestResult(last_accepted_seq=await redis_stream.get_last_sequence())@@ -182,7 +195,13 @@ async def _ingest_event_lines(sequence = parsed_line.sequenceevent = parsed_line.event- stream_id = await redis_stream.write_event_with_sequence(event, sequence)+ rtk_savings_properties = _parse_rtk_savings_properties(claims, event)+ stream_id = await redis_stream.write_event_with_sequence(+ event,+ sequence,+ pending_side_effect=RTK_SAVINGS_SIDE_EFFECT if rtk_savings_properties is not None else None,+ )+ await _capture_rtk_savings_if_needed(redis_stream, claims, sequence, rtk_savings_properties)if stream_id is None:result.duplicate += 1result.last_accepted_seq = max(result.last_accepted_seq, await redis_stream.get_last_sequence())@@ -190,7 +209,7 @@ async def _ingest_event_lines(result.accepted += 1result.last_accepted_seq = sequence- await _heartbeat_workflow_if_needed(redis_stream, run_id, event)+ await _heartbeat_workflow_if_needed(redis_stream, claims.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@@ -202,6 +221,83 @@ async def _ingest_event_lines(return result+async def _capture_rtk_savings_if_needed(+ redis_stream: TaskRunRedisStream,+ claims: SandboxEventIngestTokenPayload,+ sequence: int,+ properties: dict[str, str | int] | None,+) -> None:+ if properties is None:+ return+ capture_claim = await redis_stream.claim_pending_side_effect(+ RTK_SAVINGS_SIDE_EFFECT, sequence, RTK_SAVINGS_CAPTURE_LOCK_SECONDS+ )+ if capture_claim is None:+ return+ if not capture_claim:+ return++ try:+ event_uuid = str(uuid5(NAMESPACE_URL, f"posthog-task-rtk-savings:{claims.run_id}:{sequence}"))+ await sync_to_async(_capture_rtk_savings, thread_sensitive=False)(claims.team_id, event_uuid, properties)+ except Exception as error:+ await redis_stream.release_pending_side_effect(RTK_SAVINGS_SIDE_EFFECT, sequence)+ logger.warning("task_run_rtk_savings_capture_failed", run_id=claims.run_id, exc_info=True)+ raise EventIngestCaptureError from error+ await redis_stream.complete_pending_side_effect(RTK_SAVINGS_SIDE_EFFECT, sequence)+++def _capture_rtk_savings(team_id: int, event_uuid: str, properties: dict[str, str | int]) -> None:+ with ph_scoped_capture() as capture:+ capture(+ distinct_id=f"team_{team_id}",+ event="rtk savings",+ properties=properties,+ uuid=event_uuid,+ )+++def _parse_rtk_savings_properties(claims: SandboxEventIngestTokenPayload, event: dict) -> dict[str, str | int] | None:+ notification = event.get("notification")+ if not isinstance(notification, dict) or notification.get("method") != "_posthog/rtk_savings":+ return None++ params = notification.get("params")+ if not isinstance(params, dict):+ return None++ counters: dict[str, int] = {}+ for key in (+ "cumulative_commands",+ "cumulative_input_tokens",+ "cumulative_output_tokens",+ "cumulative_tokens_saved",+ ):+ value = params.get(key)+ if (+ isinstance(value, bool)+ or not isinstance(value, (int, float))+ or (isinstance(value, float) and (not math.isfinite(value) or not value.is_integer()))+ or value < 0+ ):+ return None+ counters[key] = int(value)++ properties: dict[str, str | int] = {+ "team_id": claims.team_id,+ "task_id": claims.task_id,+ "run_id": claims.run_id,+ "counter_id": claims.run_id,+ **counters,+ }+ for key in ("runtime_adapter", "model"):+ value = params.get(key)+ if isinstance(value, str) and value:+ properties[key] = value++ return properties++async def _iter_request_lines(receive: ASGIReceive) -> AsyncGenerator[str]:"""Yield NDJSON request lines with bounded event-loop work per request."""buffer = b""diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.pyindex c4635e373faa..1ada3fa24402 100644--- a/products/tasks/backend/logic/stream/redis_stream.py+++ b/products/tasks/backend/logic/stream/redis_stream.py@@ -105,6 +105,14 @@ def get_task_run_stream_heartbeat_key(stream_key: str) -> str:return f"{stream_key}:ingest-heartbeat"+def get_task_run_stream_side_effect_pending_key(stream_key: str, side_effect: str, sequence: int) -> str:+ return f"{stream_key}:side-effect:{side_effect}:{sequence}:pending"+++def get_task_run_stream_side_effect_lock_key(stream_key: str, side_effect: str, sequence: int) -> str:+ return f"{stream_key}:side-effect:{side_effect}:{sequence}:lock"++class TaskRunRedisStream:"""Manages task run event streaming via Redis streams.@@ -320,7 +328,31 @@ class TaskRunRedisStream:)return bool(claimed)- async def write_event_with_sequence(self, event: dict, sequence: int) -> str | None:+ async def claim_pending_side_effect(self, side_effect: str, sequence: int, lock_seconds: int) -> bool | None:+ pending_key = get_task_run_stream_side_effect_pending_key(self._stream_key, side_effect, sequence)+ lock_key = get_task_run_stream_side_effect_lock_key(self._stream_key, side_effect, sequence)+ if not await self._redis_client.exists(pending_key):+ return None+ claimed = await self._redis_client.set(lock_key, "1", ex=lock_seconds, nx=True)+ if not claimed:+ return False+ if await self._redis_client.exists(pending_key):+ return True+ await self._redis_client.delete(lock_key)+ return None++ async def complete_pending_side_effect(self, side_effect: str, sequence: int) -> None:+ pending_key = get_task_run_stream_side_effect_pending_key(self._stream_key, side_effect, sequence)+ lock_key = get_task_run_stream_side_effect_lock_key(self._stream_key, side_effect, sequence)+ await self._redis_client.delete(pending_key, lock_key)++ async def release_pending_side_effect(self, side_effect: str, sequence: int) -> None:+ lock_key = get_task_run_stream_side_effect_lock_key(self._stream_key, side_effect, sequence)+ await self._redis_client.delete(lock_key)++ async def write_event_with_sequence(+ self, event: dict, sequence: int, *, pending_side_effect: str | None = None+ ) -> str | None:"""Write an event if it is the next unseen sequence number.Sequences must start at 1; sequence 0 is the initial sentinel and is@@ -329,10 +361,15 @@ class TaskRunRedisStream:duplicate sequence that was already accepted on an earlier connection."""if settings.TEST:- return await self._write_event_with_sequence_for_tests(event, sequence)+ return await self._write_event_with_sequence_for_tests(event, sequence, pending_side_effect)sequence_key = get_task_run_stream_sequence_key(self._stream_key)completed_key = get_task_run_stream_completed_key(self._stream_key)+ pending_side_effect_key = (+ get_task_run_stream_side_effect_pending_key(self._stream_key, pending_side_effect, sequence)+ if pending_side_effect is not None+ else None+ )raw = json.dumps(event)while True:@@ -363,12 +400,16 @@ class TaskRunRedisStream:)pipe.expire(self._stream_key, self._timeout)pipe.set(sequence_key, sequence, ex=self._sequence_timeout)+ if pending_side_effect_key is not None:+ pipe.set(pending_side_effect_key, "1", ex=self._sequence_timeout)results = await pipe.execute()return _normalize_stream_id(results[0])except redis_exceptions.WatchError:continue- async def _write_event_with_sequence_for_tests(self, event: dict, sequence: int) -> str | None:+ async def _write_event_with_sequence_for_tests(+ self, event: dict, sequence: int, pending_side_effect: str | None = None+ ) -> 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)@@ -389,6 +430,9 @@ class TaskRunRedisStream:stream_id = await self.write_event(event)await self._redis_client.set(sequence_key, sequence, ex=self._sequence_timeout)+ if pending_side_effect is not None:+ pending_key = get_task_run_stream_side_effect_pending_key(self._stream_key, pending_side_effect, sequence)+ await self._redis_client.set(pending_key, "1", ex=self._sequence_timeout)return stream_idasync def mark_complete(self) -> None:diff --git a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.pyindex 0f83cc145406..d2b15f92fd07 100644--- a/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/cleanup_sandbox.py@@ -40,6 +40,21 @@ def cleanup_sandbox(input: CleanupSandboxInput) -> None:sandbox = Noneif sandbox is not None:+ if input.complete_stream_on_cleanup:+ try:+ stop_result = sandbox.stop_agent_server()+ if stop_result.exit_code != 0:+ logger.warning(+ "cleanup_sandbox_agent_server_shutdown_timed_out",+ extra={"sandbox_id": input.sandbox_id},+ )+ except Exception:+ logger.warning(+ "cleanup_sandbox_agent_server_shutdown_failed",+ extra={"sandbox_id": input.sandbox_id},+ exc_info=True,+ )+try:sandbox.destroy()stream_completion_safe = Truediff --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.pyindex 07a6fdf795fc..860d95718039 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@@ -26,8 +26,9 @@ def test_cleanup_sandbox_skips_agent_server_shutdown_for_regular_cleanup(activit@pytest.mark.django_db-def test_cleanup_sandbox_does_not_request_agent_server_shutdown_when_completing_stream(activity_environment, mocker):+def test_cleanup_sandbox_requests_agent_server_shutdown_when_completing_stream(activity_environment, mocker):sandbox = mocker.Mock(id="sandbox-123")+ sandbox.stop_agent_server.return_value.exit_code = 0get_by_id = mocker.patch.object(Sandbox, "get_by_id", return_value=sandbox)async_to_sync(activity_environment.run)(@@ -36,6 +37,7 @@ def test_cleanup_sandbox_does_not_request_agent_server_shutdown_when_completing_)get_by_id.assert_called_once_with("sandbox-123")+ sandbox.stop_agent_server.assert_called_once_with()sandbox.execute.assert_not_called()sandbox.destroy.assert_called_once_with()diff --git a/products/tasks/backend/tests/test_event_ingest.py b/products/tasks/backend/tests/test_event_ingest.pyindex b2be80084c9b..15c92daa2263 100644--- a/products/tasks/backend/tests/test_event_ingest.py+++ b/products/tasks/backend/tests/test_event_ingest.py@@ -2,6 +2,7 @@ import jsonimport asyncioimport threadingfrom collections.abc import Sequence+from uuid import NAMESPACE_URL, uuid5from unittest.mock import patch@@ -188,6 +189,113 @@ class TestTaskRunEventIngest(TestCase):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_rtk_savings_capture_uses_authenticated_ids_and_idempotent_event_uuid(self) -> None:+ token = self._create_token()+ event = {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {+ "method": "_posthog/rtk_savings",+ "params": {+ "task_id": "spoofed-task",+ "run_id": "spoofed-run",+ "team_id": 999,+ "counter_id": "spoofed-counter",+ "runtime_adapter": "claude",+ "model": "claude-sonnet-4-5",+ "cumulative_commands": 4,+ "cumulative_input_tokens": 1000,+ "cumulative_output_tokens": 350,+ "cumulative_tokens_saved": 650,+ },+ },+ },+ }++ with patch("products.tasks.backend.logic.stream.event_ingest._capture_rtk_savings") as capture_rtk_savings:+ first_status, _ = self._call_ingest(token, [event])+ duplicate_status, duplicate_body = self._call_ingest(token, [event])++ self.assertEqual(first_status, 200)+ self.assertEqual(duplicate_status, 200)+ self.assertEqual(duplicate_body["duplicate"], 1)+ capture_rtk_savings.assert_called_once_with(+ self.team.id,+ str(uuid5(NAMESPACE_URL, f"posthog-task-rtk-savings:{self.task_run.id}:1")),+ {+ "team_id": self.team.id,+ "task_id": str(self.task.id),+ "run_id": str(self.task_run.id),+ "counter_id": str(self.task_run.id),+ "runtime_adapter": "claude",+ "model": "claude-sonnet-4-5",+ "cumulative_commands": 4,+ "cumulative_input_tokens": 1000,+ "cumulative_output_tokens": 350,+ "cumulative_tokens_saved": 650,+ },+ )++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_rtk_savings_capture_failure_can_be_retried(self) -> None:+ token = self._create_token()+ event = {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {+ "method": "_posthog/rtk_savings",+ "params": {+ "cumulative_commands": 4,+ "cumulative_input_tokens": 1000,+ "cumulative_output_tokens": 350,+ "cumulative_tokens_saved": 650,+ },+ },+ },+ }++ with patch(+ "products.tasks.backend.logic.stream.event_ingest._capture_rtk_savings",+ side_effect=[RuntimeError("capture failed"), None],+ ) as capture_rtk_savings:+ failed_status, _ = self._call_ingest(token, [event])+ retry_status, retry_body = self._call_ingest(token, [event])++ self.assertEqual(failed_status, 503)+ self.assertEqual(retry_status, 200)+ self.assertEqual(retry_body["duplicate"], 1)+ self.assertEqual(capture_rtk_savings.call_count, 2)+ self.assertEqual(self._read_notification_methods(), ["_posthog/rtk_savings"])++ @override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)+ def test_rtk_savings_capture_rejects_fractional_counters(self) -> None:+ token = self._create_token()+ event = {+ "seq": 1,+ "event": {+ "type": "notification",+ "notification": {+ "method": "_posthog/rtk_savings",+ "params": {+ "cumulative_commands": 1.5,+ "cumulative_input_tokens": 1000,+ "cumulative_output_tokens": 350,+ "cumulative_tokens_saved": 650,+ },+ },+ },+ }++ with patch("products.tasks.backend.logic.stream.event_ingest._capture_rtk_savings") as capture_rtk_savings:+ status, body = self._call_ingest(token, [event])++ self.assertEqual(status, 200)+ self.assertEqual(body["accepted"], 1)+ capture_rtk_savings.assert_not_called()+@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()