: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
fix(cdp): retry wakes for steps that have not parked yet (#115238)
Tue Haulundd221aed2b131
diff --git a/posthog/plugins/plugin_server_api.py b/posthog/plugins/plugin_server_api.pyindex 4b8aa26316c4..55f4036867b4 100644--- a/posthog/plugins/plugin_server_api.py+++ b/posthog/plugins/plugin_server_api.py@@ -239,7 +239,7 @@ def _mint_step_resume_jwt(team_id: int, origin_key: str) -> str:def resume_workflow_step(team_id: int, origin_key: str, status: str, result: dict) -> requests.Response:"""Wake the parked workflow step that dispatched `origin_key`. 409 means the worker still holds the- job and the caller should retry; every other 2xx outcome is final."""+ job and the caller should retry. A 200 carries the outcome in its body."""return internal_requests.post(CDP_API_URL + f"/api/projects/{team_id}/workflow_steps/resume",json={"origin_key": origin_key, "status": status, "result": result},diff --git a/products/cdp/backend/test/test_workflow_step_resume.py b/products/cdp/backend/test/test_workflow_step_resume.pyindex 086786482e89..999aa8484b7d 100644--- a/products/cdp/backend/test/test_workflow_step_resume.py+++ b/products/cdp/backend/test/test_workflow_step_resume.py@@ -9,7 +9,12 @@ from django.test import override_settingsimport jwtimport requests-from products.cdp.backend.workflow_step_resume import RESULT_BYTE_CAP, RESULT_STRING_CAP, emit_workflow_step_resume+from products.cdp.backend.workflow_step_resume import (+ RESULT_BYTE_CAP,+ RESULT_STRING_CAP,+ WorkflowStepResumeNotTaken,+ emit_workflow_step_resume,+)_PRODUCE = "products.cdp.backend.workflow_step_resume.produce_internal_event"_POST = "posthog.plugins.plugin_server_api.internal_requests.post"@@ -37,7 +42,7 @@ def test_posts_the_wake_with_a_scoped_jwt_and_capped_strings() -> None:assert kwargs["json"] == {"origin_key": "job:step:3","status": "completed",- "result": {"final_message": "x" * RESULT_STRING_CAP, "pr_urls": ["u"]},+ "result": {"final_message": "x" * RESULT_STRING_CAP, "pr_urls": ["u"], "error_message": None},}assert kwargs["timeout"] == 10assert "x-internal-api-secret" not in {key.lower() for key in kwargs["headers"]}@@ -80,13 +85,56 @@ def test_the_wake_falls_back_to_the_internal_event_when_the_api_cannot_take_it(fassert event.properties == {"origin_key": "job:step:3", "status": "completed", "result": {"pr_urls": ["u"]}}-def test_a_wake_the_worker_cannot_take_yet_is_dropped_as_a_duplicate() -> None:- with patch(_POST, return_value=_response(409)), patch(_PRODUCE) as produce:- emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="completed", raise_on_error=True)+def _outcome(outcome: str) -> MagicMock:+ response = _response(200)+ response.json.return_value = {"outcome": outcome}+ return response++ "responses,raise_on_error,attempts,taken",+ [+ ([_response(409), _outcome("delivered")], False, 2, True),+ ([_outcome("stale_key")], False, 1, True),+ ([_outcome("job_missing")], False, 1, True),+ ([_response(409)] * 4, False, 4, True),+ # A caller that retries on its own schedule gets no sleeps here, and learns the wake was not taken.+ ([_response(409)], True, 1, False),+ ],+)+def test_only_a_step_the_worker_still_holds_gets_a_short_retry(responses, raise_on_error, attempts, taken) -> None:+ with (+ patch(_POST, side_effect=responses) as post,+ patch("products.cdp.backend.workflow_step_resume.time.sleep") as sleep,+ patch(_PRODUCE) as produce,+ ):+ if taken:+ emit_workflow_step_resume(+ team_id=7, origin_key="job:step:3", status="completed", raise_on_error=raise_on_error+ )+ else:+ with pytest.raises(WorkflowStepResumeNotTaken):+ emit_workflow_step_resume(+ team_id=7, origin_key="job:step:3", status="completed", raise_on_error=raise_on_error+ )++ assert post.call_count == attempts+ assert sleep.call_count == attempts - 1produce.assert_not_called()+def test_an_undelivered_fallback_event_raises_for_a_caller_that_retries() -> None:+ undelivered = MagicMock()+ undelivered.done.return_value = False+ with (+ override_settings(WORKFLOWS_STEP_RESUME_JWT_SECRETS=[]),+ patch(_PRODUCE, return_value=undelivered),+ patch("products.cdp.backend.workflow_step_resume.flush_internal_events_producer"),+ pytest.raises(WorkflowStepResumeNotTaken),+ ):+ emit_workflow_step_resume(team_id=7, origin_key="job:step:3", status="completed", raise_on_error=True)++def test_a_failed_emit_does_not_raise() -> None:with (patch(_POST, side_effect=requests.ConnectionError("api down")),@@ -102,6 +150,7 @@ def test_a_failed_emit_does_not_raise() -> None:{"final_message": "漢" * 1500, "error_message": "字" * 1500},{"pr_urls": [f"https://example.com/pr/{index}" for index in range(1000)]},{"nested": {"text": '\\"\n' * 1500}, "pr_urls": ["https://example.com/" + "x" * 6000]},+ {"a": "x" * 1500, "b": "y" * 1500, "c": "z" * 1066, "d": None},],)def test_result_fits_the_serialized_byte_budget(result) -> None:diff --git a/products/cdp/backend/workflow_step_resume.py b/products/cdp/backend/workflow_step_resume.pyindex a903263ed715..435ba74da098 100644--- a/products/cdp/backend/workflow_step_resume.py+++ b/products/cdp/backend/workflow_step_resume.py@@ -1,13 +1,20 @@import json-from collections.abc import Mapping+import time+from collections.abc import Mapping, Sequencefrom typing import Any, Literalimport requestsimport structlog+from posthog.kafka_client.client import ProduceResultfrom posthog.plugins.plugin_server_api import WORKFLOWS_STEP_RESUME_JWT_PURPOSE, resume_workflow_step-from products.cdp.backend.internal_events import WORKFLOW_STEP_RESUME_EVENT, InternalEventEvent, produce_internal_event+from products.cdp.backend.internal_events import (+ WORKFLOW_STEP_RESUME_EVENT,+ InternalEventEvent,+ flush_internal_events_producer,+ produce_internal_event,+)logger = structlog.get_logger(__name__)@@ -16,6 +23,9 @@ RESULT_BYTE_CAP = 4096WorkflowStepResumeStatus = Literal["completed", "failed", "cancelled"]+RESUME_RETRY_DELAYS_SECONDS = (1, 2, 4)+RESUME_EVENT_DELIVERY_TIMEOUT_SECONDS = 10+def _json_size(value: Any) -> int:return len(json.dumps(value, ensure_ascii=False, separators=(",", ":")).encode("utf-8"))@@ -37,6 +47,11 @@ def cap_value(value: Any, budget: int) -> Any:available = budget - _json_size({**result, key: None}) + 4if available <= 0:break+ # An explicit null stays, so every answer reaches the step with the same keys.+ if item is None:+ if available >= len("null"):+ result[key] = None+ continuecapped = cap_value(item, available)if capped is not None and _json_size(capped) <= available:result[key] = capped@@ -53,8 +68,14 @@ def cap_value(value: Any, budget: int) -> Any:return value if value is not None and _json_size(value) <= budget else None-def produce_step_resume_event(*, team_id: int, origin_key: str, status: str, result: Mapping[str, Any]) -> None:- produce_internal_event(+class WorkflowStepResumeNotTaken(Exception):+ """The engine still held the step after every retry, or the internal event was not delivered."""+++def produce_step_resume_event(+ *, team_id: int, origin_key: str, status: str, result: Mapping[str, Any]+) -> ProduceResult:+ return produce_internal_event(team_id=team_id,event=InternalEventEvent(event=WORKFLOW_STEP_RESUME_EVENT,@@ -64,6 +85,30 @@ def produce_step_resume_event(*, team_id: int, origin_key: str, status: str, res)+def _post_resume(+ *,+ team_id: int,+ origin_key: str,+ status: WorkflowStepResumeStatus,+ result: dict[str, Any],+ retry_delays: Sequence[float],+) -> bool:+ """POST the wake. False when the worker still held the step on every attempt.++ Only a 409 is retried: the worker holds the job until the step parks. A 200 is final, including+ `stale_key`, which means the step has already moved past this wake.+ """+ for delay in (0, *retry_delays):+ if delay:+ time.sleep(delay)+ response = resume_workflow_step(team_id=team_id, origin_key=origin_key, status=status, result=result)+ if response.status_code != 409:+ response.raise_for_status()+ return True+ logger.info("workflow_step_resume_not_parked", team_id=team_id, origin_key=origin_key)+ return False++def emit_workflow_step_resume(*,team_id: int,@@ -71,23 +116,33 @@ def emit_workflow_step_resume(status: WorkflowStepResumeStatus,result: Mapping[str, Any] | None = None,raise_on_error: bool = False,+ retry_delays: Sequence[float] | None = None,) -> None:- """Wake the step which dispatched `origin_key`: one POST to the engine's API with the key- provisioned, else the `$workflow_step_resume` internal event. A 409 is a duplicate of a wake- already taken, so it is final; `raise_on_error` lets a Temporal activity retry a lost wake."""+ """Wake the step which dispatched `origin_key`: a POST to the engine's API with the key+ provisioned, else the `$workflow_step_resume` internal event. A step that has not parked yet+ gets a few short retries. With `raise_on_error` a wake that is not acknowledged raises instead,+ and the caller retries it on its own schedule, so by default it gets no retries in place."""+ if retry_delays is None:+ retry_delays = () if raise_on_error else RESUME_RETRY_DELAYS_SECONDScapped = cap_value(result or {}, RESULT_BYTE_CAP)try:if WORKFLOWS_STEP_RESUME_JWT_PURPOSE.enabled():try:- response = resume_workflow_step(team_id=team_id, origin_key=origin_key, status=status, result=capped)- if response.status_code == 409:- logger.info("workflow_step_resume_not_parked", team_id=team_id, origin_key=origin_key)+ if _post_resume(+ team_id=team_id, origin_key=origin_key, status=status, result=capped, retry_delays=retry_delays+ ):return- response.raise_for_status()+ if raise_on_error:+ raise WorkflowStepResumeNotTaken(origin_key)returnexcept requests.RequestException:logger.exception("workflow_step_resume_post_failed", team_id=team_id, origin_key=origin_key)- produce_step_resume_event(team_id=team_id, origin_key=origin_key, status=status, result=capped)+ produced = produce_step_resume_event(team_id=team_id, origin_key=origin_key, status=status, result=capped)+ if raise_on_error:+ flush_internal_events_producer(RESUME_EVENT_DELIVERY_TIMEOUT_SECONDS)+ if not produced.done():+ raise WorkflowStepResumeNotTaken(origin_key)+ produced.get(timeout=0)except Exception:logger.exception("workflow_step_resume_emit_failed", team_id=team_id, origin_key=origin_key, status=status)if raise_on_error:diff --git a/products/workflows/backend/presentation/views/workflow_scout_runs.py b/products/workflows/backend/presentation/views/workflow_scout_runs.pyindex b5097832fd4f..385655e6ff49 100644--- a/products/workflows/backend/presentation/views/workflow_scout_runs.py+++ b/products/workflows/backend/presentation/views/workflow_scout_runs.py@@ -4,12 +4,11 @@ from typing import Any, castimport structlogfrom drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsets-from rest_framework.exceptions import AuthenticationFailedfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.auth import InternalAPIUser, ScopedServiceJWTAuthentication+from posthog.auth import InternalAPIUserfrom posthog.redis import get_clientfrom products.signals.backend.facade.api import (@@ -19,6 +18,7 @@ from products.signals.backend.facade.api import ()from products.workflows.backend.facade.api import workflow_existsfrom products.workflows.backend.facade.service_jwt import WORKFLOW_SCOUT_RUN_PURPOSE+from products.workflows.backend.presentation.views.workflow_step_auth import WorkflowStepJWTAuthenticationlogger = structlog.get_logger(__name__)@@ -47,20 +47,9 @@ _REJECTION_STATUS: dict[ScoutRunRejectionKind, int] = {}-class WorkflowScoutRunsJWTAuthentication(ScopedServiceJWTAuthentication):+class WorkflowScoutRunsJWTAuthentication(WorkflowStepJWTAuthentication):purpose = WORKFLOW_SCOUT_RUN_PURPOSE- # nosemgrep: tuple-return-prefer-dataclass -- DRF's (user, auth) authentication contract- def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, Any]:- user, _ = super()._authenticate_claims(request, claims)- # The workflow is identified by the verified token, never by the request body, so a- # token minted for one workflow can't spend another workflow's scout runs.- try:- hog_flow_id = uuid.UUID(str(claims.get("hog_flow_id")))- except ValueError:- raise AuthenticationFailed("Service token is missing its workflow claim.")- return user, hog_flow_id-class WorkflowScoutRunCreateSerializer(serializers.Serializer):skill_name = serializers.CharField(diff --git a/products/workflows/backend/presentation/views/workflow_step_auth.py b/products/workflows/backend/presentation/views/workflow_step_auth.pynew file mode 100644index 000000000000..b122ccf27362--- /dev/null+++ b/products/workflows/backend/presentation/views/workflow_step_auth.py@@ -0,0 +1,21 @@+import uuid+from typing import Any++from rest_framework.exceptions import AuthenticationFailed+from rest_framework.request import Request++from posthog.auth import ScopedServiceJWTAuthentication+++class WorkflowStepJWTAuthentication(ScopedServiceJWTAuthentication):+ """Authenticates a workflow step's call back into Django. Subclasses set `purpose`."""++ # nosemgrep: tuple-return-prefer-dataclass -- DRF's (user, auth) authentication contract+ def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, Any]:+ user, _ = super()._authenticate_claims(request, claims)+ # Read from the verified token, never the body, so one workflow's token can't act for another.+ try:+ hog_flow_id = uuid.UUID(str(claims.get("hog_flow_id")))+ except ValueError:+ raise AuthenticationFailed("Service token is missing its workflow claim.")+ return user, hog_flow_iddiff --git a/products/workflows/backend/presentation/views/workflow_tasks.py b/products/workflows/backend/presentation/views/workflow_tasks.pyindex 117b0b78ce8e..f952e455e972 100644--- a/products/workflows/backend/presentation/views/workflow_tasks.py+++ b/products/workflows/backend/presentation/views/workflow_tasks.py@@ -4,12 +4,11 @@ from typing import Any, castimport structlogfrom drf_spectacular.utils import OpenApiResponse, extend_schemafrom rest_framework import serializers, status, viewsets-from rest_framework.exceptions import AuthenticationFailedfrom rest_framework.permissions import IsAuthenticatedfrom rest_framework.request import Requestfrom rest_framework.response import Response-from posthog.auth import InternalAPIUser, ScopedServiceJWTAuthentication+from posthog.auth import InternalAPIUserfrom posthog.models.team.team import Teamfrom products.tasks.backend.facade.workflow_tasks import (@@ -34,24 +33,14 @@ from products.workflows.backend.facade.api import (get_workflow_task_daily_limits,)from products.workflows.backend.facade.service_jwt import TASKS_CREATE_PURPOSE+from products.workflows.backend.presentation.views.workflow_step_auth import WorkflowStepJWTAuthenticationlogger = structlog.get_logger(__name__)-class WorkflowTasksJWTAuthentication(ScopedServiceJWTAuthentication):+class WorkflowTasksJWTAuthentication(WorkflowStepJWTAuthentication):purpose = TASKS_CREATE_PURPOSE- # nosemgrep: tuple-return-prefer-dataclass -- DRF's (user, auth) authentication contract- def _authenticate_claims(self, request: Request, claims: dict[str, Any]) -> tuple[Any, Any]:- user, _ = super()._authenticate_claims(request, claims)- # The workflow is identified by the verified token, never by the request body, so a- # token minted for one workflow can't create tasks attributed to another.- try:- hog_flow_id = uuid.UUID(str(claims.get("hog_flow_id")))- except ValueError:- raise AuthenticationFailed("Service token is missing its workflow claim.")- return user, hog_flow_id-class WorkflowTaskSlackContextSerializer(serializers.Serializer):integration_id = serializers.IntegerField(diff --git a/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py b/products/workflows/backend/tests/api/test_workflow_scout_runs_api.pyindex da5b16bdadf5..73b6bf0772a9 100644--- a/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py+++ b/products/workflows/backend/tests/api/test_workflow_scout_runs_api.py@@ -17,6 +17,7 @@ from products.signals.backend.facade.api import ScoutRunRejectionKind, WorkflowSfrom products.signals.backend.scout_harness.run_gates import ScoutRunRejectionfrom products.workflows.backend.models import HogFlowfrom products.workflows.backend.presentation.views.workflow_scout_runs import WorkflowScoutRunsJWTAuthentication+from products.workflows.backend.presentation.views.workflow_step_auth import WorkflowStepJWTAuthenticationSECRET = "test-workflow-scout-run-jwt"SCOUT = "signals-scout-error-tracking"@@ -57,7 +58,7 @@ class TestWorkflowScoutRunsAPI(APIBaseTest):HTTP_AUTHORIZATION=f"Bearer {token or _token(self.team.id, str(self.hog_flow.id))}",)- @covers_authentication(WorkflowScoutRunsJWTAuthentication)+ @covers_authentication(WorkflowScoutRunsJWTAuthentication, WorkflowStepJWTAuthentication)def test_dispatches_a_scout_run(self) -> None:started = WorkflowScoutRunStarted(skill_name=SCOUT, workflow_id="signals-scout-workflow-run-1")with patch(_START_SCOUT, return_value=started) as start: