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.

feat(tasks): pass sandbox event ingest environment (#58134)

Alessandro Pogliaghi1a31e4831d0c
diff --git a/products/tasks/backend/services/docker_sandbox.py b/products/tasks/backend/services/docker_sandbox.py
index 0393f526a1b3..66009807cde7 100644
--- a/products/tasks/backend/services/docker_sandbox.py
+++ b/products/tasks/backend/services/docker_sandbox.py
@@ -50,6 +50,7 @@ from .sandbox import (
SandboxTemplate,
build_agent_runtime_env_prefix,
parse_sandbox_repo_mount_map,
+ redact_sandbox_command,
wait_for_health_check,
)
@@ -97,7 +98,7 @@ class DockerSandbox(SandboxBase):
@staticmethod
def _run(args: list[str], check: bool = False, timeout: int | None = None) -> subprocess.CompletedProcess:
"""Run a subprocess command with logging."""
- logger.debug(f"Running: {' '.join(args)}")
+ logger.debug(f"Running: {redact_sandbox_command(' '.join(args))}")
result = subprocess.run(args, capture_output=True, text=True, check=check, timeout=timeout)
if result.stdout:
logger.debug(f"stdout: {result.stdout[:500]}")
@@ -428,7 +429,8 @@ class DockerSandbox(SandboxBase):
timeout_seconds = self.config.default_execution_timeout_seconds
try:
- logger.debug(f"Executing in sandbox {self.id}: {command[:100]}...")
+ redacted_command = redact_sandbox_command(command)
+ logger.debug(f"Executing in sandbox {self.id}: {redacted_command[:100]}...")
result = DockerSandbox._run(
["docker", "exec", self._container_id, "bash", "-c", command],
timeout=timeout_seconds,
@@ -451,7 +453,7 @@ class DockerSandbox(SandboxBase):
logger.exception(f"Failed to execute command: {e}")
raise SandboxExecutionError(
"Failed to execute command",
- {"sandbox_id": self.id, "command": command, "error": str(e)},
+ {"sandbox_id": self.id, "command": redacted_command, "error": str(e)},
cause=e,
)
@@ -471,7 +473,8 @@ class DockerSandbox(SandboxBase):
timeout_seconds = self.config.default_execution_timeout_seconds
try:
- logger.debug(f"Streaming execution in sandbox {self.id}: {command[:100]}...")
+ redacted_command = redact_sandbox_command(command)
+ logger.debug(f"Streaming execution in sandbox {self.id}: {redacted_command[:100]}...")
process = subprocess.Popen(
["docker", "exec", self._container_id, "bash", "-c", command],
stdout=subprocess.PIPE,
@@ -483,7 +486,7 @@ class DockerSandbox(SandboxBase):
logger.exception(f"Failed to start streaming command: {e}")
raise SandboxExecutionError(
"Failed to execute command",
- {"sandbox_id": self.id, "command": command, "error": str(e)},
+ {"sandbox_id": self.id, "command": redacted_command, "error": str(e)},
cause=e,
)
@@ -637,6 +640,7 @@ class DockerSandbox(SandboxBase):
reasoning_effort: str | None = None,
mcp_servers_arg: str = "",
allowed_domains: list[str] | None = None,
+ event_ingest_token: str | None = None,
) -> str:
env_prefix = build_agent_runtime_env_prefix(
interaction_origin=interaction_origin,
@@ -644,6 +648,7 @@ class DockerSandbox(SandboxBase):
provider=provider,
model=model,
reasoning_effort=reasoning_effort,
+ event_ingest_token=event_ingest_token,
)
create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"
branch_flag = f" --baseBranch {shlex.quote(branch)}" if branch else ""
@@ -691,6 +696,7 @@ class DockerSandbox(SandboxBase):
reasoning_effort: str | None = None,
mcp_configs: list[McpServerConfig] | None = None,
allowed_domains: list[str] | None = None,
+ event_ingest_token: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
@@ -730,6 +736,7 @@ class DockerSandbox(SandboxBase):
reasoning_effort,
mcp_servers_arg,
allowed_domains=allowed_domains,
+ event_ingest_token=event_ingest_token,
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
@@ -762,6 +769,7 @@ class DockerSandbox(SandboxBase):
reasoning_effort=reasoning_effort,
mcp_servers_arg=mcp_servers_arg,
allowed_domains=allowed_domains,
+ event_ingest_token=event_ingest_token,
)
if self._launch_and_check(command):
logger.info(f"Agent-server started on port {self._host_port} (without --baseBranch)")
diff --git a/products/tasks/backend/services/modal_sandbox.py b/products/tasks/backend/services/modal_sandbox.py
index 9edbd9cd00a1..2fa3f78553cd 100644
--- a/products/tasks/backend/services/modal_sandbox.py
+++ b/products/tasks/backend/services/modal_sandbox.py
@@ -53,6 +53,7 @@ from products.tasks.backend.services.sandbox import (
WORKING_DIR,
SandboxBase,
build_agent_runtime_env_prefix,
+ redact_sandbox_command,
wait_for_health_check,
)
from products.tasks.backend.temporal.exceptions import (
@@ -419,6 +420,7 @@ class ModalSandbox(SandboxBase):
timeout_seconds = self.config.default_execution_timeout_seconds
try:
+ redacted_command = redact_sandbox_command(command)
process = self._sandbox.exec("bash", "-c", command, timeout=timeout_seconds)
process.wait()
@@ -443,12 +445,15 @@ class ModalSandbox(SandboxBase):
cause=e,
)
except Exception as e:
- capture_exception(e)
- logger.exception(f"Failed to execute command: {e}")
+ redacted_error = redact_sandbox_command(str(e))
+ # Provider exceptions can echo the shell command, so avoid exc_info here.
+ logger.error( # noqa: TRY400
+ "Failed to execute command", extra={"sandbox_id": self.id, "redacted_error": redacted_error}
+ )
raise SandboxExecutionError(
- f"Failed to execute command",
- {"sandbox_id": self.id, "command": command, "error": str(e)},
- cause=e,
+ "Failed to execute command",
+ {"sandbox_id": self.id, "command": redacted_command, "error": redacted_error},
+ cause=RuntimeError(redacted_error),
)
def execute_stream(
@@ -467,6 +472,7 @@ class ModalSandbox(SandboxBase):
timeout_seconds = self.config.default_execution_timeout_seconds
try:
+ redacted_command = redact_sandbox_command(command)
process = self._sandbox.exec("bash", "-c", command, timeout=timeout_seconds)
except TimeoutError as e:
capture_exception(e)
@@ -476,12 +482,15 @@ class ModalSandbox(SandboxBase):
cause=e,
)
except Exception as e:
- capture_exception(e)
- logger.exception(f"Failed to execute command: {e}")
+ redacted_error = redact_sandbox_command(str(e))
+ # Provider exceptions can echo the shell command, so avoid exc_info here.
+ logger.error( # noqa: TRY400
+ "Failed to execute command", extra={"sandbox_id": self.id, "redacted_error": redacted_error}
+ )
raise SandboxExecutionError(
- f"Failed to execute command",
- {"sandbox_id": self.id, "command": command, "error": str(e)},
- cause=e,
+ "Failed to execute command",
+ {"sandbox_id": self.id, "command": redacted_command, "error": redacted_error},
+ cause=RuntimeError(redacted_error),
)
class _ModalExecutionStream:
@@ -596,6 +605,7 @@ class ModalSandbox(SandboxBase):
reasoning_effort: str | None = None,
mcp_servers_arg: str = "",
allowed_domains: list[str] | None = None,
+ event_ingest_token: str | None = None,
) -> str:
env_prefix = build_agent_runtime_env_prefix(
interaction_origin=interaction_origin,
@@ -603,6 +613,7 @@ class ModalSandbox(SandboxBase):
provider=provider,
model=model,
reasoning_effort=reasoning_effort,
+ event_ingest_token=event_ingest_token,
)
create_pr_flag = f" --createPr {shlex.quote('true' if create_pr else 'false')}"
repo_flag = f" --repositoryPath {shlex.quote(repo_path)}" if repo_path else ""
@@ -646,6 +657,7 @@ class ModalSandbox(SandboxBase):
reasoning_effort: str | None = None,
mcp_configs: list[McpServerConfig] | None = None,
allowed_domains: list[str] | None = None,
+ event_ingest_token: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
@@ -683,6 +695,7 @@ class ModalSandbox(SandboxBase):
reasoning_effort,
mcp_servers_arg,
allowed_domains=allowed_domains,
+ event_ingest_token=event_ingest_token,
)
logger.info(f"Starting agent-server in sandbox {self.id} for {repository or 'no-repo'}")
diff --git a/products/tasks/backend/services/sandbox.py b/products/tasks/backend/services/sandbox.py
index 6fb4c53b2b56..b4a968cab928 100644
--- a/products/tasks/backend/services/sandbox.py
+++ b/products/tasks/backend/services/sandbox.py
@@ -12,6 +12,7 @@ This module exports:
from __future__ import annotations
import os
+import re
import shlex
from abc import ABC, abstractmethod
from collections.abc import Callable, Iterable
@@ -83,11 +84,21 @@ PUBLIC_SANDBOX_REPOS: frozenset[str] = frozenset({"posthog/hedgebox", "posthog/.
"""Repos the sandbox is allowed to clone unauthenticated, even when the team has no GitHub integration"""
# TODO: Remove `posthog/.github` when we switch repo discovery to repo-less agent (now it works as a lightweight dummy)
+SENSITIVE_AGENT_RUNTIME_ENV_NAMES: frozenset[str] = frozenset({"POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN"})
+SENSITIVE_AGENT_RUNTIME_ENV_PATTERN = re.compile(
+ r"(?P<name>" + "|".join(re.escape(name) for name in SENSITIVE_AGENT_RUNTIME_ENV_NAMES) + r")="
+ r"(?P<value>'(?:[^']|'\"'\"')*'|\"(?:\\.|[^\"])*\"|\S+)"
+)
+
def is_public_sandbox_repo(repository: str | None) -> bool:
return repository is not None and repository.lower() in PUBLIC_SANDBOX_REPOS
+def redact_sandbox_command(command: str) -> str:
+ return SENSITIVE_AGENT_RUNTIME_ENV_PATTERN.sub(r"\g<name>=<redacted>", command)
+
+
def build_agent_runtime_env_prefix(
*,
interaction_origin: str | None = None,
@@ -95,6 +106,7 @@ def build_agent_runtime_env_prefix(
provider: str | None = None,
model: str | None = None,
reasoning_effort: str | None = None,
+ event_ingest_token: str | None = None,
) -> str:
env_vars = {
"POSTHOG_CODE_INTERACTION_ORIGIN": interaction_origin,
@@ -102,6 +114,7 @@ def build_agent_runtime_env_prefix(
"POSTHOG_CODE_PROVIDER": provider,
"POSTHOG_CODE_MODEL": model,
"POSTHOG_CODE_REASONING_EFFORT": reasoning_effort,
+ "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN": event_ingest_token,
}
assignments = " ".join(
f"{name}={shlex.quote(value)}" for name, value in env_vars.items() if value is not None and value != ""
@@ -210,6 +223,7 @@ class SandboxBase(ABC):
reasoning_effort: str | None = None,
mcp_configs: list[McpServerConfig] | None = None,
allowed_domains: list[str] | None = None,
+ event_ingest_token: str | None = None,
) -> None:
"""Start the agent-server HTTP server in the sandbox.
diff --git a/products/tasks/backend/services/test_docker_sandbox.py b/products/tasks/backend/services/test_docker_sandbox.py
index 7cbd88e8dca7..458e8008ce30 100644
--- a/products/tasks/backend/services/test_docker_sandbox.py
+++ b/products/tasks/backend/services/test_docker_sandbox.py
@@ -12,7 +12,9 @@ from products.tasks.backend.services.sandbox import (
SandboxTemplate,
get_sandbox_class,
parse_sandbox_repo_mount_map,
+ redact_sandbox_command,
)
+from products.tasks.backend.temporal.exceptions import SandboxExecutionError
def docker_available() -> bool:
@@ -71,6 +73,21 @@ class TestSandboxFactory:
class TestDockerSandboxUnit:
"""Unit tests that don't require Docker."""
+ @pytest.mark.parametrize(
+ "command",
+ [
+ "env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token ./node_modules/.bin/agent-server",
+ "bash -c 'env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token ./node_modules/.bin/agent-server'",
+ "env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN='secret token' ./node_modules/.bin/agent-server",
+ ],
+ )
+ def test_redact_sandbox_command_hides_event_ingest_token(self, command):
+ redacted = redact_sandbox_command(command)
+
+ assert "secret-token" not in redacted
+ assert "secret token" not in redacted
+ assert "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=<redacted>" in redacted
+
@pytest.mark.parametrize(
"input_url,expected_url",
[
@@ -152,6 +169,24 @@ class TestDockerSandboxUnit:
assert result.stdout == "hello world"
assert result.stderr == ""
+ @patch("products.tasks.backend.services.docker_sandbox.DockerSandbox._run")
+ def test_execute_redacts_event_ingest_token_from_error_context(self, mock_run):
+ mock_run.side_effect = [
+ MagicMock(stdout="true", returncode=0),
+ RuntimeError("boom"),
+ ]
+
+ sandbox = DockerSandbox.__new__(DockerSandbox)
+ sandbox._container_id = "abc123"
+ sandbox.id = "abc123"
+ sandbox.config = SandboxConfig(name="test")
+
+ with pytest.raises(SandboxExecutionError) as exc:
+ sandbox.execute("env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token agent-server")
+
+ assert exc.value.context["command"] == "env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=<redacted> agent-server"
+ assert "secret-token" not in exc.value.context["command"]
+
@pytest.mark.parametrize(
"repository",
[
@@ -474,6 +509,7 @@ class TestDockerSandboxUnit:
provider="openai",
model="gpt-5.3-codex",
reasoning_effort="medium",
+ event_ingest_token="ingest-token",
)
command = mock_execute.call_args_list[0][0][0]
@@ -481,6 +517,7 @@ class TestDockerSandboxUnit:
assert "POSTHOG_CODE_PROVIDER=openai" in command
assert "POSTHOG_CODE_MODEL=gpt-5.3-codex" in command
assert "POSTHOG_CODE_REASONING_EFFORT=medium" in command
+ assert "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=ingest-token" in command
@pytest.mark.skipif(is_ci() or not docker_available(), reason="Docker sandbox tests only run locally, not in CI")
diff --git a/products/tasks/backend/services/tests/test_modal_sandbox.py b/products/tasks/backend/services/tests/test_modal_sandbox.py
index 66f3ee8275f0..fb5acb587b4a 100644
--- a/products/tasks/backend/services/tests/test_modal_sandbox.py
+++ b/products/tasks/backend/services/tests/test_modal_sandbox.py
@@ -271,6 +271,22 @@ class TestModalSandboxAgentServer:
with pytest.raises(RuntimeError, match="Sandbox not in running state"):
mock_sandbox.get_connect_credentials()
+ @pytest.mark.parametrize("method_name", ["execute", "execute_stream"])
+ def test_execution_redacts_event_ingest_token_from_error_context(self, mock_sandbox: Any, method_name: str):
+ mock_sandbox._sandbox.exec.side_effect = RuntimeError("failed POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token")
+
+ with (
+ patch("products.tasks.backend.services.modal_sandbox.capture_exception") as capture_exception,
+ pytest.raises(SandboxExecutionError) as exc,
+ ):
+ getattr(mock_sandbox, method_name)("env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=secret-token agent-server")
+
+ assert exc.value.context["command"] == "env POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=<redacted> agent-server"
+ assert exc.value.context["error"] == "failed POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=<redacted>"
+ assert "secret-token" not in exc.value.context["command"]
+ assert "secret-token" not in exc.value.context["error"]
+ capture_exception.assert_not_called()
+
def test_start_agent_server_success_without_domains_skips_agentsh(self, mock_sandbox: Any):
mock_sandbox.execute = MagicMock(
side_effect=[
@@ -396,6 +412,7 @@ class TestModalSandboxAgentServer:
provider="openai",
model="gpt-5.3-codex",
reasoning_effort="high",
+ event_ingest_token="ingest-token",
)
command = mock_sandbox.execute.call_args_list[0][0][0]
@@ -403,6 +420,7 @@ class TestModalSandboxAgentServer:
assert "POSTHOG_CODE_PROVIDER=openai" in command
assert "POSTHOG_CODE_MODEL=gpt-5.3-codex" in command
assert "POSTHOG_CODE_REASONING_EFFORT=high" in command
+ assert "POSTHOG_TASK_RUN_EVENT_INGEST_TOKEN=ingest-token" in command
def test_start_agent_server_raises_when_not_running(self, mock_sandbox: Any):
mock_sandbox._sandbox.poll.return_value = 0