: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
fix(tasks): make sandbox guards test-aware, fix provider import cycle (#68732)
Georges-Antoine Assia328aad8bf9a
diff --git a/docs/internal/dev-env-vars.md b/docs/internal/dev-env-vars.mdnew file mode 100644index 000000000000..3cdea4700270--- /dev/null+++ b/docs/internal/dev-env-vars.md@@ -0,0 +1,46 @@+# Where local dev environment variables come from++If an env var is set in your shell but you can't find it in any `.env*` file, it is almost certainly coming from **flox**, not dotenv.+This is the layering, highest precedence first.++## The layers++1. **Your shell** — anything you `export` yourself wins over everything below.+2. **flox `[vars]`** (`.flox/env/manifest.toml`) — injected on every `flox activate`, which `direnv` runs automatically via `.envrc` whenever you `cd` into the repo. This is where `DEBUG=1`, `CLICKHOUSE_DATABASE`, and other always-on dev knobs live. These are **not** in any `.env` file, which is why grepping `.env*` for them comes up empty.+3. **`.env.local`** — your personal, gitignored overrides and secrets (`op://` refs auto-resolve via 1Password). Sourced by `bin/start`.+4. **`.env.development`** — committed dev-mode runtime knobs.+5. **`.env.services`** — committed service connection defaults, shared with containers.++`bin/start` sources `.env.local` > `.env.development` > `.env.services` and only sets a var if it is not already in the environment, so flox `[vars]` and your shell take precedence over the dotenv files.+`python manage.py setup_background_agents` additionally appends a few keys (`DEBUG`, `SANDBOX_PROVIDER`, …) to `.env` from `.env.example`.++## Tracing a var++To find where `FOO` is actually coming from:++```bash+# The flox layer (the usual "invisible" source):+grep -n FOO .flox/env/manifest.toml+# The dotenv layers:+grep -n FOO .env .env.local .env.development .env.services .env.example+# What the activated env actually resolves to:+flox activate -- bash -c 'echo "$FOO"'+```++## Developing cloud-only features locally++Cloud-gated code checks `is_cloud()`, which is true when `CLOUD_DEPLOYMENT` is one of `US`, `EU`, `DEV`, or `E2E`.+`DEBUG` is on by default in local dev (flox `[vars]`), and there is a hard guard (`posthog/settings/utils.py`) that refuses to boot with `DEBUG` **and** `CLOUD_DEPLOYMENT` in `US`/`EU`/`DEV` — because `DEBUG` relaxes authentication, so it must never coincide with a real deployed-cloud identity.++The sanctioned way to run local dev "as cloud" is therefore:++```bash+# in .env.local+CLOUD_DEPLOYMENT=E2E+```++`E2E` is treated as cloud by `is_cloud()` and is the one cloud value allowed alongside `DEBUG`.+Do **not** set `CLOUD_DEPLOYMENT=US` and unset `DEBUG` to get around the guard — unsetting `DEBUG` then trips the sandbox-provider guards (`docker` / `MODAL_DOCKER` require `DEBUG`), and you end up playing whack-a-mole between the two.+Code that branches on the literal region (`get_instance_region()`, `region == "US"`) will see `"E2E"`; for region-specific work, override it per-test with `@override_settings(CLOUD_DEPLOYMENT="US")` (tests are exempt from the guard).++See also [sandboxes-setup-guide.md](sandboxes-setup-guide.md) for the PostHog Code sandbox providers.diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex f304f9f95591..16f9b44be94c 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -257,18 +257,19 @@ cd /path/to/posthog-code/packages/agent && pnpm build## Troubleshooting-| Problem | Solution |-| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| Docker not running | Start Docker Desktop or the Docker daemon |-| Temporal not reachable | Ensure Temporal is running on `127.0.0.1:7233`. Check with `temporal server start-dev` |-| Feature flag not enabled | Re-run `python manage.py setup_background_agents` to (re-)create the `tasks` flag at 100% rollout |-| Array OAuth app missing | Re-run `python manage.py setup_background_agents` |-| GitHub token expired | Tokens from GitHub App installations expire after ~1 hour. Re-run the task to get a fresh token |-| "Task workflow execution blocked" | The `tasks` feature flag is not enabled for this user/org |-| Sandbox image build fails | Check Docker has enough disk space. Delete old images with `docker system prune` |-| Agent server health check fails | Check sandbox logs: `docker exec <container_id> cat /tmp/agent-server.log` |-| `SANDBOX_JWT_PRIVATE_KEY` missing | Re-run `python manage.py setup_background_agents` — it will auto-fill from `.env.example` |-| Port conflict on sandbox host port | DockerSandbox maps container port 47821 to a dynamic host port. Check sandbox logs or TaskRun state for the assigned port; if another process uses it, stop that process or restart Docker |-| Sandbox can't reach PostHog API | Don't set `SANDBOX_API_URL` with Docker — auto-transform handles it. If overriding, use port 8000, not 8010 (Caddy returns empty responses from inside Docker) |-| `DEBUG` not set | `SANDBOX_PROVIDER=docker` requires `DEBUG=1`. Re-run `python manage.py setup_background_agents` to write it |-| `git commit is disabled in PostHog Code` | A PATH shim (`git-guard.sh` at `/opt/posthog/bin/git`) blocks `git commit` and `git push` so unsigned commits can't leave the sandbox. Stage changes with `git add`, then use the `git_signed_commit` tool. To bypass during debugging, set `POSTHOG_ALLOW_UNSIGNED_GIT=1` |+| Problem | Solution |+| -------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Docker not running | Start Docker Desktop or the Docker daemon |+| Temporal not reachable | Ensure Temporal is running on `127.0.0.1:7233`. Check with `temporal server start-dev` |+| Feature flag not enabled | Re-run `python manage.py setup_background_agents` to (re-)create the `tasks` flag at 100% rollout |+| Array OAuth app missing | Re-run `python manage.py setup_background_agents` |+| GitHub token expired | Tokens from GitHub App installations expire after ~1 hour. Re-run the task to get a fresh token |+| "Task workflow execution blocked" | The `tasks` feature flag is not enabled for this user/org |+| Sandbox image build fails | Check Docker has enough disk space. Delete old images with `docker system prune` |+| Agent server health check fails | Check sandbox logs: `docker exec <container_id> cat /tmp/agent-server.log` |+| `SANDBOX_JWT_PRIVATE_KEY` missing | Re-run `python manage.py setup_background_agents` — it will auto-fill from `.env.example` |+| Port conflict on sandbox host port | DockerSandbox maps container port 47821 to a dynamic host port. Check sandbox logs or TaskRun state for the assigned port; if another process uses it, stop that process or restart Docker |+| Sandbox can't reach PostHog API | Don't set `SANDBOX_API_URL` with Docker — auto-transform handles it. If overriding, use port 8000, not 8010 (Caddy returns empty responses from inside Docker) |+| `DEBUG` not set | `SANDBOX_PROVIDER=docker` requires `DEBUG=1`. Re-run `python manage.py setup_background_agents` to write it |+| `... sandbox is for local development only` (RuntimeError at import) | The `docker` / `MODAL_DOCKER` providers require `DEBUG=1` (or `TEST=1`, which pytest sets). `DEBUG=1` is normally injected by the flox env (`.flox/env/manifest.toml` `[vars]`) — this fires when you're outside `flox activate` or explicitly unset `DEBUG` (e.g. to escape the cloud-DEBUG guard). Keep `DEBUG` on and use `CLOUD_DEPLOYMENT=E2E` for cloud-mode dev instead. See [dev-env-vars.md](dev-env-vars.md) |+| `git commit is disabled in PostHog Code` | A PATH shim (`git-guard.sh` at `/opt/posthog/bin/git`) blocks `git commit` and `git push` so unsigned commits can't leave the sandbox. Stage changes with `git add`, then use the `git_signed_commit` tool. To bypass during debugging, set `POSTHOG_ALLOW_UNSIGNED_GIT=1` |diff --git a/posthog/settings/utils.py b/posthog/settings/utils.pyindex a65249e49bbd..fa112d01e042 100644--- a/posthog/settings/utils.py+++ b/posthog/settings/utils.py@@ -26,7 +26,9 @@ def assert_debug_not_in_production(*, debug: bool, cloud_deployment: Optional[stif debug and not test and (cloud_deployment or "").upper() in ("US", "EU", "DEV"):raise ImproperlyConfigured(f"DEBUG must not be enabled on deployed cloud environments (CLOUD_DEPLOYMENT={cloud_deployment!r}). "- "Unset DEBUG."+ "Unset DEBUG. Developing cloud-only features locally? Use CLOUD_DEPLOYMENT=E2E instead — "+ "is_cloud() treats it as cloud and it is allowed with DEBUG. "+ "(DEBUG=1 is injected by the flox env: .flox/env/manifest.toml [vars].)")diff --git a/products/tasks/backend/logic/services/sandbox.py b/products/tasks/backend/logic/services/sandbox.pyindex 268a90147db9..7bb94725b1ef 100644--- a/products/tasks/backend/logic/services/sandbox.py+++ b/products/tasks/backend/logic/services/sandbox.py@@ -397,10 +397,13 @@ SandboxClass = type[SandboxBase]def _get_docker_sandbox_class() -> SandboxClass:- if not settings.DEBUG:+ # Allow TEST too: the guard runs at module import, and pytest loads settings with+ # DEBUG off in some paths — blocking there would kill collection, not production.+ if not (settings.DEBUG or settings.TEST):raise RuntimeError(- "DockerSandbox cannot be used in production. "- "Set DEBUG=True for local development or remove SANDBOX_PROVIDER=docker."+ "DockerSandbox is for local development only. Set DEBUG=1 (the flox env sets this "+ "automatically — are you outside 'flox activate'?) or unset SANDBOX_PROVIDER "+ "(check .env/.env.local and your shell).")from .docker_sandbox import DockerSandbox@@ -414,8 +417,14 @@ def _get_modal_docker_sandbox_class() -> SandboxClass:local image builds with LOCAL_POSTHOG_CODE_MONOREPO_ROOT don'tpollute the production app's image cache."""- if not settings.DEBUG:- raise RuntimeError("MODAL_DOCKER sandbox is for local development only (DEBUG=True).")+ # Allow TEST too: the guard runs at module import, and pytest loads settings with+ # DEBUG off in some paths — blocking there would kill collection, not production.+ if not (settings.DEBUG or settings.TEST):+ raise RuntimeError(+ "MODAL_DOCKER sandbox is for local development only. Set DEBUG=1 (the flox env sets "+ "this automatically — are you outside 'flox activate'?) or unset SANDBOX_PROVIDER "+ "(check .env/.env.local and your shell)."+ )from .modal_sandbox import ModalSandboxclass ModalDockerSandbox(ModalSandbox):@@ -452,7 +461,24 @@ def get_sandbox_class_for_backend(backend: str) -> SandboxClass:raise RuntimeError(f"Unsupported sandbox backend: {backend}")-Sandbox: SandboxClass = get_sandbox_class()+if TYPE_CHECKING:+ # Declared for type-checkers only; resolved at runtime by __getattr__ -> get_sandbox_class().+ Sandbox: SandboxClass+else:++ def __getattr__(name: str) -> object:+ # Resolve `Sandbox` lazily. Computing it at import time calls get_sandbox_class(),+ # which for the docker / modal_docker providers imports a sibling module+ # (docker_sandbox / modal_sandbox). When that sibling is the first of the pair to be+ # imported (e.g. test_docker_sandbox.py imports docker_sandbox, which imports this+ # module), the eager call reaches back into the still-initializing sibling and fails+ # as a circular import. Deferring to first attribute access breaks the cycle.+ if name == "Sandbox":+ sandbox_class = get_sandbox_class()+ globals()["Sandbox"] = sandbox_class # cache so later lookups skip __getattr__+ return sandbox_class+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+__all__ = ["AgentServerResult",diff --git a/products/tasks/backend/logic/services/test_docker_sandbox.py b/products/tasks/backend/logic/services/test_docker_sandbox.pyindex 9c4f6cd99af0..b56d72d026cc 100644--- a/products/tasks/backend/logic/services/test_docker_sandbox.py+++ b/products/tasks/backend/logic/services/test_docker_sandbox.py@@ -5,6 +5,8 @@ from typing import Anyimport pytestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from products.tasks.backend.exceptions import SandboxExecutionError, SandboxProvisionErrorfrom products.tasks.backend.logic.services.docker_sandbox import DockerSandboxfrom products.tasks.backend.logic.services.sandbox import (@@ -43,25 +45,36 @@ def is_ci() -> bool:return os.environ.get("GITHUB_ACTIONS") is not None or os.environ.get("CI") is not None[email protected](is_ci() or not docker_available(), reason="Docker sandbox tests only run locally, not in CI")-class TestSandboxFactory:- """Tests for sandbox factory and production safety."""+class TestSandboxProviderGuard:+ """The docker/modal_docker provider guards run at module import time. They must block+ production (neither DEBUG nor TEST) but never trip test collection, where settings load+ with DEBUG off but TEST on. No Docker daemon needed, so this runs in CI unlike the classes below."""+ @parameterized.expand(+ [+ ("docker_production_blocked", "docker", False, False, True),+ ("docker_local_dev_debug", "docker", True, False, False),+ ("docker_test_context", "docker", False, True, False),+ # MODAL_DOCKER blocked in production — the guard fires before the modal import.+ ("modal_docker_production_blocked", "MODAL_DOCKER", False, False, True),+ ]+ )@patch("products.tasks.backend.logic.services.sandbox.settings")- def test_docker_sandbox_blocked_in_production(self, mock_settings):- mock_settings.SANDBOX_PROVIDER = "docker"- mock_settings.DEBUG = False-- with pytest.raises(RuntimeError, match="DockerSandbox cannot be used in production"):- get_sandbox_class()+ def test_provider_guard(self, _name, provider, debug, test, expect_raise, mock_settings):+ mock_settings.SANDBOX_PROVIDER = provider+ mock_settings.DEBUG = debug+ mock_settings.TEST = test++ if expect_raise:+ with pytest.raises(RuntimeError, match="for local development only"):+ get_sandbox_class()+ else:+ assert get_sandbox_class() is DockerSandbox- @patch("products.tasks.backend.logic.services.sandbox.settings")- def test_docker_sandbox_opt_in_with_debug(self, mock_settings):- mock_settings.SANDBOX_PROVIDER = "docker"- mock_settings.DEBUG = True- sandbox_class = get_sandbox_class()- assert sandbox_class == DockerSandbox[email protected](is_ci() or not docker_available(), reason="Docker sandbox tests only run locally, not in CI")+class TestSandboxFactory:+ """Tests for sandbox factory and production safety."""@patch("products.tasks.backend.logic.services.sandbox.settings")def test_modal_sandbox_default_in_debug(self, mock_settings):