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.

fix(tasks): drop boot milestone signals that arrive before workflow context (#113084)

Alessandro Pogliaghia33d40c16dc0
diff --git a/products/tasks/backend/logic/stream/redis_stream.py b/products/tasks/backend/logic/stream/redis_stream.py
index 9574a4719d8f..674fa88738e2 100644
--- a/products/tasks/backend/logic/stream/redis_stream.py
+++ b/products/tasks/backend/logic/stream/redis_stream.py
@@ -741,6 +741,17 @@ def reset_task_run_stream(run_id: str, use_dedicated: bool = False) -> bool:
return False
+def release_task_run_milestone_claims(run_id: str, use_dedicated: bool = False) -> None:
+ stream_key = get_task_run_stream_key(run_id)
+ try:
+ get_tasks_stream_redis_sync(use_dedicated).delete(
+ get_task_run_stream_first_command_key(stream_key),
+ get_task_run_stream_first_activity_key(stream_key),
+ )
+ except Exception:
+ logger.exception("task_run_milestone_claims_release_failed", run_id=run_id)
+
+
def publish_task_run_stream_event(
run_id: str,
event: dict,
diff --git a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
index a90aaf15a341..6b3f51f942a7 100644
--- a/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/start_agent_server.py
@@ -45,7 +45,9 @@ from products.tasks.backend.logic.services.sandbox import (
get_sandbox_class_for_sandbox_id,
sandbox_repo_path,
)
+from products.tasks.backend.logic.stream.redis_stream import release_task_run_milestone_claims
from products.tasks.backend.models import Task, TaskRun
+from products.tasks.backend.redis import run_uses_dedicated_stream
from products.tasks.backend.temporal.metrics import (
StepTimer,
increment_agent_server_readiness_retry,
@@ -483,6 +485,7 @@ def _prepare_launch(ctx: TaskProcessingContext, scopes: PosthogMcpScopes, sandbo
{"task_id": ctx.task_id, "run_id": ctx.run_id},
cause=TaskRun.DoesNotExist(f"TaskRun {ctx.run_id} not found"),
)
+ release_task_run_milestone_claims(ctx.run_id, run_uses_dedicated_stream(task_run.state))
task_run_session_token: str | None = None
if event_stream_ingest_enabled or task.runtime == Task.Runtime.PI:
try:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
index bec4864a2890..f77140690fe8 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_start_agent_server.py
@@ -739,6 +739,20 @@ def _mock_prepare_launch_dependencies(mocker) -> None:
mocker.patch(f"{prefix}.get_imported_mcp_server_configs", return_value=[])
mocker.patch(f"{prefix}.get_relayed_mcp_server_names", return_value=[])
mocker.patch(f"{prefix}.emit_agent_log")
+ mocker.patch(f"{prefix}.release_task_run_milestone_claims")
+
+
+def test_prepare_launch_releases_boot_milestone_claims(mocker) -> None:
+ prefix = "products.tasks.backend.temporal.process_task.activities.start_agent_server"
+ _mock_prepare_launch_dependencies(mocker)
+ mocker.patch(f"{prefix}.TaskRun.objects.filter").return_value.first.return_value = mocker.Mock(
+ state={"use_dedicated_stream": True}
+ )
+ release = mocker.patch(f"{prefix}.release_task_run_milestone_claims")
+
+ _prepare_launch(_context(), "read_only", "sandbox-id")
+
+ release.assert_called_once_with("run-id", True)
def test_prepare_judge_has_no_live_or_inherited_mcp_connections(mocker) -> None:
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
index 6a5347c769e8..bb88a767f43d 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_update_task_run_status.py
@@ -96,6 +96,20 @@ class TestUpdateTaskRunStatusActivity:
test_task_run.refresh_from_db()
assert test_task_run.status == TaskRun.Status.CANCELLED
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize("status", [TaskRun.Status.COMPLETED, TaskRun.Status.FAILED, TaskRun.Status.CANCELLED])
+ def test_terminal_run_refuses_to_start(self, activity_environment, test_task_run, status):
+ test_task_run.status = status
+ test_task_run.save(update_fields=["status"])
+
+ input_data = UpdateTaskRunStatusInput(run_id=str(test_task_run.id), status=TaskRun.Status.IN_PROGRESS)
+ with pytest.raises(ApplicationError) as exc_info:
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+
+ assert exc_info.value.non_retryable is True
+ test_task_run.refresh_from_db()
+ assert test_task_run.status == status
+
@pytest.mark.django_db(transaction=True)
def test_updates_error_message(self, activity_environment, test_task_run):
error_msg = "Something went wrong"
diff --git a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
index c41930c2b260..d529228fc83e 100644
--- a/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
+++ b/products/tasks/backend/temporal/process_task/activities/update_task_run_status.py
@@ -84,6 +84,12 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
# Terminal statuses are final. A run cancelled out of band must not be resurrected to
# completed/failed by its own workflow finishing afterward, which would both lie in the
# audit trail and undo the cancellation. Re-checked here while holding the row lock.
+ if old_status in _TERMINAL_STATUSES and input.status == TaskRun.Status.IN_PROGRESS:
+ raise ApplicationError(
+ f"TaskRun {input.run_id} is already {old_status}; refusing to start it",
+ non_retryable=True,
+ type="TaskRunAlreadyTerminalError",
+ )
if old_status in _TERMINAL_STATUSES and input.status != old_status:
log_with_activity_context(
"Skipping terminal status overwrite",
diff --git a/products/tasks/backend/temporal/process_task/tests/test_workflow.py b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
index e32cd04501cd..f2ac66950dc0 100644
--- a/products/tasks/backend/temporal/process_task/tests/test_workflow.py
+++ b/products/tasks/backend/temporal/process_task/tests/test_workflow.py
@@ -1450,6 +1450,20 @@ async def test_first_agent_activity_signal_is_recorded_once(monkeypatch):
schedule.assert_called_once_with("agent_first_activity_observed")
+async def test_boot_milestone_signal_before_context_is_dropped(monkeypatch):
+ workflow_instance = ProcessTaskWorkflow()
+ workflow_instance._agent_boot_interaction_telemetry_enabled = True
+ schedule = Mock()
+ monkeypatch.setattr(workflow_instance, "_schedule_boot_milestone", schedule)
+
+ await workflow_instance.agent_activity_observed()
+ await workflow_instance.agent_command_dispatched()
+
+ schedule.assert_not_called()
+ assert workflow_instance._first_agent_activity_recorded is False
+ assert workflow_instance._first_command_dispatched_recorded is False
+
+
async def test_boot_milestone_contains_only_timing_and_runtime_dimensions(monkeypatch):
workflow_instance = ProcessTaskWorkflow()
workflow_instance._context = _build_context(github_integration_id=123)
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 20d3927826c9..a32405b4afc2 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -2784,12 +2784,16 @@ class ProcessTaskWorkflow(PostHogWorkflow):
def _record_first_command_dispatched(self) -> None:
if self._first_command_dispatched_recorded or not self._agent_boot_interaction_telemetry_enabled:
return
+ if self._context is None:
+ return
self._first_command_dispatched_recorded = True
self._schedule_boot_milestone("agent_first_command_dispatched")
def _record_first_agent_activity(self) -> None:
if self._first_agent_activity_recorded or not self._agent_boot_interaction_telemetry_enabled:
return
+ if self._context is None:
+ return
self._first_agent_activity_recorded = True
self._schedule_boot_milestone("agent_first_activity_observed")