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.

refactor(tasks): split the agent-proxy callback into parsing and dispatch (#113844)

Alessandro Pogliaghiad91134c073e
diff --git a/products/tasks/backend/agent_proxy_callback.py b/products/tasks/backend/agent_proxy_callback.py
index 686ad8ff7c53..b2f19f988d46 100644
--- a/products/tasks/backend/agent_proxy_callback.py
+++ b/products/tasks/backend/agent_proxy_callback.py
@@ -1,13 +1,16 @@
import hmac
import json
import logging
+from typing import TYPE_CHECKING, Any, Literal
from django.conf import settings
-from django.http import JsonResponse
+from django.http import HttpRequest, JsonResponse
from drf_spectacular.utils import OpenApiResponse, extend_schema
from jwt import PyJWTError
+from posthog.dataclasses import frozen
+
from products.tasks.backend.facade.api import signal_workflow_completion
from products.tasks.backend.logic.services.process_killed import (
PROCESS_KILLED_EVENT,
@@ -27,8 +30,209 @@ from products.tasks.backend.turn_completed import dispatch_turn_completed
from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
+if TYPE_CHECKING:
+ from products.tasks.backend.logic.services.connection_token import SandboxEventIngestTokenPayload
+
logger = logging.getLogger(__name__)
+AgentBootMilestone = Literal["agent_command_dispatched", "agent_activity_observed"]
+
+RETRYABLE_KINDS = frozenset({"budget_steer", "process_killed"})
+
+
+class CallbackRejected(Exception):
+ def __init__(self, status: int, error: str, **extra: Any) -> None:
+ super().__init__(error)
+ self.status = status
+ self.payload: dict[str, Any] = {"error": error, **extra}
+
+ def response(self) -> JsonResponse:
+ return JsonResponse(self.payload, status=self.status)
+
+
+@frozen
+class CallbackOutcome:
+ dispatched: bool = False
+ status: int = 200
+ error: str | None = None
+
+ def response(self) -> JsonResponse:
+ if self.error is not None:
+ return JsonResponse({"error": self.error}, status=self.status)
+ payload = AgentProxyCallbackResponseSerializer({"dispatched": self.dispatched}).data
+ return JsonResponse(payload, status=self.status)
+
+
+@frozen
+class CallbackRequest:
+ run_id: str
+ claims: "SandboxEventIngestTokenPayload"
+ body: dict[str, Any]
+ data: dict[str, Any]
+
+ @classmethod
+ def from_request(cls, request: HttpRequest, run_id: str) -> "CallbackRequest":
+ if request.method != "POST":
+ raise CallbackRejected(405, "Method not allowed")
+ claims = cls._authenticate(request, run_id)
+ cls._check_proxy_secret(request)
+ body = cls._parse_json(request)
+ data = cls._validate(body)
+ if data["task_id"] != claims.task_id or data["team_id"] != claims.team_id:
+ raise CallbackRejected(403, "Token claims do not match request body")
+ return cls(run_id=run_id, claims=claims, body=body, data=data)
+
+ @staticmethod
+ def _authenticate(request: HttpRequest, run_id: str) -> "SandboxEventIngestTokenPayload":
+ from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the import path
+ validate_sandbox_event_ingest_token,
+ )
+
+ authorization = request.headers.get("Authorization", "")
+ if not authorization.startswith("Bearer "):
+ raise CallbackRejected(401, "Missing authorization bearer token")
+ token = authorization[len("Bearer ") :].strip()
+ if not token:
+ raise CallbackRejected(401, "Missing authorization bearer token")
+ try:
+ claims = validate_sandbox_event_ingest_token(token)
+ except PyJWTError as exc:
+ raise CallbackRejected(401, "Invalid event ingest token", code=exc.__class__.__name__) from exc
+ if claims.run_id != run_id:
+ raise CallbackRejected(403, "Token does not match task run")
+ return claims
+
+ @staticmethod
+ def _check_proxy_secret(request: HttpRequest) -> None:
+ # The event-ingest JWT is also held by the sandbox, so the JWT alone does not prove the caller
+ # is the agent-proxy. Require the shared secret so a sandbox cannot drive this callback directly
+ # (bypassing the proxy's Redis sequencing/throttle). An unset secret fails closed except in
+ # local dev/test, where no proxy deployment exists to share a secret with.
+ expected_secret = settings.AGENT_PROXY_CALLBACK_SECRET
+ if expected_secret:
+ provided_secret = request.headers.get("X-Agent-Proxy-Secret", "")
+ if not hmac.compare_digest(provided_secret, expected_secret):
+ raise CallbackRejected(403, "Invalid agent-proxy callback secret")
+ elif not (settings.DEBUG or settings.TEST):
+ raise CallbackRejected(403, "Agent-proxy callback secret is not configured")
+
+ @staticmethod
+ def _parse_json(request: HttpRequest) -> dict[str, Any]:
+ try:
+ return json.loads(request.body)
+ except (json.JSONDecodeError, ValueError):
+ raise CallbackRejected(400, "Invalid JSON body") from None
+
+ @staticmethod
+ def _validate(body: dict[str, Any]) -> dict[str, Any]:
+ serializer = AgentProxyCallbackRequestSerializer(data=body)
+ if not serializer.is_valid():
+ raise CallbackRejected(400, "Invalid request body", detail=serializer.errors)
+ return serializer.validated_data
+
+
+class AgentProxyCallbackDispatcher:
+ def __init__(self, callback: CallbackRequest) -> None:
+ self.callback = callback
+ self.run_id = callback.run_id
+ self.task_id: str = callback.data["task_id"]
+ self.team_id: int = callback.data["team_id"]
+ self.kind: str = callback.data["kind"]
+
+ def dispatch(self) -> CallbackOutcome:
+ try:
+ return self._dispatch_kind()
+ except Exception:
+ logger.exception(
+ f"agent_proxy_callback.{self.kind}_failed", extra={"run_id": self.run_id, "kind": self.kind}
+ )
+ return CallbackOutcome(status=503) if self.kind in RETRYABLE_KINDS else CallbackOutcome()
+
+ def _dispatch_kind(self) -> CallbackOutcome:
+ match self.kind:
+ case "heartbeat":
+ return self._heartbeat()
+ case "command_dispatched":
+ return self._boot_milestone("agent_command_dispatched")
+ case "agent_activity":
+ return self._boot_milestone("agent_activity_observed")
+ case "awaiting_input":
+ return self._awaiting_input()
+ case "turn_failed":
+ return self._turn_failed()
+ case "budget_steer":
+ return self._budget_steer()
+ case "process_killed":
+ return self._process_killed()
+ return CallbackOutcome()
+
+ def _load_run(self, *related: str) -> TaskRun | None:
+ queryset = TaskRun.objects.select_related(*related) if related else TaskRun.objects.all()
+ try:
+ return queryset.get(id=self.run_id, task_id=self.task_id, team_id=self.team_id)
+ except TaskRun.DoesNotExist:
+ logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": self.run_id})
+ return None
+
+ def _heartbeat(self) -> CallbackOutcome:
+ if not self.callback.data["agent_active"]:
+ return CallbackOutcome()
+ task_run = self._load_run()
+ if task_run is None:
+ return CallbackOutcome()
+ task_run.heartbeat_workflow(agent_active=True, force=self.callback.data["activity_started"])
+ return CallbackOutcome(dispatched=True)
+
+ def _boot_milestone(self, milestone: AgentBootMilestone) -> CallbackOutcome:
+ task_run = self._load_run()
+ if task_run is None:
+ return CallbackOutcome()
+ return CallbackOutcome(dispatched=task_run.signal_agent_boot_milestone(milestone))
+
+ def _awaiting_input(self) -> CallbackOutcome:
+ # The push dispatcher reads task.created_by; prefetch it so the dispatch stays one query.
+ task_run = self._load_run("task__created_by")
+ if task_run is None:
+ return CallbackOutcome()
+ task_run.signal_agent_turn_completed(succeeded=self.callback.data["turn_succeeded"])
+ dispatched = dispatch_turn_completed(task_run, turn_completed=self.callback.data["turn_completed"])
+ return CallbackOutcome(dispatched=dispatched)
+
+ def _turn_failed(self) -> CallbackOutcome:
+ if self._load_run() is None:
+ return CallbackOutcome()
+ signal_workflow_completion(self.run_id, "failed", PI_RUNTIME_ERROR_MESSAGE)
+ return CallbackOutcome(dispatched=True)
+
+ def _budget_steer(self) -> CallbackOutcome:
+ properties = _parse_budget_steer_properties(
+ self.callback.claims, {"notification": {"method": "_posthog/budget_steer", "params": self.callback.body}}
+ )
+ sequence = self.callback.data.get("sequence")
+ if sequence is None or properties is None:
+ return CallbackOutcome(status=400, error="Invalid budget steer")
+ BudgetSteerCapture.enqueue(self.team_id, self.run_id, sequence, properties, self.callback.body.get("timestamp"))
+ return CallbackOutcome(dispatched=True)
+
+ def _process_killed(self) -> CallbackOutcome:
+ sequence = self.callback.data.get("sequence")
+ killed = self.callback.data.get("process_killed")
+ if sequence is None or killed is None:
+ return CallbackOutcome(status=400, error="Invalid process kill")
+ task_run = self._load_run("task__created_by", "team")
+ if task_run is None:
+ return CallbackOutcome()
+ notice = ProcessKilledNotice(**killed)
+ captured = task_run.capture_event(
+ PROCESS_KILLED_EVENT,
+ notice.analytics_properties(),
+ event_uuid=process_killed_event_uuid(self.run_id, sequence),
+ )
+ if not captured:
+ return CallbackOutcome(status=503)
+ observe_sandbox_process_killed()
+ return CallbackOutcome(dispatched=True)
+
# ---------------------------------------------------------------------------
# Internal agent-proxy callback (not a DRF viewset action — no team scoping,
@@ -63,150 +267,8 @@ logger = logging.getLogger(__name__)
),
)
def agent_proxy_callback(request, run_id: str) -> JsonResponse:
- """Handle side-effect callbacks from the Node agent-proxy service.
-
- Auth: sandbox event ingest JWT forwarded from the Node service as a Bearer token.
- The JWT already carries run_id, task_id, team_id — body fields are validated
- against the JWT claims to prevent cross-run confusion.
- """
- from products.tasks.backend.logic.services.connection_token import ( # noqa: PLC0415 — keep sandbox deps off the import path
- validate_sandbox_event_ingest_token,
- )
-
- if request.method != "POST":
- return JsonResponse({"error": "Method not allowed"}, status=405)
-
- # Extract and validate the Bearer token
- authorization = request.headers.get("Authorization", "")
- if not authorization.startswith("Bearer "):
- return JsonResponse({"error": "Missing authorization bearer token"}, status=401)
- token = authorization[len("Bearer ") :].strip()
- if not token:
- return JsonResponse({"error": "Missing authorization bearer token"}, status=401)
-
- try:
- claims = validate_sandbox_event_ingest_token(token)
- except PyJWTError as exc:
- return JsonResponse({"error": "Invalid event ingest token", "code": exc.__class__.__name__}, status=401)
-
- # JWT run_id must match URL parameter
- if claims.run_id != run_id:
- return JsonResponse({"error": "Token does not match task run"}, status=403)
-
- # Service-to-service guard: the event-ingest JWT is also held by the sandbox, so the JWT alone
- # does not prove the caller is the agent-proxy. Require the shared secret so a sandbox cannot
- # drive this callback directly (bypassing the proxy's Redis sequencing/throttle). An unset
- # secret fails closed — the endpoint stays dead until the secret is provisioned — except in
- # local dev/test where no proxy deployment exists to share a secret with.
- expected_secret = settings.AGENT_PROXY_CALLBACK_SECRET
- if expected_secret:
- provided_secret = request.headers.get("X-Agent-Proxy-Secret", "")
- if not hmac.compare_digest(provided_secret, expected_secret):
- return JsonResponse({"error": "Invalid agent-proxy callback secret"}, status=403)
- elif not (settings.DEBUG or settings.TEST):
- return JsonResponse({"error": "Agent-proxy callback secret is not configured"}, status=403)
-
- # Validate and parse the request body
try:
- body = json.loads(request.body)
- except (json.JSONDecodeError, ValueError):
- return JsonResponse({"error": "Invalid JSON body"}, status=400)
-
- serializer = AgentProxyCallbackRequestSerializer(data=body)
- if not serializer.is_valid():
- return JsonResponse({"error": "Invalid request body", "detail": serializer.errors}, status=400)
-
- data = serializer.validated_data
- kind: str = data["kind"]
- task_id: str = data["task_id"]
- team_id: int = data["team_id"]
- agent_active: bool = data["agent_active"]
-
- # Body claims must match JWT claims to prevent cross-run confusion
- if task_id != claims.task_id or team_id != claims.team_id:
- return JsonResponse({"error": "Token claims do not match request body"}, status=403)
-
- dispatched = False
-
- if kind == "heartbeat" and agent_active:
- try:
- task_run = TaskRun.objects.get(id=run_id, task_id=task_id, team_id=team_id)
- task_run.heartbeat_workflow(agent_active=True, force=data["activity_started"])
- dispatched = True
- except TaskRun.DoesNotExist:
- logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
- except Exception:
- logger.exception("agent_proxy_callback.heartbeat_failed", extra={"run_id": run_id})
-
- elif kind in {"command_dispatched", "agent_activity"}:
- try:
- task_run = TaskRun.objects.get(id=run_id, task_id=task_id, team_id=team_id)
- if kind == "command_dispatched":
- dispatched = task_run.signal_agent_boot_milestone("agent_command_dispatched")
- else:
- dispatched = task_run.signal_agent_boot_milestone("agent_activity_observed")
- except TaskRun.DoesNotExist:
- logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
- except Exception:
- logger.exception("agent_proxy_callback.milestone_failed", extra={"run_id": run_id, "kind": kind})
-
- elif kind == "awaiting_input":
- try:
- # The push dispatcher reads task.created_by; prefetch it so the dispatch stays one query.
- task_run = TaskRun.objects.select_related("task__created_by").get(
- id=run_id, task_id=task_id, team_id=team_id
- )
- task_run.signal_agent_turn_completed(succeeded=data["turn_succeeded"])
- dispatched = dispatch_turn_completed(task_run, turn_completed=data["turn_completed"])
- except TaskRun.DoesNotExist:
- logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
- except Exception:
- logger.exception("agent_proxy_callback.awaiting_input_failed", extra={"run_id": run_id})
-
- elif kind == "turn_failed":
- try:
- if TaskRun.objects.filter(id=run_id, task_id=task_id, team_id=team_id).exists():
- signal_workflow_completion(run_id, "failed", PI_RUNTIME_ERROR_MESSAGE)
- dispatched = True
- else:
- logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
- except Exception:
- logger.exception("agent_proxy_callback.turn_failed_failed", extra={"run_id": run_id})
-
- elif kind == "budget_steer":
- properties = _parse_budget_steer_properties(
- claims, {"notification": {"method": "_posthog/budget_steer", "params": body}}
- )
- sequence = data.get("sequence")
- if sequence is None or properties is None:
- return JsonResponse({"error": "Invalid budget steer"}, status=400)
- try:
- BudgetSteerCapture.enqueue(team_id, run_id, sequence, properties, body.get("timestamp"))
- dispatched = True
- except Exception:
- logger.exception("agent_proxy_callback.budget_steer_failed", extra={"run_id": run_id})
- return JsonResponse({"dispatched": False}, status=503)
-
- elif kind == "process_killed":
- sequence = data.get("sequence")
- killed = data.get("process_killed")
- if sequence is None or killed is None:
- return JsonResponse({"error": "Invalid process kill"}, status=400)
- notice = ProcessKilledNotice(**killed)
- try:
- task_run = TaskRun.objects.select_related("task__created_by", "team").get(
- id=run_id, task_id=task_id, team_id=team_id
- )
- except TaskRun.DoesNotExist:
- logger.warning("agent_proxy_callback.run_not_found", extra={"run_id": run_id})
- else:
- dispatched = task_run.capture_event(
- PROCESS_KILLED_EVENT,
- notice.analytics_properties(),
- event_uuid=process_killed_event_uuid(run_id, sequence),
- )
- if not dispatched:
- return JsonResponse({"dispatched": False}, status=503)
- observe_sandbox_process_killed()
-
- return JsonResponse(AgentProxyCallbackResponseSerializer({"dispatched": dispatched}).data)
+ callback = CallbackRequest.from_request(request, run_id)
+ except CallbackRejected as rejection:
+ return rejection.response()
+ return AgentProxyCallbackDispatcher(callback).dispatch().response()
diff --git a/products/tasks/backend/tests/test_agent_proxy_callback.py b/products/tasks/backend/tests/test_agent_proxy_callback.py
index e59c132b717a..6966b9213fc4 100644
--- a/products/tasks/backend/tests/test_agent_proxy_callback.py
+++ b/products/tasks/backend/tests/test_agent_proxy_callback.py
@@ -20,6 +20,14 @@ from products.tasks.backend.tests.test_api import TEST_RSA_PRIVATE_KEY
from ee.hogai.sandbox import PI_RUNTIME_ERROR_MESSAGE
+PROCESS_KILLED = {
+ "comm": "bash",
+ "signal": "SIGTERM",
+ "tree_rss_bytes": 12 * 1024**3,
+ "memory_current_bytes": 14 * 1024**3,
+ "memory_limit_bytes": 16 * 1024**3,
+}
+
@override_settings(SANDBOX_JWT_PRIVATE_KEY=TEST_RSA_PRIVATE_KEY)
class TestAgentProxyCallback(TestCase):
@@ -234,13 +242,7 @@ class TestAgentProxyCallback(TestCase):
expected_status: int,
expected_count: int,
) -> None:
- killed = {
- "comm": "bash",
- "signal": "SIGTERM",
- "tree_rss_bytes": 12 * 1024**3,
- "memory_current_bytes": 14 * 1024**3,
- "memory_limit_bytes": 16 * 1024**3,
- }
+ killed = dict(PROCESS_KILLED)
if isinstance(overrides.get("process_killed"), dict):
killed.update(overrides["process_killed"])
body = self._body(kind="process_killed", agent_active=False, sequence=5, process_killed=killed)
@@ -362,7 +364,17 @@ class TestAgentProxyCallback(TestCase):
self.assertTrue(response.json()["dispatched"])
signal_workflow_completion.assert_called_once_with(str(self.task_run.id), "failed", PI_RUNTIME_ERROR_MESSAGE)
- def test_turn_failed_not_dispatched_for_unknown_run(self) -> None:
+ @parameterized.expand(
+ [
+ ("heartbeat", {"agent_active": True}),
+ ("command_dispatched", {"agent_active": False}),
+ ("agent_activity", {"agent_active": True}),
+ ("awaiting_input", {"agent_active": False}),
+ ("turn_failed", {"agent_active": False}),
+ ("process_killed", {"agent_active": False, "sequence": 5, "process_killed": PROCESS_KILLED}),
+ ]
+ )
+ def test_unknown_run_returns_200_not_dispatched(self, kind: str, overrides: dict[str, Any]) -> None:
run = self.task.create_run()
run_id = str(run.id)
token = self._token(run)
@@ -370,18 +382,26 @@ class TestAgentProxyCallback(TestCase):
with patch(
"products.tasks.backend.agent_proxy_callback.signal_workflow_completion"
) as signal_workflow_completion:
- response = self._post(self._body(kind="turn_failed", agent_active=False), token=token, run_id=run_id)
+ response = self._post(self._body(kind=kind, **overrides), token=token, run_id=run_id)
self.assertEqual(response.status_code, 200)
self.assertFalse(response.json()["dispatched"])
signal_workflow_completion.assert_not_called()
- def test_unknown_run_returns_200_not_dispatched(self) -> None:
- run = self.task.create_run()
- run_id = str(run.id)
- token = self._token(run)
- TaskRun.objects.filter(id=run_id).delete()
- with patch.object(TaskRun, "heartbeat_workflow") as heartbeat:
- response = self._post(self._body(kind="heartbeat", agent_active=True), token=token, run_id=run_id)
- self.assertEqual(response.status_code, 200)
+ @parameterized.expand(
+ [
+ ("heartbeat", {"agent_active": True}, "heartbeat_workflow", 200),
+ (
+ "process_killed",
+ {"agent_active": False, "sequence": 5, "process_killed": PROCESS_KILLED},
+ "capture_event",
+ 503,
+ ),
+ ]
+ )
+ def test_handler_exception_is_logged_not_raised(
+ self, kind: str, overrides: dict[str, Any], method: str, expected_status: int
+ ) -> None:
+ with patch.object(TaskRun, method, side_effect=RuntimeError("down")):
+ response = self._post(self._body(kind=kind, **overrides), token=self._token())
+ self.assertEqual(response.status_code, expected_status)
self.assertFalse(response.json()["dispatched"])
- heartbeat.assert_not_called()