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.

perf(tasks): evaluate the agent shadow flag once on the processing context (#122635)

Alessandro Pogliaghif6e2893a1584
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index c254623ab106..b5a48539ab61 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -221,6 +221,7 @@ DESKTOP_WORKSPACE_WARM_FEATURE_FLAG = "task-cloud-desktop-workspace-warm"
# an image rebuild.
RTK_DISABLED_FEATURE_FLAG = "tasks-rtk-disabled"
BENJAMIN_FEATURE_FLAG = "task-cloud-run-benjamin-plus"
+AGENT_SERVER_SHADOW_FEATURE_FLAG = "agent-server-shadow-observer"
CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-claude-own-subscription-cloud"
CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG = "posthog-code-codex-own-subscription-cloud"
OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAGS: dict[str, str] = {
diff --git a/products/tasks/backend/temporal/execute_sandbox/workflow.py b/products/tasks/backend/temporal/execute_sandbox/workflow.py
index 81324a8422e3..804844f7b793 100644
--- a/products/tasks/backend/temporal/execute_sandbox/workflow.py
+++ b/products/tasks/backend/temporal/execute_sandbox/workflow.py
@@ -1112,7 +1112,7 @@ class ExecuteSandboxWorkflow(PostHogWorkflow):
async def _get_task_processing_context(self, input: ExecuteSandboxInput) -> TaskProcessingContext:
return await workflow.execute_activity(
get_task_processing_context,
- GetTaskProcessingContextInput(run_id=input.run_id, create_pr=input.create_pr),
+ GetTaskProcessingContextInput(run_id=input.run_id, create_pr=input.create_pr, launches_agent=True),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),
)
diff --git a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
index e1019e4552ed..c651133caf71 100644
--- a/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/get_task_processing_context.py
@@ -19,6 +19,7 @@ from products.context_layer.backend.facade import api as context_layer_facade
from products.tasks.backend.constants import (
AGENT_OTEL_TELEMETRY_STATE_KEY,
AGENT_PEER_MESSAGING_FEATURE_FLAG,
+ AGENT_SERVER_SHADOW_FEATURE_FLAG,
BENJAMIN_FEATURE_FLAG,
CODEX_SUBSCRIPTION_EGRESS_DOMAINS,
DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,
@@ -91,6 +92,7 @@ class GetTaskProcessingContextInput:
resumed_sandbox_id: str | None = None
resumed_sandbox_backend: str | None = None
stream_generation: str | None = None
+ launches_agent: bool = False
@dataclass(frozen=False)
@@ -148,6 +150,7 @@ class TaskProcessingContext:
overlap_clone_boot_enabled: bool = False
# Captured at workflow start so the warmup decision stays stable across retries.
desktop_workspace_warm_enabled: bool = False
+ agent_shadow_enabled: bool = False
agent_proxy_keep_stream_open: bool = True # Temporal payload compatibility
# Set only when the run resolved to the VM runtime — custom images layer on the VM base.
custom_image_name: str | None = None
@@ -436,6 +439,28 @@ def _is_pi_acp_enabled(
return False
+def _is_agent_shadow_enabled(
+ *,
+ distinct_id: str,
+ organization_id: str,
+ run_id: str,
+) -> bool:
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ AGENT_SERVER_SHADOW_FEATURE_FLAG,
+ distinct_id=distinct_id,
+ groups={"organization": organization_id},
+ group_properties={"organization": {"id": organization_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as e:
+ log_with_activity_context("agent_shadow_flag_check_failed", run_id=run_id, error=str(e))
+ return False
+
+
@StepTimer("flag_rtk")
def _is_rtk_enabled(
*,
@@ -1274,6 +1299,11 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
log_with_activity_context(
f"desktop_workspace_warm_enabled: {desktop_workspace_warm_enabled} for this task run", run_id=run_id
)
+ agent_shadow_enabled = input.launches_agent and _is_agent_shadow_enabled(
+ distinct_id=distinct_id,
+ organization_id=organization_id,
+ run_id=run_id,
+ )
rtk_enabled = _is_rtk_enabled(
distinct_id=distinct_id,
organization_id=organization_id,
@@ -1431,6 +1461,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro
use_hogland_hotplug_golden=use_hogland_hotplug_golden,
overlap_clone_boot_enabled=overlap_clone_boot_enabled,
desktop_workspace_warm_enabled=desktop_workspace_warm_enabled,
+ agent_shadow_enabled=agent_shadow_enabled,
custom_image_name=custom_image_name,
rtk_enabled=rtk_enabled,
benjamin_enabled=benjamin_enabled,
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 586b0ba1d1d5..6e380090d58d 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
@@ -83,7 +83,6 @@ from .get_task_processing_context import TaskProcessingContext
logger = get_logger(__name__)
-AGENT_SERVER_SHADOW_FEATURE_FLAG = "agent-server-shadow-observer"
PROTECTED_BASE_BRANCH_JOIN_TIMEOUT_SECONDS = 30.0
@@ -211,23 +210,6 @@ def _ensure_repository_on_disk(ctx: TaskProcessingContext, sandbox: SandboxBase)
)
-def _is_agent_shadow_enabled(ctx: TaskProcessingContext) -> bool:
- try:
- return bool(
- posthoganalytics.feature_enabled(
- AGENT_SERVER_SHADOW_FEATURE_FLAG,
- distinct_id=ctx.distinct_id,
- groups={"organization": ctx.organization_id},
- group_properties={"organization": {"id": ctx.organization_id}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
- )
- except Exception:
- logger.exception("agent_shadow_flag_check_failed", run_id=ctx.run_id)
- return False
-
-
def _has_agent_shadow_launch_marker(ctx: TaskProcessingContext, sandbox: SandboxBase) -> bool:
try:
result = sandbox.execute(
@@ -245,7 +227,7 @@ def _launch_agent_shadow(ctx: TaskProcessingContext, sandbox: SandboxBase) -> bo
return False
if current_activity_attempt() > 1 and _has_agent_shadow_launch_marker(ctx, sandbox):
return True
- if not _is_agent_shadow_enabled(ctx):
+ if not ctx.agent_shadow_enabled:
return False
quoted_run_id = shlex.quote(ctx.run_id)
command = (
diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
index f78a6bc8b1ae..cb23ed0b86be 100644
--- a/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_get_task_processing_context.py
@@ -15,6 +15,7 @@ from posthog.models.user_integration import UserIntegration
from products.signals.backend.models import SignalTeamConfig
from products.skills.backend.models.skills import LLMSkill
from products.tasks.backend.constants import (
+ AGENT_SERVER_SHADOW_FEATURE_FLAG,
BENJAMIN_FEATURE_FLAG,
CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,
CODEX_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG,
@@ -39,6 +40,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing
TaskProcessingContext,
VmSandboxDecision,
_ensure_subscription_allowed,
+ _is_agent_shadow_enabled,
_is_benjamin_enabled,
_is_burstable_sandbox_resources_enabled,
_is_desktop_workspace_warm_enabled,
@@ -150,6 +152,31 @@ def test_desktop_workspace_warm_flag_fails_closed():
)
+def test_agent_shadow_flag_uses_server_side_organization_targeting():
+ with patch(FEATURE_ENABLED_TARGET, return_value=True) as feature_enabled_mock:
+ assert (
+ _is_agent_shadow_enabled(distinct_id="distinct-id", organization_id="organization-id", run_id="run-id")
+ is True
+ )
+
+ feature_enabled_mock.assert_called_once_with(
+ AGENT_SERVER_SHADOW_FEATURE_FLAG,
+ distinct_id="distinct-id",
+ groups={"organization": "organization-id"},
+ group_properties={"organization": {"id": "organization-id"}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+
+
+def test_agent_shadow_flag_fails_closed():
+ with patch(FEATURE_ENABLED_TARGET, side_effect=RuntimeError("flag service failed")):
+ assert (
+ _is_agent_shadow_enabled(distinct_id="distinct-id", organization_id="organization-id", run_id="run-id")
+ is False
+ )
+
+
def _preview_gate(
*,
origin_product: str = Task.OriginProduct.USER_CREATED,
@@ -237,10 +264,18 @@ class TestGetTaskProcessingContextActivity:
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
- "subscription,is_trial,resume",
- [(False, False, False), (True, False, False), (False, True, False), (False, False, True)],
+ "subscription,is_trial,resume,launches_agent",
+ [
+ (False, False, False, True),
+ (True, False, False, True),
+ (False, True, False, True),
+ (False, False, True, True),
+ (False, False, False, False),
+ ],
)
- def test_get_task_processing_context_success(self, activity_environment, test_task, subscription, is_trial, resume):
+ def test_get_task_processing_context_success(
+ self, activity_environment, test_task, subscription, is_trial, resume, launches_agent
+ ):
owner = User.objects.create_user(
email="[email protected]", password=None, first_name="Owner", distinct_id="subscription-owner"
)
@@ -253,7 +288,7 @@ class TestGetTaskProcessingContextActivity:
task_run = test_task.create_run(acting_user_id=owner.id, extra_state=extra_state)
if resume:
task_run.prepare_for_cloud_resume()
- input_data = GetTaskProcessingContextInput(run_id=str(task_run.id))
+ input_data = GetTaskProcessingContextInput(run_id=str(task_run.id), launches_agent=launches_agent)
with (
patch(
@@ -266,10 +301,14 @@ class TestGetTaskProcessingContextActivity:
),
):
flag.side_effect = lambda key, distinct_id=None, **kwargs: (
- key == CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG and distinct_id == owner.distinct_id
+ (key == CLAUDE_OWN_SUBSCRIPTION_CLOUD_FEATURE_FLAG and distinct_id == owner.distinct_id)
+ or key == AGENT_SERVER_SHADOW_FEATURE_FLAG
)
result = async_to_sync(activity_environment.run)(get_task_processing_context, input_data)
+ assert result.agent_shadow_enabled is launches_agent
+ assert (AGENT_SERVER_SHADOW_FEATURE_FLAG in [call.args[0] for call in flag.call_args_list]) is launches_agent
+
assert isinstance(result, TaskProcessingContext)
assert result.task_id == str(test_task.id)
assert result.run_id == str(task_run.id)
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 6311d3dd05ce..ae342dde7e80 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
@@ -27,7 +27,6 @@ from products.tasks.backend.temporal.process_task.activities.start_agent_server
_ensure_repository_on_disk,
_include_personal_mcp_for_task,
_invoke_start_agent_server,
- _is_agent_shadow_enabled,
_launch_agent_shadow,
_LaunchParams,
_network_enforcement_observation,
@@ -88,6 +87,7 @@ def _context(
use_modal_network_allowlist: bool = False,
claude_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway",
codex_model_access: Literal["posthog-gateway", "own-subscription"] = "posthog-gateway",
+ agent_shadow_enabled: bool = False,
) -> TaskProcessingContext:
return TaskProcessingContext(
task_id="task-id",
@@ -107,6 +107,7 @@ def _context(
use_modal_network_allowlist=use_modal_network_allowlist,
claude_model_access=claude_model_access,
codex_model_access=codex_model_access,
+ agent_shadow_enabled=agent_shadow_enabled,
_branch=branch,
)
@@ -882,43 +883,13 @@ def test_subscription_compatibility_is_checked_before_launch(mocker, access, exi
assert sandbox.start_agent_server.call_args.kwargs["claude_model_access"] == access
-def test_agent_shadow_flag_uses_server_side_organization_targeting(mocker) -> None:
- feature_enabled = mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server.posthoganalytics.feature_enabled",
- return_value=True,
- )
-
- assert _is_agent_shadow_enabled(_context()) is True
- feature_enabled.assert_called_once_with(
- "agent-server-shadow-observer",
- distinct_id="distinct-id",
- groups={"organization": "organization-id"},
- group_properties={"organization": {"id": "organization-id"}},
- only_evaluate_locally=False,
- send_feature_flag_events=False,
- )
-
-
-def test_agent_shadow_flag_fails_closed(mocker) -> None:
- mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server.posthoganalytics.feature_enabled",
- side_effect=RuntimeError("unavailable"),
- )
-
- assert _is_agent_shadow_enabled(_context()) is False
-
-
def test_agent_shadow_launches_without_credentials(mocker) -> None:
- mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",
- return_value=True,
- )
sandbox = mocker.Mock(id="sandbox-id")
sandbox.config.snapshot_restored = False
sandbox.agent_server_health_url.return_value = "http://127.0.0.1:8080/health"
sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
- assert _launch_agent_shadow(_context(), sandbox) is True
+ assert _launch_agent_shadow(_context(agent_shadow_enabled=True), sandbox) is True
command = sandbox.execute.call_args.args[0]
assert "/usr/local/bin/agent-shadow" in command
assert "/usr/bin/env -i /usr/bin/setsid /usr/local/bin/agent-shadow" in command
@@ -928,16 +899,12 @@ def test_agent_shadow_launches_without_credentials(mocker) -> None:
def test_agent_shadow_launch_guards_on_marker_not_its_own_command_line(mocker) -> None:
- mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",
- return_value=True,
- )
sandbox = mocker.Mock(id="sandbox-id")
sandbox.config.snapshot_restored = False
sandbox.agent_server_health_url.return_value = "http://127.0.0.1:8080/health"
sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
- assert _launch_agent_shadow(_context(), sandbox) is True
+ assert _launch_agent_shadow(_context(agent_shadow_enabled=True), sandbox) is True
command = sandbox.execute.call_args.args[0]
assert "pgrep" not in command
assert "/tmp/agent-shadow-launched" in command
@@ -948,31 +915,28 @@ def test_agent_shadow_launch_recovers_prior_attempt_from_marker(mocker) -> None:
"products.tasks.backend.temporal.process_task.activities.start_agent_server.current_activity_attempt",
return_value=2,
)
- feature_enabled = mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",
- return_value=False,
- )
sandbox = mocker.Mock(id="sandbox-id")
sandbox.config.snapshot_restored = False
sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=0)
- assert _launch_agent_shadow(_context(), sandbox) is True
+ assert _launch_agent_shadow(_context(agent_shadow_enabled=False), sandbox) is True
assert "head -c 128 /tmp/agent-shadow-launched" in sandbox.execute.call_args.args[0]
- feature_enabled.assert_not_called()
[email protected]("exit_code,launched", [(0, True), (1, False)])
-def test_agent_shadow_launch_fails_closed_on_nonzero_exit(mocker, exit_code, launched) -> None:
- mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",
- return_value=True,
- )
+ "agent_shadow_enabled,exit_code,launched,executed",
+ [(True, 0, True, True), (True, 1, False, True), (False, 0, False, False)],
+)
+def test_agent_shadow_launch_fails_closed_on_nonzero_exit(
+ mocker, agent_shadow_enabled: bool, exit_code: int, launched: bool, executed: bool
+) -> None:
sandbox = mocker.Mock(id="sandbox-id")
sandbox.config.snapshot_restored = False
sandbox.agent_server_health_url.return_value = "http://127.0.0.1:8080/health"
sandbox.execute.return_value = ExecutionResult(stdout="", stderr="", exit_code=exit_code)
- assert _launch_agent_shadow(_context(), sandbox) is launched
+ assert _launch_agent_shadow(_context(agent_shadow_enabled=agent_shadow_enabled), sandbox) is launched
+ assert sandbox.execute.called is executed
def test_agent_shadow_skips_filesystem_snapshot(mocker) -> None:
@@ -980,15 +944,11 @@ def test_agent_shadow_skips_filesystem_snapshot(mocker) -> None:
"products.tasks.backend.temporal.process_task.activities.start_agent_server.current_activity_attempt",
return_value=2,
)
- mocker.patch(
- "products.tasks.backend.temporal.process_task.activities.start_agent_server._is_agent_shadow_enabled",
- return_value=True,
- )
sandbox = mocker.Mock(id="sandbox-id")
sandbox.config.snapshot_restored = True
sandbox.config.snapshot_kind = "filesystem"
- assert _launch_agent_shadow(_context(), sandbox) is False
+ assert _launch_agent_shadow(_context(agent_shadow_enabled=True), sandbox) is False
sandbox.execute.assert_not_called()
diff --git a/products/tasks/backend/temporal/process_task/workflow.py b/products/tasks/backend/temporal/process_task/workflow.py
index 4b3a49d042ec..12d68fabe7b0 100644
--- a/products/tasks/backend/temporal/process_task/workflow.py
+++ b/products/tasks/backend/temporal/process_task/workflow.py
@@ -1944,6 +1944,7 @@ class ProcessTaskWorkflow(PostHogWorkflow):
resumed_sandbox_id=input.resumed_sandbox.sandbox_id if input.resumed_sandbox else None,
resumed_sandbox_backend=input.resumed_sandbox.sandbox_backend if input.resumed_sandbox else None,
stream_generation=self._stream_generation,
+ launches_agent=True,
),
start_to_close_timeout=timedelta(minutes=2),
retry_policy=RetryPolicy(maximum_attempts=3),