: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 local Modal agent overlays reliable (#69913)
Alessandro Pogliaghid2b4c86ff165
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.mdindex 16f9b44be94c..f8b33762fd30 100644--- a/docs/internal/sandboxes-setup-guide.md+++ b/docs/internal/sandboxes-setup-guide.md@@ -203,11 +203,11 @@ cd /path/to/posthog-code/packages/agent && pnpm build### Sandbox providers-| Provider | `.env` value | When to use |-| ----------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `modal` (default) | `SANDBOX_PROVIDER=modal` | Production. Uses the published `@posthog/agent` npm package from the GHCR image. |-| `MODAL_DOCKER` | `SANDBOX_PROVIDER=MODAL_DOCKER` | **Local development with Modal.** Same as `modal` but uses a separate Modal app (`posthog-sandbox-modal-docker-*`) so local image builds don't pollute the production app cache. When `LOCAL_POSTHOG_CODE_MONOREPO_ROOT` is set, the local agent packages are overlaid onto the image. |-| `docker` | `SANDBOX_PROVIDER=docker` | Local-only Docker containers (`DEBUG=True` required). No Modal account needed. This is the recommended option for local development. |+| Provider | `.env` value | When to use |+| ----------------- | ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `modal` (default) | `SANDBOX_PROVIDER=modal` | Production. Uses the published `@posthog/agent` npm package from the GHCR image. |+| `MODAL_DOCKER` | `SANDBOX_PROVIDER=MODAL_DOCKER` | **Local development with Modal.** Same as `modal` but uses a separate Modal app (`posthog-sandbox-modal-docker-*`) so local image builds don't pollute the production app cache. When `LOCAL_POSTHOG_CODE_MONOREPO_ROOT` is set, each local package's external runtime dependencies are installed and its compiled output is overlaid onto the image. |+| `docker` | `SANDBOX_PROVIDER=docker` | Local-only Docker containers (`DEBUG=True` required). No Modal account needed. This is the recommended option for local development. |### Sandbox templates@@ -241,10 +241,11 @@ repositories.When both `SANDBOX_PROVIDER=MODAL_DOCKER` and `LOCAL_POSTHOG_CODE_MONOREPO_ROOT` are set:-1. The Dockerfile is built in a temp context with your local `packages/agent`, `packages/shared`, and `packages/git` copied in-2. `pnpm pack` + `pnpm install` replaces the published npm package with your local build-3. The image is pushed to a separate Modal app (`posthog-sandbox-modal-docker-default`) so it doesn't affect production-4. The first build takes a few minutes; subsequent builds reuse Modal's layer cache+1. The selected sandbox Dockerfile is built in a temporary context+2. External runtime dependencies from local `packages/agent`, `packages/shared`, and `packages/git` manifests that are missing from the published image are installed at `/scripts`; required system compatibility packages such as musl for Codex are installed with them, while `workspace:*` dependencies continue to resolve through the overlaid packages+3. Each local package's built `dist/` directory is mounted over the published package's compiled output+4. The image runs in a separate Modal app (`posthog-sandbox-modal-docker-default`) so it doesn't affect production+5. The first build takes a few minutes; subsequent builds reuse Modal's layer cacheAfter changing agent-server code, rebuild and restart the worker:diff --git a/products/tasks/backend/logic/services/local_packages.py b/products/tasks/backend/logic/services/local_packages.pyindex 0506cc75b52b..dcfdc6a5c055 100644--- a/products/tasks/backend/logic/services/local_packages.py+++ b/products/tasks/backend/logic/services/local_packages.py@@ -11,6 +11,7 @@ Only active in DEBUG mode — production always uses the registry image.from __future__ import annotationsimport os+import jsonimport loggingfrom dataclasses import dataclassfrom pathlib import Path@@ -75,3 +76,28 @@ def get_local_posthog_code_packages() -> tuple[LocalPackage, ...] | None:return Nonereturn packages+++def get_local_package_runtime_dependencies(packages: tuple[LocalPackage, ...]) -> dict[str, dict[str, str]]:+ """Collect registry dependencies needed by the overlaid local package builds."""+ dependencies: dict[str, dict[str, str]] = {}++ for package in packages:+ manifest_path = package.source_path / "package.json"+ manifest = json.loads(manifest_path.read_text())+ package_dependencies = manifest.get("dependencies", {})+ if not isinstance(package_dependencies, dict):+ raise ValueError(f"Expected dependencies to be an object in {manifest_path}")++ runtime_dependencies: dict[str, str] = {}+ for name, version in package_dependencies.items():+ if not isinstance(name, str) or not isinstance(version, str):+ raise ValueError(f"Expected dependency names and versions to be strings in {manifest_path}")+ if version.startswith("workspace:"):+ continue+ runtime_dependencies[name] = version++ if runtime_dependencies:+ dependencies[package.name] = dict(sorted(runtime_dependencies.items()))++ return dependenciesdiff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.pyindex 71a2628b0997..5fee2937dc14 100644--- a/products/tasks/backend/logic/services/modal_sandbox.py+++ b/products/tasks/backend/logic/services/modal_sandbox.py@@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Any, castfrom django.conf import settingsfrom cachetools import TTLCache, cached+from semantic_version import NpmSpecif TYPE_CHECKING:from products.tasks.backend.temporal.process_task.utils import McpServerConfig@@ -64,7 +65,10 @@ from products.tasks.backend.logic.services.agentsh import (generate_env_wrapper,generate_policy_yaml,)-from products.tasks.backend.logic.services.local_packages import get_local_posthog_code_packages+from products.tasks.backend.logic.services.local_packages import (+ get_local_package_runtime_dependencies,+ get_local_posthog_code_packages,+)from products.tasks.backend.logic.services.local_skills import (BUILT_SKILLS_RELATIVE_PATH as LOCAL_BUILT_SKILLS_PATH,LocalSkillsCache,@@ -271,19 +275,65 @@ def _get_sandbox_image_reference(image: str = SANDBOX_IMAGE) -> str:AGENT_SERVER_TEMPLATES = frozenset({SandboxTemplate.DEFAULT_BASE, SandboxTemplate.VM_BASE})+def _merge_runtime_dependency_specs(name: str, existing: str, candidate: str) -> str:+ if existing == candidate:+ return existing++ try:+ NpmSpec(existing)+ NpmSpec(candidate)+ except ValueError as error:+ raise ValueError(+ f"Conflicting non-semver runtime dependency specs for {name}: {existing!r} and {candidate!r}"+ ) from error++ return f"{existing} {candidate}"++def _attach_local_package_mounts(image: modal.Image, template: SandboxTemplate) -> modal.Image:"""Overlay each local package's built `dist/` dir onto the installed packagevia add_local_dir(copy=False). No-op unless `template` bundles the agent-serverand local packages are available.- Transitive deps are resolved from the baked /scripts/node_modules/ tree;- only compiled output is swapped live.+ Install external runtime dependencies that are missing from the published image+ before mounting the compiled output. The published package can lag behind a local+ branch, but running npm inside it would also process unpublished workspace packages."""if template not in AGENT_SERVER_TEMPLATES:return imagepackages = get_local_posthog_code_packages()if not packages:return image++ dependencies = get_local_package_runtime_dependencies(packages)+ if dependencies:+ if any("@openai/codex" in package_dependencies for package_dependencies in dependencies.values()):+ image = image.apt_install("musl")++ runtime_dependencies: dict[str, str] = {}+ for package_dependencies in dependencies.values():+ for name, version in package_dependencies.items():+ if existing_version := runtime_dependencies.get(name):+ runtime_dependencies[name] = _merge_runtime_dependency_specs(name, existing_version, version)+ continue+ runtime_dependencies[name] = version++ dependency_json = json.dumps(runtime_dependencies, separators=(",", ":"), sort_keys=True)+ merge_manifest_script = (+ 'const fs=require("fs");'+ 'const path="/scripts/package.json";'+ 'const manifest=JSON.parse(fs.readFileSync(path,"utf8"));'+ "const dependencies=JSON.parse(process.argv[1]);"+ "manifest.dependencies={...(manifest.dependencies||{}),...dependencies};"+ "fs.writeFileSync(path,JSON.stringify(manifest));"+ )+ install_command = (+ f"node -e {shlex.quote(merge_manifest_script)} {shlex.quote(dependency_json)} && "+ "npm install --prefix /scripts --package-lock=false "+ "--omit=dev --no-audit --no-fund"+ )+ image = image.run_commands(install_command)+for package in packages:image = image.add_local_dir(str(package.build_output_path),@@ -880,6 +930,12 @@ class ModalSandbox(SandboxBase):f"{create_pr_flag}{auto_publish_flag}{branch_flag}{mcp_servers_arg}{domains_flag}{repo_ready_flag}")+ if repo_ready_file:+ # Keep the adapter process from inheriting a repository cwd that does not+ # exist yet, even if an overlaid agent-server mishandles its readiness flag.+ wait_for_repo = f"while [ ! -f {shlex.quote(repo_ready_file)} ]; do sleep 0.1; done; exec {server_cmd}"+ server_cmd = f"bash -c {shlex.quote(wait_for_repo)}"+inner = f"cd /scripts && {server_cmd} > /tmp/agent-server.log 2>&1"if allowed_domains is not None:diff --git a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py b/products/tasks/backend/logic/services/tests/test_modal_sandbox.pyindex 05555145c3af..803c8b4a5f96 100644--- a/products/tasks/backend/logic/services/tests/test_modal_sandbox.py+++ b/products/tasks/backend/logic/services/tests/test_modal_sandbox.py@@ -1,5 +1,8 @@+import json+import shleximport asyncioimport builtins+from pathlib import Pathfrom typing import Anyimport pytest@@ -18,6 +21,7 @@ from products.tasks.backend.exceptions import (SnapshotCreationError,SnapshotTimeoutError,)+from products.tasks.backend.logic.services.local_packages import LocalPackagefrom products.tasks.backend.logic.services.modal_provision_diagnostics import (MAX_PROVISION_LOG_EXCERPT_LINES,summarize_modal_output,@@ -29,9 +33,11 @@ from products.tasks.backend.logic.services.modal_sandbox import (DIRECTORY_SNAPSHOT_TIMEOUT_SECONDS,SANDBOX_IMAGE,ModalSandbox,+ _attach_local_package_mounts,_get_modal_region,_get_sandbox_image_reference,_image_ref_cache,+ _merge_runtime_dependency_specs,_resource_create_kwargs,)from products.tasks.backend.logic.services.sandbox import (@@ -271,6 +277,95 @@ class TestGetModalRegion:assert _get_modal_region() == expected_region+class TestAttachLocalPackageMounts:+ @pytest.mark.parametrize(+ "existing,candidate",+ [+ ("github:example/runtime#v1", "github:example/runtime#v2"),+ ("git+https://example.com/runtime.git#v1", "git+https://example.com/runtime.git#v2"),+ ("file:../runtime-v1", "file:../runtime-v2"),+ ("https://example.com/runtime-v1.tgz", "https://example.com/runtime-v2.tgz"),+ ("npm:runtime-v1@^1.0.0", "npm:runtime-v2@^1.0.0"),+ ("latest", "next"),+ ],+ )+ def test_rejects_conflicting_non_semver_runtime_dependency_specs(self, existing: str, candidate: str) -> None:+ with pytest.raises(ValueError, match="Conflicting non-semver runtime dependency specs for runtime"):+ _merge_runtime_dependency_specs("runtime", existing, candidate)++ def test_installs_runtime_dependencies_before_mounting_local_builds(self, tmp_path: Path) -> None:+ source_path = tmp_path / "agent"+ build_output_path = source_path / "dist"+ build_output_path.mkdir(parents=True)+ (source_path / "package.json").write_text(+ json.dumps(+ {+ "dependencies": {+ "@openai/codex": "0.140.0",+ "custom-runtime": "github:example/custom-runtime#v1.2.3",+ "@posthog/shared": "workspace:*",+ "zod": "^4.2.0",+ }+ }+ )+ )+ package = LocalPackage(+ name="agent",+ source_path=source_path,+ sandbox_install_path="/scripts/node_modules/@posthog/agent",+ )+ shared_source_path = tmp_path / "shared"+ shared_build_output_path = shared_source_path / "dist"+ shared_build_output_path.mkdir(parents=True)+ (shared_source_path / "package.json").write_text(json.dumps({"dependencies": {"zod": "^4.1.12"}}))+ shared_package = LocalPackage(+ name="shared",+ source_path=shared_source_path,+ sandbox_install_path="/scripts/node_modules/@posthog/shared",+ )+ base_image = MagicMock()+ system_dependency_image = MagicMock()+ dependency_image = MagicMock()+ mounted_image = MagicMock()+ final_image = MagicMock()+ base_image.apt_install.return_value = system_dependency_image+ system_dependency_image.run_commands.return_value = dependency_image+ dependency_image.add_local_dir.return_value = mounted_image+ mounted_image.add_local_dir.return_value = final_image++ with patch(+ "products.tasks.backend.logic.services.modal_sandbox.get_local_posthog_code_packages",+ return_value=(package, shared_package),+ ):+ result = _attach_local_package_mounts(base_image, SandboxTemplate.DEFAULT_BASE)++ base_image.apt_install.assert_called_once_with("musl")+ command = system_dependency_image.run_commands.call_args.args[0]+ command_parts = shlex.split(command)+ assert command_parts[:2] == ["node", "-e"]+ assert json.loads(command_parts[3]) == {+ "@openai/codex": "0.140.0",+ "custom-runtime": "github:example/custom-runtime#v1.2.3",+ "zod": "^4.2.0 ^4.1.12",+ }+ assert "npm install --prefix /scripts" in command+ assert "[ -d " not in command+ assert "@openai/[email protected]" not in command+ assert "custom-runtime@github:" not in command+ assert "@posthog/shared" not in command+ dependency_image.add_local_dir.assert_called_once_with(+ str(build_output_path),+ "/scripts/node_modules/@posthog/agent/dist",+ copy=False,+ )+ mounted_image.add_local_dir.assert_called_once_with(+ str(shared_build_output_path),+ "/scripts/node_modules/@posthog/shared/dist",+ copy=False,+ )+ assert result is final_image++class TestModalSandboxAgentServer:@pytest.fixturedef mock_sandbox(self) -> Any:@@ -353,6 +448,24 @@ class TestModalSandboxAgentServer:assert "agentsh exec" not in commandassert "nohup" in command+ def test_start_agent_server_waits_for_repository_before_launch(self, mock_sandbox: Any):+ mock_sandbox.execute = MagicMock(+ return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),+ )++ mock_sandbox.start_agent_server(+ repository="posthog/posthog",+ task_id="task-123",+ run_id="run-456",+ mode="background",+ repo_ready_file="/tmp/workspace/.repo-ready",+ wait_for_health=False,+ )++ command = _agent_server_launch_command(mock_sandbox.execute)+ assert "while [ ! -f /tmp/workspace/.repo-ready ]; do sleep 0.1; done; exec env" in command+ assert "--repoReadyFile /tmp/workspace/.repo-ready" in command+def test_start_agent_server_wraps_with_agentsh_when_domains_provided(self, mock_sandbox: Any):mock_sandbox.execute = MagicMock(return_value=ExecutionResult(stdout="ok:1", stderr="", exit_code=0, error=None),