: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
feat(tasks): route task sandboxes to hogland behind a feature flag (#87253)
Tom Owers681fc048b221
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.pyindex 7439b5983b00..ea9f6e8cdfa8 100644--- a/products/tasks/backend/constants.py+++ b/products/tasks/backend/constants.py@@ -19,6 +19,8 @@ MODAL_VM_SANDBOX_FEATURE_FLAG = "tasks-modal-vm-sandbox"# Gates the nightly prebaked dev-stack image bake (see logic/services/dev_stack_image.py).DEV_STACK_IMAGE_BAKE_FEATURE_FLAG = "tasks-dev-stack-image-bake"MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG = "tasks-modal-network-allowlist"+# Routes a plain default-template run onto the hogland (Firecracker) sandbox backend.+HOGLAND_SANDBOX_FEATURE_FLAG = "tasks-hogland-sandbox"AGENT_RUN_OTEL_TELEMETRY_FEATURE_FLAG = "tasks-agent-run-otel-telemetry"PI_CLOUD_RUNTIME_FEATURE_FLAG = "pi-harness"# Gates agent-to-agent peer messaging between cloud runs. v1 additionally requires the Pidiff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.pyindex 0e91b15af428..ee4052730d10 100644--- a/products/tasks/backend/facade/api.py+++ b/products/tasks/backend/facade/api.py@@ -2115,6 +2115,13 @@ _PROTECTED_RUN_STATE_KEYS = frozenset("repositories","verified_pr_urls","sandbox_id",+ # Sandbox connection state is written only by the provisioning activity. A PATCHable+ # sandbox_backend/sandbox_url would let a task controller point the account-wide hogland+ # bearer (or the connect token) at an arbitrary server, so it stays server-owned.+ "sandbox_backend",+ "sandbox_url",+ "sandbox_connect_token",+ "sandbox_jwt_kid","sandbox_cpu_cores","sandbox_memory_gb","sandbox_ttl_seconds",@@ -4146,11 +4153,17 @@ def get_task_run_sandbox_connection(if not run_state.sandbox_url:return contracts.TaskRunSandboxConnectionDTO(sandbox_url=None, sandbox_connect_token=None)+ from products.tasks.backend.logic.services.agent_command import ( # noqa: PLC0415 — keep sandbox deps off the api import path+ sandbox_transport_token,+ )+connection_token = _create(task_run=run, user_id=user_id, distinct_id=distinct_id)+ transport_token, token_param = sandbox_transport_token(run.state, run_state.sandbox_url)return contracts.TaskRunSandboxConnectionDTO(sandbox_url=run_state.sandbox_url,- sandbox_connect_token=run_state.sandbox_connect_token,+ sandbox_connect_token=transport_token,connection_token=connection_token,+ sandbox_token_param=token_param,)diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.pyindex dad55a33674f..ddddbaf8efee 100644--- a/products/tasks/backend/facade/contracts.py+++ b/products/tasks/backend/facade/contracts.py@@ -625,6 +625,8 @@ class TaskRunSandboxConnectionDTO:sandbox_url: str | Nonesandbox_connect_token: str | Noneconnection_token: str | None = None+ # Query-param name the transport token travels under (provider-specific).+ sandbox_token_param: str = "_modal_connect_token"@dataclass(frozen=True)diff --git a/products/tasks/backend/logic/services/agent_command.py b/products/tasks/backend/logic/services/agent_command.pyindex 4adadb2eec18..ba8478960cca 100644--- a/products/tasks/backend/logic/services/agent_command.py+++ b/products/tasks/backend/logic/services/agent_command.py@@ -104,15 +104,85 @@ def _get_sandbox_url_and_token(task_run: Any) -> tuple[str | None, str | None]:return state.get("sandbox_url"), state.get("sandbox_connect_token")+def _is_loopback_host(hostname: str | None) -> bool:+ """Whether ``hostname`` is a loopback address (``localhost``/``127.0.0.1``/``::1``)."""+ if not hostname:+ return False+ if hostname == "localhost":+ return True+ try:+ return ipaddress.ip_address(hostname).is_loopback+ except ValueError:+ return False+++def _is_hogland_sandbox_url(sandbox_url: str | None) -> bool:+ """Whether ``sandbox_url`` points at the configured hogland control plane.++ The hogland bearer is an account-wide credential, so it must only ever be+ attached to a request bound for the real hogland host. Gating on the URL host+ (not the mutable ``sandbox_backend`` state flag) means a forged run state+ cannot redirect the credential to an attacker-controlled server, even on the+ ``send_agent_command`` path whose SSRF check permits arbitrary public hosts.+ """+ hogland_api_url = getattr(settings, "HOGLAND_API_URL", None)+ if not sandbox_url or not hogland_api_url:+ return False+ try:+ target = urlparse(sandbox_url)+ expected = urlparse(hogland_api_url)+ except Exception:+ return False+ # A scheme-less HOGLAND_API_URL parses to hostname=None; refusing that stops a+ # None==None match from attaching the bearer to a scheme-less or mismatched-port URL.+ if not target.hostname or not expected.hostname:+ return False+ # Require an https origin matching the configured host AND port. The one exception is+ # local dev (SANDBOX_PROVIDER=hogland, DEBUG), which talks to a loopback host over+ # http; allow http only when both hosts are loopback. Every real remote origin must+ # still be https to receive the account-wide bearer.+ loopback_dev = settings.DEBUG and _is_loopback_host(target.hostname) and _is_loopback_host(expected.hostname)+ if not loopback_dev and (target.scheme != "https" or expected.scheme != "https"):+ return False+ return (target.hostname, target.port) == (expected.hostname, expected.port)+++def sandbox_transport_token(state: dict[str, Any] | None, sandbox_url: str | None = None) -> tuple[str | None, str]:+ """(token, query_param_name) for the sandbox tunnel/proxy layer.++ Modal mints a per-sandbox connect token that is persisted in ``TaskRun.state``.+ Hogland has no per-sandbox token: its proxy authenticates with the backend's+ bearer — a rotating projected ServiceAccount JWT read fresh per request (the+ static token is the local-dev fallback) — attached here at request time so it+ never touches persisted state or Temporal payloads.++ The hogland bearer is only returned when ``sandbox_url`` is the configured+ hogland host. That host check, not the ``sandbox_backend`` state flag, is what+ authorizes attaching an account-wide credential — ``sandbox_backend`` /+ ``sandbox_url`` are also protected run-state keys, so this is defense in depth.+ """+ if (state or {}).get("sandbox_backend") == "hogland" and _is_hogland_sandbox_url(sandbox_url):+ # Deferred: hogland_sandbox pulls in the hogland SDK + httpx, which every+ # non-hogland caller of this module would otherwise pay for.+ from products.tasks.backend.logic.services.hogland_sandbox import get_hogland_api_token # noqa: PLC0415++ return get_hogland_api_token(), "token"+ return (state or {}).get("sandbox_connect_token"), "_modal_connect_token"++def _build_request_args(connect_token: str | None,auth_token: str | None,+ token_param: str = "_modal_connect_token",) -> tuple[dict[str, str], dict[str, str]]:"""Build request headers and query params with appropriate auth scheme.- When auth_token is provided (external callers going through Modal tunnel):- JWT goes as Authorization header, Modal connect token as query param.- Otherwise (internal callers on same network): connect_token as Authorization header.+ When auth_token is provided (callers going through the provider tunnel/proxy):+ JWT goes as Authorization header, the transport token as the provider's query+ param. Otherwise (internal callers on same network): a Modal connect token goes+ in the Authorization header, while hogland's bearer stays a query param — its+ proxy strips an Authorization header it consumed, and only header-free requests+ reach the agent-server unauthenticated the way Modal's do.Returns:Tuple of (headers, query_params).@@ -122,9 +192,12 @@ def _build_request_args(if auth_token:headers["Authorization"] = f"Bearer {auth_token}"if connect_token:- query_params["_modal_connect_token"] = connect_token+ query_params[token_param] = connect_tokenelif connect_token:- headers["Authorization"] = f"Bearer {connect_token}"+ if token_param == "_modal_connect_token":+ headers["Authorization"] = f"Bearer {connect_token}"+ else:+ query_params[token_param] = connect_tokenreturn headers, query_params@@ -145,7 +218,8 @@ def send_agent_command(as ``_modal_connect_token`` query param for Modal tunnel auth.When omitted, connect_token is used directly as Authorization."""- sandbox_url, connect_token = _get_sandbox_url_and_token(task_run)+ sandbox_url, _ = _get_sandbox_url_and_token(task_run)+ connect_token, token_param = sandbox_transport_token(task_run.state, sandbox_url)if not sandbox_url:return CommandResult(success=False,@@ -169,7 +243,7 @@ def send_agent_command(retryable=False,)- headers, query_params = _build_request_args(connect_token, auth_token)+ headers, query_params = _build_request_args(connect_token, auth_token, token_param)command_url = f"{sandbox_url.rstrip('/')}/command"payload: dict[str, Any] = {diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex cfdf72e66641..639df0113564 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -817,6 +817,20 @@ def get_sandbox_class_for_backend(backend: str) -> SandboxClass:raise RuntimeError(f"Unsupported sandbox backend: {backend}")+def get_sandbox_class_for_run_backend(backend: str) -> SandboxClass:+ """Resolve the provider class for a run whose backend was chosen at context time.++ Only ``"hogland"`` diverts from the process default. Every other value — including+ the ``"modal"`` default — falls through to ``get_sandbox_class()`` so+ ``SANDBOX_PROVIDER`` still selects docker / modal-docker / modal-evals in dev, test,+ and evals. Routing straight to ``get_sandbox_class_for_backend("modal")`` here would+ force ModalSandbox even under ``SANDBOX_PROVIDER=docker``, breaking local runs.+ """+ if backend == "hogland":+ return _get_hogland_sandbox_class()+ return get_sandbox_class()++# hogland mints `box-<12 hex>` (hogd enforces `^box-[0-9a-f]{12}$`); Modal object ids# are `sb-...`. A box restored from a pen keeps a `box-` id, so this covers pens too.HOGLAND_SANDBOX_ID_PREFIX = "box-"diff --git a/products/tasks/backend/logic/services/tests/test_agent_command.py b/products/tasks/backend/logic/services/tests/test_agent_command.pyindex ca16d82408fa..91e606bcccaa 100644--- a/products/tasks/backend/logic/services/tests/test_agent_command.py+++ b/products/tasks/backend/logic/services/tests/test_agent_command.py@@ -10,6 +10,7 @@ from products.tasks.backend.logic.services.agent_command import (REFRESH_TIMEOUT_SECONDS,CommandResult,_build_request_args,+ sandbox_transport_token,send_agent_command,send_cancel,send_refresh_session,@@ -445,3 +446,126 @@ class TestSendRefreshSession:)assert result.successassert REFRESH_SESSION_METHOD == "_posthog/refresh_session"+++_HOGLAND_URL = "https://hogland.prod-us.posthog.dev"+_HOGLAND_SANDBOX_URL = f"{_HOGLAND_URL}/v1/hogboxes/hb-1/proxy/8080"+++class TestSandboxTransportToken:+ @override_settings(HOGLAND_API_TOKEN="hog-tok", HOGLAND_API_URL=_HOGLAND_URL)+ def test_hogland_runs_use_the_backend_bearer_as_a_query_param(self):+ token, param = sandbox_transport_token(+ {"sandbox_backend": "hogland", "sandbox_connect_token": "stale"}, _HOGLAND_SANDBOX_URL+ )+ assert (token, param) == ("hog-tok", "token")++ @override_settings(HOGLAND_API_TOKEN="hog-tok", HOGLAND_API_URL=_HOGLAND_URL)+ def test_hogland_bearer_is_withheld_when_the_url_is_not_the_hogland_host(self):+ # A forged sandbox_backend must not send the account bearer to an+ # arbitrary host — the URL host, not the state flag, authorizes it.+ token, param = sandbox_transport_token(+ {"sandbox_backend": "hogland", "sandbox_connect_token": "modal-tok"},+ "https://attacker.example/steal",+ )+ assert (token, param) == ("modal-tok", "_modal_connect_token")++ @override_settings(HOGLAND_API_TOKEN="hog-tok", HOGLAND_API_URL=_HOGLAND_URL)+ @pytest.mark.parametrize(+ "sandbox_url",+ [+ "https://hogland.prod-us.posthog.dev:9999/v1/hogboxes/hb-1/proxy/8080", # wrong port+ "http://hogland.prod-us.posthog.dev/v1/hogboxes/hb-1/proxy/8080", # wrong scheme+ "hogland.prod-us.posthog.dev/v1/hogboxes/hb-1/proxy/8080", # scheme-less -> hostname None+ ],+ ids=["wrong_port", "wrong_scheme", "scheme_less"],+ )+ def test_hogland_bearer_is_withheld_on_origin_mismatch(self, sandbox_url):+ token, param = sandbox_transport_token(+ {"sandbox_backend": "hogland", "sandbox_connect_token": "m"}, sandbox_url+ )+ assert (token, param) == ("m", "_modal_connect_token")++ @override_settings(DEBUG=True)+ @pytest.mark.parametrize(+ "hogland_api_url,sandbox_url,expects_bearer",+ [+ # Local dev (SANDBOX_PROVIDER=hogland, DEBUG) reaches a loopback host over+ # http and must keep the bearer.+ ("http://localhost:8010", "http://localhost:8010/v1/hogboxes/hb-1/proxy/8080", True),+ ("http://127.0.0.1:8010", "http://127.0.0.1:8010/v1/hogboxes/hb-1/proxy/8080", True),+ # A non-loopback http origin must never receive the bearer, even in DEBUG.+ ("http://evil.example.com", "http://evil.example.com/v1/hogboxes/hb-1/proxy/8080", False),+ ],+ ids=["loopback_localhost", "loopback_127", "remote_http"],+ )+ def test_loopback_http_keeps_the_bearer_only_in_debug(self, hogland_api_url, sandbox_url, expects_bearer):+ with override_settings(HOGLAND_API_TOKEN="hog-tok", HOGLAND_API_URL=hogland_api_url):+ token, param = sandbox_transport_token(+ {"sandbox_backend": "hogland", "sandbox_connect_token": "m"}, sandbox_url+ )+ if expects_bearer:+ assert (token, param) == ("hog-tok", "token")+ else:+ assert (token, param) == ("m", "_modal_connect_token")++ @override_settings(DEBUG=False)+ @pytest.mark.parametrize(+ "hogland_api_url,sandbox_url",+ [+ ("http://localhost:8010", "http://localhost:8010/v1/hogboxes/hb-1/proxy/8080"),+ ("http://127.0.0.1:8010", "http://127.0.0.1:8010/v1/hogboxes/hb-1/proxy/8080"),+ ],+ ids=["loopback_localhost", "loopback_127"],+ )+ def test_loopback_http_withholds_the_bearer_outside_debug(self, hogland_api_url, sandbox_url):+ # pytest.ini forces DEBUG=1, so the DEBUG=True case above cannot prove the gate.+ # Flip DEBUG off and the loopback-http exception must close: even a loopback origin+ # falls back to the modal token rather than the account-wide bearer.+ with override_settings(HOGLAND_API_TOKEN="hog-tok", HOGLAND_API_URL=hogland_api_url):+ token, param = sandbox_transport_token(+ {"sandbox_backend": "hogland", "sandbox_connect_token": "m"}, sandbox_url+ )+ assert (token, param) == ("m", "_modal_connect_token")++ def test_hogland_runs_read_the_rotating_token_file_fresh_per_request(self, tmp_path):+ token_path = tmp_path / "token"+ token_path.write_text("rotated-1\n")+ state = {"sandbox_backend": "hogland"}+ with override_settings(+ HOGLAND_API_TOKEN="static-tok", HOGLAND_API_TOKEN_FILE=str(token_path), HOGLAND_API_URL=_HOGLAND_URL+ ):+ first = sandbox_transport_token(state, _HOGLAND_SANDBOX_URL)+ token_path.write_text("rotated-2\n")+ second = sandbox_transport_token(state, _HOGLAND_SANDBOX_URL)+ assert first == ("rotated-1", "token")+ assert second == ("rotated-2", "token")++ @pytest.mark.parametrize(+ "state",+ [+ None,+ {},+ {"sandbox_connect_token": "modal-tok"},+ {"sandbox_backend": "modal", "sandbox_connect_token": "modal-tok"},+ ],+ ids=["no_state", "empty_state", "implicit_modal", "explicit_modal"],+ )+ def test_modal_runs_keep_the_persisted_connect_token(self, state):+ token, param = sandbox_transport_token(state)+ assert param == "_modal_connect_token"+ assert token == (state or {}).get("sandbox_connect_token")+++class TestBuildRequestArgsHoglandParam:+ def test_jwt_plus_hogland_token_travels_in_the_token_query_param(self):+ headers, query_params = _build_request_args("hog-tok", "jwt-tok", token_param="token")+ assert headers["Authorization"] == "Bearer jwt-tok"+ assert query_params == {"token": "hog-tok"}++ def test_hogland_token_never_lands_in_the_authorization_header_without_a_jwt(self):+ # The hogland proxy strips an Authorization header it consumed, so a+ # header-borne token would leave the agent-server no auth context at all.+ headers, query_params = _build_request_args("hog-tok", None, token_param="token")+ assert "Authorization" not in headers+ assert query_params == {"token": "hog-tok"}diff --git a/products/tasks/backend/models.py b/products/tasks/backend/models.pyindex ae70822d1aef..480e614991c0 100644--- a/products/tasks/backend/models.py+++ b/products/tasks/backend/models.py@@ -2092,6 +2092,11 @@ class TaskRun(models.Model):state.pop("sandbox_id", None)state.pop("sandbox_url", None)state.pop("sandbox_jwt_kid", None)+ state.pop("sandbox_connect_token", None)+ # Drop the provider stamp too: the handed-off run re-resolves its backend from+ # scratch, so a stale `hogland` must not survive to outrank the EU guard, the+ # Modal-only fallbacks, or the flag kill switch on the next context resolution.+ state.pop("sandbox_backend", None)self.state = statelogger.info(@@ -2193,7 +2198,7 @@ class TaskRun(models.Model):if state.get("sandbox_id") != sandbox_id:return- for key in ("sandbox_id", "sandbox_url", "sandbox_connect_token", "sandbox_jwt_kid"):+ for key in ("sandbox_id", "sandbox_url", "sandbox_connect_token", "sandbox_jwt_kid", "sandbox_backend"):state.pop(key, None)return cls.mutate_state_atomic(run_id, _mutator)@@ -3160,6 +3165,9 @@ class SandboxSnapshot(UUIDModel):if os.environ.get("MODAL_TOKEN_ID") and os.environ.get("MODAL_TOKEN_SECRET") and not settings.TEST:try:+ # Modal-only: hogland runs never create SandboxSnapshot rows today. When+ # hogland resume snapshots land, this needs a backend branch keyed on the+ # snapshot's provider rather than the MODAL_TOKEN_* env gate above.Sandbox.delete_snapshot(self.external_id)except Exception as e:raise Exception(diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.pyindex 02f45e4053c4..c8b942382e90 100644--- a/products/tasks/backend/presentation/views/api.py+++ b/products/tasks/backend/presentation/views/api.py@@ -2682,6 +2682,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):connection_token=connection.connection_token,sandbox_connect_token=connection.sandbox_connect_token,payload=command_payload,+ sandbox_token_param=connection.sandbox_token_param,)tasks_facade.capture_relay_command_telemetry(@@ -2747,6 +2748,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):- http://127.0.0.1:{port} (Docker sandboxes)- https://*.modal.run (Modal sandboxes)- https://*.modal.host (Modal connect token sandboxes)+ - the exact host of settings.HOGLAND_API_URL (hogland box proxy)"""from urllib.parse import urlparse@@ -2765,6 +2767,10 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):):return True+ hogland_host = urlparse(settings.HOGLAND_API_URL).hostname if settings.HOGLAND_API_URL else None+ if parsed.scheme == "https" and hogland_host and parsed.hostname == hogland_host:+ return True+return False@staticmethod@@ -2773,6 +2779,7 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):connection_token: str | None,sandbox_connect_token: str | None,payload: dict,+ sandbox_token_param: str = "_modal_connect_token",) -> http_requests.Response:headers = {"Content-Type": "application/json",@@ -2781,13 +2788,13 @@ class TaskRunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):command_url = f"{sandbox_url.rstrip('/')}/command"- # Modal connect tokens use Authorization: Bearer for tunnel auth,+ # Tunnel/proxy tokens use Authorization: Bearer at the provider edge,# which conflicts with the JWT auth the agent server expects.- # Pass the Modal token as a query parameter instead so both- # auth mechanisms can coexist.+ # Pass the provider token as a query parameter instead so both+ # auth mechanisms can coexist (Modal: _modal_connect_token; hogland: token).params = {}if sandbox_connect_token:- params["_modal_connect_token"] = sandbox_connect_token+ params[sandbox_token_param] = sandbox_connect_tokenreturn http_requests.post(command_url,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.pyindex 6807f377fd60..67f418d575c2 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@@ -17,6 +17,7 @@ from products.tasks.backend.constants import (AGENT_PROXY_KEEP_STREAM_OPEN_FEATURE_FLAG,CONTINUE_AS_NEW_FEATURE_FLAG,DESKTOP_WORKSPACE_WARM_FEATURE_FLAG,+ HOGLAND_SANDBOX_FEATURE_FLAG,MODAL_NETWORK_ALLOWLIST_FEATURE_FLAG,OVERLAP_CLONE_BOOT_FEATURE_FLAG,PR_BABYSIT_SNAPSHOT_FEATURE_FLAG,@@ -139,6 +140,10 @@ class TaskProcessingContext:# Whether agent peer messaging tools should surface in this run (flag + Pi runtime).# Exposure only: the peers endpoints re-check authorization server-side on every call.peer_messaging_enabled: bool = False+ # Which sandbox provider this run provisions on ("modal" or "hogland"). Captured at+ # workflow start and persisted into TaskRun.state at provision time, so activities+ # and out-of-band consumers route deterministically for the run's whole life.+ sandbox_backend: str = "modal"@propertydef mode(self) -> str:@@ -736,6 +741,76 @@ def _is_modal_network_allowlist_enabled(return enabled+def _resolve_sandbox_backend(+ *,+ distinct_id: str,+ organization_id: str,+ run_id: str,+ state: dict | None,+ task_runtime: str,+ use_modal_vm_sandbox: bool,+ use_modal_network_allowlist: bool,+ custom_image_name: str | None,+) -> str:+ """Pick the sandbox provider for this run.++ Hogland only takes plain default-template ACP runs; anything needing a+ Modal-only feature (VM runtime, custom image, Pi runtime, Modal-level network+ allowlist) stays on Modal even with the flag on. Fails closed to Modal.+ """+ raw_override = (state or {}).get("sandbox_backend")+ override = raw_override if isinstance(raw_override, str) and raw_override in ("modal", "hogland") else None++ # A "modal" override is a kill switch and always wins — forcing Modal is never unsafe.+ if override == "modal":+ log_with_activity_context("sandbox_backend_state_override", run_id=run_id, sandbox_backend="modal")+ return "modal"++ # Hard gates: a "hogland" result (override OR flag) is only allowed when hogland can+ # actually run this run. These sit ahead of the override so a stale or forged `hogland`+ # (e.g. carried across a cloud handoff) can't defeat the EU guard or the Modal-only+ # fallbacks and leave the run with unenforced egress.+ if not settings.HOGLAND_API_URL or not (settings.HOGLAND_API_TOKEN_FILE or settings.HOGLAND_API_TOKEN):+ return "modal"+ # Hogland runs in the US only; EU runs stay on Modal regardless of flag/override state.+ if getattr(settings, "CLOUD_DEPLOYMENT", None) == "EU":+ return "modal"+ if (+ use_modal_vm_sandbox+ or custom_image_name is not None+ or task_runtime == Task.Runtime.PI+ or use_modal_network_allowlist+ ):+ return "modal"++ # Past the gates, a "hogland" override pins the run (the canary lever), no flag eval.+ if override == "hogland":+ log_with_activity_context("sandbox_backend_state_override", run_id=run_id, sandbox_backend="hogland")+ return "hogland"++ try:+ enabled = bool(+ posthoganalytics.feature_enabled(+ HOGLAND_SANDBOX_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("hogland_sandbox_flag_check_failed", run_id=run_id, error=str(e))+ return "modal"++ log_with_activity_context(+ "hogland_sandbox_flag_checked",+ run_id=run_id,+ sandbox_backend="hogland" if enabled else "modal",+ )+ return "hogland" if enabled else "modal"++def _compile_effective_network_policy(allowed_domains: list[str]) -> EffectiveNetworkPolicy:debug_domains = _get_debug_only_domains() if settings.DEBUG else []debug_ports = _get_debug_only_ports() if settings.DEBUG else []@@ -1159,6 +1234,22 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro"debug",f"pr_babysit_enabled: {pr_babysit_enabled} for this task run",)+ sandbox_backend = _resolve_sandbox_backend(+ distinct_id=distinct_id,+ organization_id=organization_id,+ run_id=run_id,+ state=state,+ task_runtime=task.runtime,+ use_modal_vm_sandbox=use_modal_vm_sandbox,+ use_modal_network_allowlist=use_modal_network_allowlist,+ custom_image_name=custom_image_name,+ )+ emit_agent_log(+ run_id,+ "debug",+ f"sandbox_backend: {sandbox_backend} for this task run",+ )+pr_authorship_mode = get_pr_authorship_mode(task, state)user_github_integration_id = Noneif not (is_slack_interaction_state(state) and pr_authorship_mode.value == "user"):@@ -1205,8 +1296,9 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro),json_schema=task.json_schema,ci_prompt=task.ci_prompt,- use_modal_resume_snapshots=True,- use_modal_directory_resume_snapshots=True,+ # Hogland has no resume-snapshot support yet; every run cold-boots there.+ use_modal_resume_snapshots=sandbox_backend != "hogland",+ use_modal_directory_resume_snapshots=sandbox_backend != "hogland",sandbox_event_ingest_enabled=sandbox_event_ingest_enabled,sandbox_rotation_enabled=_is_sandbox_rotation_enabled(distinct_id=distinct_id,@@ -1229,6 +1321,7 @@ def get_task_processing_context(input: GetTaskProcessingContextInput) -> TaskPro),continue_as_new_history_threshold=settings.TASKS_CONTINUE_AS_NEW_HISTORY_THRESHOLD,interactive_max_run_duration_seconds=interactive_max_run_duration_seconds,+ sandbox_backend=sandbox_backend,# v1 scopes peer messaging to Pi runs; the flag check is skipped elsewhere# so ACP runs never even evaluate it.peer_messaging_enabled=task.runtime == Task.Runtime.PIdiff --git a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.pyindex 09d954f905f3..da6fb6e12d7f 100644--- a/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py+++ b/products/tasks/backend/temporal/process_task/activities/provision_sandbox.py@@ -52,11 +52,10 @@ from products.tasks.backend.logic.services.network_policy import ()from products.tasks.backend.logic.services.sandbox import (ExecutionResult,- Sandbox,SandboxBase,SandboxConfig,SandboxTemplate,- get_sandbox_class,+ get_sandbox_class_for_run_backend,get_sandbox_class_for_sandbox_id,sandbox_repo_path,workload_for_origin_product,@@ -690,7 +689,7 @@ def prepare_sandbox_for_repository(input: PrepareSandboxForRepositoryInput) -> Pcustom_image_name=ctx.custom_image_name if ctx.use_modal_vm_sandbox else None,)- sandbox_class = get_sandbox_class()+ sandbox_class = get_sandbox_class_for_run_backend(ctx.sandbox_backend)return PrepareSandboxForRepositoryOutput(sandbox_name=get_sandbox_name_for_task(ctx.task_id),repository=repository,@@ -769,7 +768,7 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr)runtime = sandbox_runtime_label(use_vm_sandbox)- sandbox_backend = modal_sandbox_backend_label()+ sandbox_backend = ctx.sandbox_backend if ctx.sandbox_backend != "modal" else modal_sandbox_backend_label()_apply_modal_network_policy(config, ctx, use_vm_sandbox=use_vm_sandbox)if config.outbound_domain_allowlist is not None:emit_agent_log(@@ -786,7 +785,7 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Crruntime=runtime,sandbox_backend=sandbox_backend,) as sandbox_creation_timer:- sandbox = Sandbox.create(config)+ sandbox = get_sandbox_class_for_run_backend(ctx.sandbox_backend).create(config)# The provider's TTL clock starts here — the usage ledger anchors its# kill deadline on this boundary, not on when the row is opened below.sandbox_created_at = timezone.now()@@ -846,6 +845,8 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr"sandbox_url": credentials.url,SANDBOX_JWT_STATE_KID_KEY: jwt_kid,}+ if ctx.sandbox_backend != "modal":+ sandbox_state["sandbox_backend"] = ctx.sandbox_backendif credentials.token:sandbox_state["sandbox_connect_token"] = credentials.tokenTaskRun.update_state_atomic(ctx.run_id, updates=sandbox_state)@@ -884,7 +885,7 @@ def _create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> Cr@activity.defnasync def create_sandbox_for_repository(input: CreateSandboxForRepositoryInput) -> CreateSandboxForRepositoryOutput:- sandbox_class = get_sandbox_class()+ sandbox_class = get_sandbox_class_for_run_backend(input.context.sandbox_backend)if not sandbox_class.supports_creation_cancellation:return await _create_sandbox_for_repository(input)diff --git a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.pyindex df4ef39fc672..3f7b43f87a6e 100644--- a/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/relay_sandbox_events.py@@ -19,7 +19,7 @@ from temporalio.exceptions import ApplicationErrorfrom posthog.temporal.common.utils import close_db_connections-from products.tasks.backend.logic.services.agent_command import validate_sandbox_url+from products.tasks.backend.logic.services.agent_command import sandbox_transport_token, validate_sandbox_urlfrom products.tasks.backend.logic.services.connection_token import create_sandbox_connection_tokenfrom products.tasks.backend.logic.services.permission_broker import (parse_permission_request,@@ -60,6 +60,19 @@ TERMINAL_NOTIFICATION_METHODS = frozenset(FINAL_MESSAGE_MAX_CHARS = 20_000+def _sanitize_httpx_error(e: httpx.HTTPStatusError) -> str:+ """str(e) without the request URL's query string.++ The relayed request carries the sandbox transport token (the account-wide+ Hogland bearer, for hogland runs) as a query param. httpx's default error+ message embeds the full request URL, so logging str(e) verbatim would copy+ that credential into application logs on every 5xx from the sandbox.+ """+ url = e.request.url+ redacted_url = url.copy_with(query=b"redacted") if url.query else url+ return f"Server error '{e.response.status_code}' for url '{redacted_url}'"++class FinalMessageTracker:def __init__(self) -> None:self._current_turn_parts: list[str] = []@@ -152,8 +165,11 @@ async def _relay_sandbox_events(input: RelaySandboxEventsInput, *, finalize_stre"Authorization": f"Bearer {connection_token}","Accept": "text/event-stream",}+ transport_token, token_param = sandbox_transport_token(task_run.state, input.sandbox_url)params: dict[str, str] = {}- if input.sandbox_connect_token:+ if transport_token:+ params[token_param] = transport_token+ elif input.sandbox_connect_token:params["_modal_connect_token"] = input.sandbox_connect_tokenevents_url = f"{input.sandbox_url.rstrip('/')}/events"@@ -572,7 +588,7 @@ async def _relay_loop("relay_sandbox_events_http_error",run_id=run_id,status_code=status,- error=str(e),+ error=_sanitize_httpx_error(e),reconnect_count=reconnect_count,)await asyncio.sleep(min(reconnect_count * 2, 10))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.pyindex 0254328a16c5..d680c4e774ec 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@@ -1,3 +1,5 @@+from typing import Any+import pytestfrom unittest.mock import patch@@ -38,6 +40,7 @@ from products.tasks.backend.temporal.process_task.activities.get_task_processing_is_rtk_enabled,_is_sandbox_event_ingest_enabled,_resolve_modal_vm_sandbox,+ _resolve_sandbox_backend,get_task_processing_context,)from products.tasks.backend.temporal.process_task.utils import get_actor_distinct_id@@ -1330,3 +1333,112 @@ class TestGetTaskProcessingContextActivity:assert result.model is Noneassert result.reasoning_effort is Noneassert result.initial_permission_mode is None+++_HOGLAND_SETTINGS = {"HOGLAND_API_URL": "https://hogland.example", "HOGLAND_API_TOKEN": "hog-tok"}+++class TestResolveSandboxBackend:+ def _resolve(self, **overrides):+ kwargs: dict[str, Any] = {+ "distinct_id": "user-1",+ "organization_id": "org-1",+ "run_id": "run-1",+ "state": None,+ "task_runtime": "acp",+ "use_modal_vm_sandbox": False,+ "use_modal_network_allowlist": False,+ "custom_image_name": None,+ }+ kwargs.update(overrides)+ return _resolve_sandbox_backend(**kwargs)++ def _resolve_with_flag(self, flag_enabled, **overrides):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ return_value=flag_enabled,+ ):+ return self._resolve(**overrides)++ @override_settings(**_HOGLAND_SETTINGS)+ def test_flag_routes_a_plain_run_to_hogland(self):+ assert self._resolve_with_flag(True) == "hogland"+ assert self._resolve_with_flag(False) == "modal"++ @pytest.mark.parametrize(+ "overrides",+ [+ {"use_modal_vm_sandbox": True},+ {"custom_image_name": "posthog-sandbox-custom-x"},+ {"task_runtime": "pi"},+ {"use_modal_network_allowlist": True},+ ],+ ids=["vm_runtime", "custom_image", "pi_runtime", "modal_network_allowlist"],+ )+ @override_settings(**_HOGLAND_SETTINGS)+ def test_modal_only_features_fall_back_to_modal_even_with_the_flag_on(self, overrides):+ assert self._resolve_with_flag(True, **overrides) == "modal"++ @override_settings(**_HOGLAND_SETTINGS, CLOUD_DEPLOYMENT="EU")+ def test_eu_stays_on_modal(self):+ assert self._resolve_with_flag(True) == "modal"++ @override_settings(+ HOGLAND_API_URL="https://hogland.example",+ HOGLAND_API_TOKEN=None,+ HOGLAND_API_TOKEN_FILE="/var/run/secrets/hogland.posthog.dev/token",+ )+ def test_token_file_alone_enables_hogland_routing(self):+ assert self._resolve_with_flag(True) == "hogland"++ @override_settings(HOGLAND_API_URL=None, HOGLAND_API_TOKEN=None, HOGLAND_API_TOKEN_FILE=None)+ def test_unconfigured_hogland_stays_on_modal_without_evaluating_the_flag(self):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ ) as feature_enabled_mock:+ assert self._resolve() == "modal"+ feature_enabled_mock.assert_not_called()++ @override_settings(**_HOGLAND_SETTINGS)+ def test_flag_evaluation_failure_fails_closed_to_modal(self):+ with patch(+ "products.tasks.backend.temporal.process_task.activities.get_task_processing_context.posthoganalytics.feature_enabled",+ side_effect=RuntimeError("flag service down"),+ ):+ assert self._resolve() == "modal"++ @pytest.mark.parametrize(+ "override,flag_enabled,expected",+ [+ ("hogland", False, "hogland"),+ ("modal", True, "modal"),+ ],+ ids=["pin_hogland", "pin_modal"],+ )+ @override_settings(**_HOGLAND_SETTINGS)+ def test_state_override_wins_over_the_flag(self, override, flag_enabled, expected):+ assert self._resolve_with_flag(flag_enabled, state={"sandbox_backend": override}) == expected++ @override_settings(**_HOGLAND_SETTINGS, CLOUD_DEPLOYMENT="EU")+ def test_hogland_override_cannot_defeat_the_eu_guard(self):+ # A stale/forged hogland override (e.g. surviving a cloud handoff) must not run an+ # EU run on hogland — the capability gates sit ahead of the override.+ assert self._resolve_with_flag(True, state={"sandbox_backend": "hogland"}) == "modal"++ @pytest.mark.parametrize(+ "overrides",+ [+ {"use_modal_vm_sandbox": True},+ {"custom_image_name": "img"},+ {"use_modal_network_allowlist": True},+ ],+ ids=["vm", "custom_image", "network_allowlist"],+ )+ @override_settings(**_HOGLAND_SETTINGS)+ def test_hogland_override_cannot_defeat_modal_only_fallbacks(self, overrides):+ assert self._resolve_with_flag(True, state={"sandbox_backend": "hogland"}, **overrides) == "modal"++ @override_settings(**_HOGLAND_SETTINGS)+ def test_modal_override_still_wins_even_when_hogland_is_available(self):+ # The kill switch must always work.+ assert self._resolve_with_flag(True, state={"sandbox_backend": "modal"}) == "modal"diff --git a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.pyindex 66a6ef44e548..69c72b12d483 100644--- a/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py+++ b/products/tasks/backend/temporal/process_task/activities/tests/test_relay_sandbox_events.py@@ -31,6 +31,7 @@ from products.tasks.backend.temporal.process_task.activities.relay_sandbox_event_mark_sandbox_error_best_effort,_persist_final_message,_relay_loop,+ _sanitize_httpx_error,_should_signal_workflow_heartbeat,relay_sandbox_events,)@@ -192,6 +193,28 @@ class TestIsKeepaliveEvent:assert _is_keepalive_event(event_data) == expected+class TestSanitizeHttpxError:+ def test_redacts_query_string_carrying_the_transport_token(self) -> None:+ request = httpx.Request("GET", "https://hogland.example/events?token=super-secret-bearer")+ response = httpx.Response(503, request=request)+ error = httpx.HTTPStatusError("boom", request=request, response=response)++ sanitized = _sanitize_httpx_error(error)++ assert "super-secret-bearer" not in sanitized+ assert "hogland.example/events" in sanitized+ assert "503" in sanitized++ def test_leaves_url_without_a_query_string_untouched(self) -> None:+ request = httpx.Request("GET", "https://hogland.example/events")+ response = httpx.Response(500, request=request)+ error = httpx.HTTPStatusError("boom", request=request, response=response)++ sanitized = _sanitize_httpx_error(error)++ assert sanitized == "Server error '500' for url 'https://hogland.example/events'"++class TestAgentActiveReactivation:"""Verify that agent_active is only re-activated by session/update events.diff --git a/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.py b/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.pyindex e1aaaac240b0..d57b6503a818 100644--- a/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.py+++ b/products/tasks/backend/tests/test_cold_run_path_after_prewarm_removal.py@@ -46,7 +46,10 @@ class TestPrewarmArtifactsRemoved(SimpleTestCase):class TestColdProvisionPathIntact(SimpleTestCase):def test_create_activity_cold_creates_via_sandbox_create(self):source = inspect.getsource(provision_sandbox._create_sandbox_for_repository)- assert "Sandbox.create(config)" in source+ # The cold path resolves the provider per run and calls create() on it+ # (get_sandbox_class_for_backend(...).create(config)); the guard is that+ # it still creates a sandbox rather than taking a prewarm shortcut.+ assert ".create(config)" in sourcefor token in PREWARM_TOKENS:assert token not in source, f"create_sandbox_for_repository still references {token}"diff --git a/products/tasks/backend/tests/test_models.py b/products/tasks/backend/tests/test_models.pyindex 317822e63820..4182bd0edbe1 100644--- a/products/tasks/backend/tests/test_models.py+++ b/products/tasks/backend/tests/test_models.py@@ -860,6 +860,8 @@ class TestTaskRun(TestCase):"sandbox_id": "old-sandbox","sandbox_url": "https://old-sandbox.test","sandbox_jwt_kid": "old-key",+ "sandbox_connect_token": "old-tunnel-token",+ "sandbox_backend": "hogland","snapshot_external_id": "snapshot-1","pending_user_message": "Review the attachment","pending_user_artifact_ids": ["artifact-1"],@@ -871,6 +873,10 @@ class TestTaskRun(TestCase):self.assertNotIn("sandbox_id", run.state)self.assertNotIn("sandbox_url", run.state)self.assertNotIn("sandbox_jwt_kid", run.state)+ self.assertNotIn("sandbox_connect_token", run.state)+ # The provider stamp must not survive; a stale `hogland` would otherwise outrank+ # the EU guard and Modal-only fallbacks when the handed-off run re-resolves.+ self.assertNotIn("sandbox_backend", run.state)self.assertNotIn("pending_user_message", run.state)self.assertNotIn("pending_user_artifact_ids", run.state)self.assertEqual(run.state["snapshot_external_id"], "snapshot-1")diff --git a/products/tasks/backend/tests/test_sandbox_url_validation.py b/products/tasks/backend/tests/test_sandbox_url_validation.pynew file mode 100644index 000000000000..b15e35bf24a7--- /dev/null+++ b/products/tasks/backend/tests/test_sandbox_url_validation.py@@ -0,0 +1,29 @@+import pytest++from django.test import override_settings++from products.tasks.backend.presentation.views.api import TaskRunViewSet+++class TestIsValidSandboxUrl:+ @pytest.mark.parametrize(+ "url,expected",+ [+ ("https://abc123.modal.host/command", True),+ ("https://abc.modal.run/events", True),+ ("https://hogland.prod-us.posthog.dev/v1/hogboxes/hb-1/proxy/8080/command", True),+ # An attacker-shaped lookalike host must not pass the exact-host check.+ ("https://hogland.prod-us.posthog.dev.evil.example/command", False),+ ("https://evil.example/command", False),+ ("http://hogland.prod-us.posthog.dev/command", False),+ ],+ )+ @override_settings(HOGLAND_API_URL="https://hogland.prod-us.posthog.dev")+ def test_allowlist(self, url, expected):+ assert TaskRunViewSet._is_valid_sandbox_url(url) is expected++ def test_hogland_host_not_allowed_when_unconfigured(self):+ with override_settings(HOGLAND_API_URL=None):+ assert not TaskRunViewSet._is_valid_sandbox_url(+ "https://hogland.prod-us.posthog.dev/v1/hogboxes/hb-1/proxy/8080/command"+ )