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): keep credential refreshes out of sandbox output (#84075)

Alessandro Pogliaghi22728958a8b1
diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.py
index e841bb2f52fd..f0d0ca5937ab 100644
--- a/products/tasks/backend/logic/services/agent_command.py
+++ b/products/tasks/backend/logic/services/agent_command.py
@@ -325,8 +325,6 @@ def send_refresh_session(
mcp_servers: list[dict[str, Any]],
auth_token: str | None = None,
timeout: int = REFRESH_TIMEOUT_SECONDS,
- refreshed_credentials: list[str] | None = None,
- authorship: str | None = None,
) -> CommandResult:
"""Push updated MCP server configs into a live sandbox agent-server.
@@ -335,18 +333,8 @@ def send_refresh_session(
history). Must be dispatched between turns — the agent-server will reply
with JSON-RPC error -32002 if a prompt is currently in flight.
- ``refreshed_credentials`` piggybacks on this channel to notify the
- agent-server which in-sandbox credentials (e.g. ``["github"]``) were just
- re-injected, purely so it can surface a debug log. A credentials-only
- notification (empty ``mcp_servers``) is logged and returns immediately on
- the agent-server side without rebuilding the session, so it is safe to send
- mid-turn.
"""
params: dict[str, Any] = {"mcpServers": mcp_servers}
- if refreshed_credentials:
- params["refreshedCredentials"] = refreshed_credentials
- if authorship:
- params["authorship"] = authorship
return send_agent_command(
task_run,
method=REFRESH_SESSION_METHOD,
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 45295feaebe6..d05433e2f626 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
@@ -7,8 +7,6 @@ from posthog.temporal.common.logger import get_logger
from posthog.temporal.common.utils import asyncify, retry_on_db_connection_drop
from products.tasks.backend.exceptions import CredentialUnavailableError, SandboxNotFoundError, SandboxNotRunningError
-from products.tasks.backend.logic.services.agent_command import send_refresh_session
-from products.tasks.backend.logic.services.connection_token import create_sandbox_connection_token
from products.tasks.backend.logic.services.sandbox import Sandbox
from products.tasks.backend.models import Task, TaskRun
from products.tasks.backend.temporal.metrics import increment_credential_refresh
@@ -17,11 +15,6 @@ from products.tasks.backend.temporal.process_task.sandbox_credentials import (
DEFAULT_REFRESH_INTERVAL_SECONDS,
build_sandbox_credentials,
)
-from products.tasks.backend.temporal.process_task.utils import (
- get_actor_distinct_id,
- get_task_run_credential_user,
- is_slack_interaction_state,
-)
from .get_task_processing_context import TaskProcessingContext
@@ -44,29 +37,6 @@ def _with_current_authorship(ctx: TaskProcessingContext) -> TaskProcessingContex
return dataclasses.replace(ctx, state={**(ctx.state or {}), "pr_authorship_mode": mode})
-def _notify_agent_server_of_refresh(ctx: TaskProcessingContext, task: Task, refreshed_kinds: list[str]) -> None:
- """Tell the running agent-server which credentials were re-injected so it logs them.
- This is best-effort since the sandbox may be unreachable, so a failure here never fails the refresh itself.
- """
- try:
- task_run = TaskRun.objects.get(id=ctx.run_id)
- auth_token = None
- actor_user = get_task_run_credential_user(task, ctx.state)
- if is_slack_interaction_state(ctx.state) and actor_user is None:
- logger.warning("sandbox_credentials_refresh_notify_missing_slack_actor", run_id=ctx.run_id)
- return
- if actor_user and actor_user.id:
- auth_token = create_sandbox_connection_token(
- task_run, user_id=actor_user.id, distinct_id=get_actor_distinct_id(actor_user)
- )
- authorship = (ctx.state or {}).get("pr_authorship_mode")
- send_refresh_session(
- task_run, [], auth_token=auth_token, refreshed_credentials=refreshed_kinds, authorship=authorship
- )
- except Exception:
- logger.warning("sandbox_credentials_refresh_notify_failed", run_id=ctx.run_id, exc_info=True)
-
-
@dataclass
class RefreshSandboxCredentialsInput:
context: TaskProcessingContext
@@ -218,8 +188,14 @@ def refresh_sandbox_credentials(input: RefreshSandboxCredentialsInput) -> Refres
if intervals:
next_refresh = min(intervals)
- if refreshed_kinds:
- _notify_agent_server_of_refresh(ctx, task, refreshed_kinds)
+ logger.info(
+ "sandbox_credentials_refreshed",
+ run_id=ctx.run_id,
+ sandbox_id=input.sandbox_id,
+ refreshed_kinds=refreshed_kinds,
+ orphaned_kinds=orphaned_kinds,
+ next_refresh_seconds=next_refresh,
+ )
track_event(
"sandbox_credentials_refreshed",
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
index 150ce9479055..a14352f3c609 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_refresh_sandbox_credentials.py
@@ -45,6 +45,7 @@ class TestRefreshSandboxCredentialsActivity:
patch(
"products.tasks.backend.temporal.process_task.activities.refresh_sandbox_credentials.track_event"
) as track_event,
+ patch("products.tasks.backend.logic.services.agent_command.send_agent_command") as send_agent_command,
):
output = async_to_sync(activity_environment.run)(
refresh_sandbox_credentials,
@@ -54,6 +55,7 @@ class TestRefreshSandboxCredentialsActivity:
assert output.refreshed_kinds == ["github"]
assert output.next_refresh_seconds == 20 * 60
assert output.sandbox_gone is False
+ send_agent_command.assert_not_called()
# git remote rewrite + env-file read both ran against the sandbox.
assert any("git remote set-url origin" in str(c.args[0]) for c in sandbox.execute.call_args_list)
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 9f440a235da2..e8b161274c40 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
@@ -8,6 +8,7 @@ from temporalio.testing import ActivityEnvironment
from products.tasks.backend.models import Loop, TaskRun
from products.tasks.backend.temporal.process_task.activities.update_task_run_status import (
SANDBOX_GONE_STATE_KEY,
+ TIMED_OUT_INACTIVITY_STATE_KEY,
TIMED_OUT_WALL_CLOCK_STATE_KEY,
UpdateTaskRunStatusInput,
update_task_run_status,
@@ -191,11 +192,49 @@ class TestUpdateTaskRunStatusActivity:
assert props["usage_turns"] == 3
assert props["rtk_enabled"] is True
assert props["run_environment"] == test_task_run.environment
+ assert props["termination_reason"] is None
mock_record.assert_called_once()
assert mock_record.call_args.kwargs["rtk_enabled"] is True
assert mock_record.call_args.kwargs["runtime_adapter"] == "codex"
assert mock_record.call_args.kwargs["status"] == status
+ @pytest.mark.django_db(transaction=True)
+ @pytest.mark.parametrize(
+ "status,timed_out_inactivity,timeout_marker,expected_event,expected_reason",
+ [
+ (TaskRun.Status.COMPLETED, True, None, "task_run_completed", TIMED_OUT_INACTIVITY_STATE_KEY),
+ (
+ TaskRun.Status.FAILED,
+ False,
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
+ "task_run_failed",
+ TIMED_OUT_WALL_CLOCK_STATE_KEY,
+ ),
+ ],
+ )
+ @patch("products.tasks.backend.models.posthoganalytics.capture")
+ def test_terminal_analytics_carries_termination_reason(
+ self,
+ mock_capture,
+ activity_environment,
+ test_task_run,
+ status,
+ timed_out_inactivity,
+ timeout_marker,
+ expected_event,
+ expected_reason,
+ ):
+ input_data = UpdateTaskRunStatusInput(
+ run_id=str(test_task_run.id),
+ status=status,
+ timed_out_inactivity=timed_out_inactivity,
+ timeout_marker=timeout_marker,
+ )
+ async_to_sync(activity_environment.run)(update_task_run_status, input_data)
+
+ captured = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == expected_event]
+ assert captured[0].kwargs["properties"]["termination_reason"] == expected_reason
+
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
"error_type,expected_error_type",
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 7cefd0a1c303..b00a2e4cd20a 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
@@ -134,6 +134,7 @@ def update_task_run_status(input: UpdateTaskRunStatusInput) -> None:
"Task run status updated",
run_id=input.run_id,
status=input.status,
+ termination_reason=marker if marker in _TERMINAL_STATE_MARKERS else None,
)
@@ -146,8 +147,13 @@ def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInp
transition so activity retries and repeat updates don't double-count.
"""
try:
+ marker = TIMED_OUT_INACTIVITY_STATE_KEY if input.timed_out_inactivity else input.timeout_marker
+ termination_reason = marker if marker in _TERMINAL_STATE_MARKERS else None
if input.status == TaskRun.Status.COMPLETED:
- task_run.capture_event("task_run_completed", {"duration_seconds": task_run._duration_seconds()})
+ task_run.capture_event(
+ "task_run_completed",
+ {"duration_seconds": task_run._duration_seconds(), "termination_reason": termination_reason},
+ )
else:
task_run.capture_event(
"task_run_failed",
@@ -155,6 +161,7 @@ def _capture_terminal_analytics(task_run: TaskRun, input: UpdateTaskRunStatusInp
"error_message": truncate_error_message(input.error_message or task_run.error_message),
"error_type": input.error_type or "unspecified",
"duration_seconds": task_run._duration_seconds(),
+ "termination_reason": termination_reason,
},
)