: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
chore(mcp): create in-process temporal server for sandboxed eval's temporal worker (#57858)
Chris Volzer90e759c32e19
diff --git a/ee/hogai/eval/sandboxed/conftest.py b/ee/hogai/eval/sandboxed/conftest.pyindex d5b27520a9a8..54dd80171fdb 100644--- a/ee/hogai/eval/sandboxed/conftest.py+++ b/ee/hogai/eval/sandboxed/conftest.py@@ -16,7 +16,8 @@ import pytestfrom django.conf import settings-from posthog.models import OAuthApplication+from temporalio.testing import WorkflowEnvironment+from posthog.temporal.common.worker import create_workerfrom products.tasks.backend.services.custom_prompt_internals import CustomPromptSandboxContext@@ -88,6 +89,14 @@ def pytest_collection_modifyitems(config, items): # noqa: ARG001_EVAL_CONTAINER_PREFIX = "task-sandbox-"+def _temporal_client_target(env: WorkflowEnvironment) -> tuple[str, str]:+ config = env.client.config()+ service_client = config["service_client"]+ target_host = service_client.config.target_host+ host, port = target_host.rsplit(":", maxsplit=1)+ return host, port++def _start_long_lived_subprocess(*,name: str,@@ -224,50 +233,6 @@ def _cleanup_sandbox_containers(pytestconfig):_cleanup_eval_containers()[email protected](scope="session", autouse=True)-def _posthog_oauth_app(django_db_setup, django_db_blocker):- """Seed the Array OAuth application required by sandbox MCP auth.-- The temporal workflow's ``provision_sandbox`` activity creates an OAuth- access token so the sandbox can authenticate with the PostHog MCP server.- Without this record the activity raises ``OAuthTokenError``.-- Uses ``get_array_app()`` first (succeeds if the app already exists in a- reused DB), falling back to creating it with the client ID that- ``get_array_app()`` would resolve for the current ``CLOUD_DEPLOYMENT``.- """- from posthog.temporal.oauth import (- ARRAY_APP_CLIENT_ID_DEV,- ARRAY_APP_CLIENT_ID_EU,- ARRAY_APP_CLIENT_ID_US,- get_array_app,- )- from posthog.utils import get_instance_region-- with django_db_blocker.unblock():- try:- app = get_array_app()- except RuntimeError:- region = get_instance_region()- if region == "EU":- client_id = ARRAY_APP_CLIENT_ID_EU- elif region == "US":- client_id = ARRAY_APP_CLIENT_ID_US- else:- client_id = ARRAY_APP_CLIENT_ID_DEV- app, _ = OAuthApplication.objects.get_or_create(- client_id=client_id,- defaults={- "name": "Array Test App",- "client_type": OAuthApplication.CLIENT_PUBLIC,- "authorization_grant_type": OAuthApplication.GRANT_AUTHORIZATION_CODE,- "redirect_uris": "https://app.posthog.com/callback",- "algorithm": "RS256",- },- )- yield app--@pytest.fixture(scope="session", autouse=True)def _django_live_server(django_db_setup, django_db_blocker):"""Start an in-process Django HTTP server on the test database.@@ -321,13 +286,48 @@ def _sandboxed_local_skills(_sandbox_settings) -> Generator[Path, None, None]:@pytest.fixture(scope="session", autouse=True)-def _sandbox_settings(_django_live_server, _llm_gateway, _posthog_oauth_app):+def _temporal_test_server() -> Generator[tuple[str, str, str], None, None]:+ """Start an isolated Temporal dev server for sandboxed eval workflows."""+ loop = asyncio.new_event_loop()+ temporal_namespace = settings.TEMPORAL_NAMESPACE+ env: WorkflowEnvironment | None = None++ try:+ env = loop.run_until_complete(+ WorkflowEnvironment.start_local(+ namespace=temporal_namespace,+ ip="127.0.0.1",+ port=None,+ dev_server_log_level="warn",+ )+ )+ host, port = _temporal_client_target(env)+ logger.info("Sandboxed eval Temporal server ready at %s:%s namespace=%s", host, port, temporal_namespace)++ yield host, port, temporal_namespace+ finally:+ if env is not None:+ logger.info("Shutting down sandboxed eval Temporal server")+ loop.run_until_complete(env.shutdown())+ loop.close()++[email protected](scope="session", autouse=True)+def _sandbox_settings(+ _django_live_server: object,+ _llm_gateway: object,+ _temporal_test_server: tuple[str, str, str],+) -> Generator[None, None, None]:"""Configure Django settings required by the sandbox/temporal activities.All URLs use ``host.docker.internal`` so they're reachable from insideDocker sandbox containers. Points at the in-process Django live serverwhich shares the test database.+ Temporal is pointed at a per-session local dev server and task queue. That+ keeps eval workflows away from any dev worker already polling the normal+ tasks queue in the developer's environment.+Also patches ``posthoganalytics.feature_enabled`` to return True for allflags so permission checks (TasksAccessPermission) and workflow guards pass."""@@ -338,6 +338,8 @@ def _sandbox_settings(_django_live_server, _llm_gateway, _posthog_oauth_app):# Docker containers reach the host via host.docker.internaldocker_api_url = f"http://host.docker.internal:{DJANGO_LIVE_PORT}"docker_llm_gateway_url = f"http://host.docker.internal:{LLM_GATEWAY_PORT}"+ temporal_host, temporal_port, temporal_namespace = _temporal_test_server+ temporal_task_queue = f"sandboxed-evals-tasks-{os.getpid()}"import posthoganalytics@@ -348,6 +350,12 @@ def _sandbox_settings(_django_live_server, _llm_gateway, _posthog_oauth_app):SANDBOX_API_URL=docker_api_url,SANDBOX_LLM_GATEWAY_URL=docker_llm_gateway_url,SANDBOX_MCP_URL=f"http://host.docker.internal:{MCP_PORT}/mcp",+ TEMPORAL_HOST=temporal_host,+ TEMPORAL_PORT=temporal_port,+ TEMPORAL_NAMESPACE=temporal_namespace,+ TEMPORAL_CLIENT_CERT=None,+ TEMPORAL_CLIENT_KEY=None,+ TASKS_TASK_QUEUE=temporal_task_queue,),patch.object(posthoganalytics, "feature_enabled", return_value=True),):