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.

refactor(posthog_ai): use Tailscale Funnel for modal eval tunnels (#76539)

Georgiy Tarasovb66c19abe96a
diff --git a/.agents/skills/writing-evals/references/running-evals.md b/.agents/skills/writing-evals/references/running-evals.md
index 02909827d9f8..e337614ed4ad 100644
--- a/.agents/skills/writing-evals/references/running-evals.md
+++ b/.agents/skills/writing-evals/references/running-evals.md
@@ -5,7 +5,7 @@ Both providers keep the eval database, Django server, LLM gateway, MCP server, T
The provider changes only where the coding-agent sandbox runs.
Prefer remote Modal for multi-case sandboxed evals when its prerequisites are available.
Remote sandboxes run in parallel without consuming local Docker memory, which usually shortens the run substantially.
-Use local Docker for a single-case smoke test, offline work, or when Modal and ngrok credentials are unavailable.
+Use local Docker for a single-case smoke test, offline work, or when Modal credentials or a Funnel-capable tailnet are unavailable.
## Shared setup
@@ -87,7 +87,7 @@ Use `--rebuild-sandbox-image` only when a forced image rebuild is part of the di
## Remote setup with Modal (preferred)
Remote sandboxed evals use the dedicated `posthog-sandbox-evals` Modal app.
-Install the `modal` and `ngrok` CLIs and make sure both are on `PATH` inside the flox environment.
+Install the `modal` and `tailscale` CLIs and make sure both are on `PATH` inside the flox environment.
Authenticate Modal once:
@@ -98,21 +98,20 @@ modal token new
This normally writes `~/.modal.toml`.
For non-interactive environments, set both `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET` instead.
-Authenticate ngrok once:
+Connect this machine to your tailnet once:
```bash
-ngrok config add-authtoken '<token>'
+tailscale up
```
-Setting `NGROK_AUTHTOKEN` is the non-interactive alternative.
-The harness generates a temporary ngrok configuration and starts HTTPS tunnels for the local Django API, LLM gateway, and MCP server.
+Funnel additionally needs the `funnel` node attribute granted to the tailnet and this node in the [admin console](https://login.tailscale.com/admin/acls), and HTTPS certificates enabled for the tailnet.
+The harness then exposes the local Django API, LLM gateway, and MCP server over Tailscale Funnel for the duration of the run, one service per Funnel public port (`443`, `8443`, `10000`).
Do not manually set `SANDBOX_API_URL`, `SANDBOX_LLM_GATEWAY_URL`, or `SANDBOX_MCP_URL` for an eval run.
-The automated Modal provider currently requires three simultaneous ngrok tunnels.
-That needs an authenticated paid ngrok plan.
-Cloudflare Tunnel can expose the same services in other development workflows, but it is not wired into `hogli evals --provider modal` and does not satisfy the provider's current ngrok preflight.
+Funnel serves only those three public ports, so the harness refuses to start when your tailnet node already serves one of them rather than clobbering it.
+Free the port first — `tailscale funnel --https=443 off`, and likewise for `8443` and `10000`.
-Start with one remote sandbox to verify credentials, tunnels, and the remote image build:
+Start with one remote sandbox to verify credentials, Funnel, and the remote image build:
```bash
hogli evals '<suite-selector>' \
@@ -131,9 +130,10 @@ Modal concurrency is unbounded by default, so always choose an intentional `--ma
hogli evals '<product-or-domain>' --provider modal --max-sandboxes 4
```
-The harness stops its temporary tunnels during teardown.
+The harness turns its Funnel mappings off during teardown.
It also terminates each case's task-tagged sandbox and sweeps leftovers belonging to the current run.
-The generated tunnel URLs are publicly reachable while the run is active, so do not share them or leave a run unattended after an interruption.
+Funnel config lives in `tailscaled` and outlives the harness process, so a run killed with `SIGKILL` can leave the three ports public — check with `tailscale serve status` and turn them off by hand.
+The Funnel URLs are reachable by anyone on the internet who learns them while the run is active, so do not share them or leave a run unattended after an interruption.
## Diagnosing setup failures
@@ -143,7 +143,8 @@ Frequent causes are:
- Running outside flox, which makes the personhog Rust build fail on its toolchain or OpenSSL dependencies.
- A stopped Docker daemon in local mode.
- Missing `~/.modal.toml` or incomplete `MODAL_TOKEN_ID` / `MODAL_TOKEN_SECRET` credentials in remote mode.
-- An ngrok free plan or missing authtoken, which prevents all three remote tunnels from starting.
+- A stopped `tailscaled`, a node that is not logged in, or a tailnet without the `funnel` node attribute or HTTPS certificates, which stops Funnel from serving the three remote-reachable services.
+- A Funnel public port (`443`, `8443`, `10000`) already serving something else, which the harness refuses to overwrite.
- Passing provider flags to a one-shot-only selection.
- Omitting `LLM_GATEWAY_OPENAI_API_KEY` when selecting `--agent-runtime codex`.
diff --git a/docs/internal/sandboxes-setup-guide.md b/docs/internal/sandboxes-setup-guide.md
index 235a82aff6f3..21d820d59152 100644
--- a/docs/internal/sandboxes-setup-guide.md
+++ b/docs/internal/sandboxes-setup-guide.md
@@ -122,59 +122,34 @@ MODAL_TOKEN_SECRET=<token_secret>
### Tunnel gateway, API, and MCP
If you run in a docker sandbox you don't need to do this. If you are testing with Modal sandboxes, since they run in the cloud and can't reach `localhost` directly,
-you'll need to expose the Django API, LLM gateway, and MCP server via a tunnel (e.g. ngrok or Cloudflare Tunnel).
-
-With ngrok, add tunnels to your ngrok config, `~/.config/ngrok/ngrok.yml` (Linux) or `~/Library/Application Support/ngrok/ngrok.yml` (MacOS):
-
-```yaml
-tunnels:
- django:
- proto: http
- addr: 8000
- gateway:
- proto: http
- addr: 3308
- mcp:
- proto: http
- addr: 8787
-```
+you'll need to expose the Django API, LLM gateway, and MCP server publicly. We use [Tailscale Funnel](https://tailscale.com/kb/1223/funnel).
-**IMPORTANT:** The free version of Ngrok includes on `dev` domain, that will try to cover both tunnels, and it won't work. Use Cloudflare (free). If you want to use ngrok, upgrade to `Hobbyist` plan, create custom domans, and add them to config:
-
-```yaml
-tunnels:
- django:
- proto: http
- addr: 8000
- domain: alexl-django.ngrok.dev
- gateway:
- proto: http
- addr: 3308
- domain: alexl-llmg.ngrok.dev
- mcp:
- proto: http
- addr: 8787
- domain: alexl-mcp.ngrok.dev
-agent:
- authtoken: ...
-```
+The eval harness sets Funnel up and tears it down automatically on a Modal run, so for evals you don't need to do any of this by hand — it only needs the daemon running and Funnel enabled (below). This section is for driving a Modal sandbox manually (e.g. from a task run).
+
+First, install Tailscale, start the daemon, and sign in:
-Then, get an auth token at `https://dashboard.ngrok.com/get-started/your-authtoken` and add it locally (either to ngrok directly, through `ngrok config add-authtoken`, or to the config file).
+```bash
+tailscale up
+```
-After that, start both tunnels:
+Then enable Funnel for the tailnet and this node in the [admin console](https://login.tailscale.com/admin/acls) (grant the `funnel` node attribute) and make sure HTTPS certificates are enabled for the tailnet. Funnel only serves three public ports — `443`, `8443`, and `10000` — which is exactly enough for the three services. Point each one at the corresponding local port:
```bash
-ngrok start --all
+tailscale funnel --bg --https=443 8000 # Django API
+tailscale funnel --bg --https=8443 3308 # LLM gateway
+tailscale funnel --bg --https=10000 8787 # MCP server
```
-Set the resulting URLs in your `.env`:
+Find your node's public hostname (the MagicDNS name) with `tailscale status --json | jq -r .Self.DNSName`, then set the resulting URLs in your `.env` (the `443` service drops the port):
```bash
-SANDBOX_API_URL=https://<django-8000-subdomain>.ngrok-free.app
-SANDBOX_LLM_GATEWAY_URL=https://<gateway-3308-subdomain>.ngrok-free.app
-SANDBOX_MCP_URL=https://<mcp-8787-subdomain>.ngrok-free.app/mcp
+SANDBOX_API_URL=https://<node>.<tailnet>.ts.net
+SANDBOX_LLM_GATEWAY_URL=https://<node>.<tailnet>.ts.net:8443
+SANDBOX_MCP_URL=https://<node>.<tailnet>.ts.net:10000/mcp
```
+Funnel exposes these services to anyone on the internet who learns the URL, so turn the mappings off when you're done: `tailscale funnel --https=443 off` (and likewise for `8443` and `10000`).
+
`SANDBOX_MCP_URL` overrides the `host.docker.internal` default (which only resolves from local Docker sandboxes, not Modal). Without it, sandbox agents can't reach the MCP server and lose access to the PostHog `execute-sql`, query, and tool-calling stack.
### Agent run telemetry (optional)
diff --git a/products/posthog_ai/eval_harness/README.md b/products/posthog_ai/eval_harness/README.md
index c5760dcac59f..11412cf161ca 100644
--- a/products/posthog_ai/eval_harness/README.md
+++ b/products/posthog_ai/eval_harness/README.md
@@ -103,14 +103,14 @@ When npm is unreachable the check warns and reuses the existing image instead of
(The modal DEBUG image is rebuilt by Modal whenever the Dockerfile or build context changes, but a new `@posthog/agent` publish alone does not invalidate it — a known limitation.)
**modal** runs sandboxes remotely.
-Modal's network cannot reach `localhost`, so the harness starts ngrok tunnels itself and points the sandbox at the public URLs.
+Modal's network cannot reach `localhost`, so the harness exposes the host services via Tailscale Funnel itself and points the sandbox at the public URLs.
Eval sandboxes run in the dedicated `posthog-sandbox-evals` Modal app, separate from production and local development sandboxes.
The manual tunnel setup in [`docs/internal/sandboxes-setup-guide.md`](../../../../docs/internal/sandboxes-setup-guide.md) is therefore not needed for evals.
The first modal run pays a one-time remote image build; later runs reuse the cached image until the skills or build context change.
Modal prerequisites, all checked by preflight before anything boots:
-- `ngrok` on `PATH`, plus an authtoken (`NGROK_AUTHTOKEN`, or `ngrok config add-authtoken <token>`). Three simultaneous tunnels need a paid ngrok plan; Cloudflare Tunnel is the free alternative.
+- `tailscale` on `PATH`, with tailscaled running and this node logged in (`tailscale up`). Funnel must be enabled for the tailnet and this node in the admin console's ACLs, with HTTPS certificates enabled. The harness serves Django, the LLM gateway, and MCP on Funnel's three public ports (443, 8443, 10000).
- Modal credentials: `MODAL_TOKEN_ID` and `MODAL_TOKEN_SECRET`, or a `~/.modal.toml` from `modal token new`.
- `SANDBOX_JWT_PRIVATE_KEY` in the environment. The dev key ships in `.env.example`; the harness auto-loads it from `.env`.
diff --git a/products/posthog_ai/eval_harness/harness/AGENTS.md b/products/posthog_ai/eval_harness/harness/AGENTS.md
index 01191be5b9f9..b9c81969c04a 100644
--- a/products/posthog_ai/eval_harness/harness/AGENTS.md
+++ b/products/posthog_ai/eval_harness/harness/AGENTS.md
@@ -90,7 +90,7 @@ Braintrust's `EvalAsync` always dispatches through `eval_async`, and the base `S
Bootstrap registers teardown on an `ExitStack` as each resource comes up, so a failure halfway through still unwinds what already started.
`atexit` hooks plus the subprocess manager's signal handlers cover Ctrl-C, where neither stack unwinds.
-After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 14040 / 15051 / 15052, no `task-sandbox-*` containers, and no Temporal dev server.
+After any change, a Ctrl-C mid-run must leave no listeners on 18000 / 13308 / 18787 / 15051 / 15052, no `task-sandbox-*` containers, no Temporal dev server, and no Tailscale Funnel mappings left enabled on 443 / 8443 / 10000.
Three layers tear a case's sandbox down, outermost last:
@@ -109,11 +109,11 @@ Add a `SandboxProviderStrategy` method rather than a conditional.
Per-case teardown is one such method (`cleanup_case`): the runner calls it after every case, so a docker-only concern like reclaiming a leftover container never leaks into `runner.py` or fires on a Modal run.
`preflight()` must catch a missing prerequisite before any infrastructure boots, and its message must say how to fix it.
-A missing ngrok authtoken, for instance, otherwise surfaces only as a 60-second tunnel timeout.
+A stopped or unauthenticated Tailscale daemon, for instance, must be caught here rather than surfacing only when the first sandbox can't reach the host.
The chosen provider must reach `settings.SANDBOX_PROVIDER` **before `django.setup()`**, which is why `__main__` sets it in the environment (from `SANDBOX_PROVIDER_SETTING`) rather than relying only on the async-phase `override_settings`.
`products.tasks` resolves the sandbox class from that setting exactly once and caches it in module globals, so the first `Sandbox` access wins for the whole process.
-`.env` ships `SANDBOX_PROVIDER=docker`, so setting it late let a `--provider modal` run cache `DockerSandbox` and execute the agent in a local container while still pointing it at the ngrok URLs.
+`.env` ships `SANDBOX_PROVIDER=docker`, so setting it late let a `--provider modal` run cache `DockerSandbox` and execute the agent in a local container while still pointing it at the Tailscale Funnel URLs.
Docker mode hid this because the cached value already matched.
Modal evals use the `MODAL_EVALS` backend, whose sandbox class is pinned to the `posthog-sandbox-evals` Modal app.
diff --git a/products/posthog_ai/eval_harness/harness/README.md b/products/posthog_ai/eval_harness/harness/README.md
index dcceac4bef96..b9a48f51f08d 100644
--- a/products/posthog_ai/eval_harness/harness/README.md
+++ b/products/posthog_ai/eval_harness/harness/README.md
@@ -27,7 +27,7 @@ A run of one-shot suites never pays for — or fails preflight on — the sandbo
| `env_preflight.py` | Loads the repo-root `.env` (stdlib parser, shell wins) and validates per-kind env vars via pydantic models. |
| `ports.py` | The six port constants. Deliberately free of Django imports. |
| `providers.py` | `SandboxProviderStrategy` and its docker/modal implementations: preflight, settings overrides, sandbox TTL, cleanup. |
-| `tunnels.py` | `NgrokTunnels`. Modal only: generates an ngrok config, starts the agent, waits for public URLs. |
+| `tunnels.py` | `TailscaleFunnel`. Modal only: enables Tailscale Funnel on the host services and resolves their public URLs. |
| `requirements.py` | `SuiteKind`, `Infra`, and the kind → infrastructure mapping (with implication closure). |
| `django_env.py` | `setup_django()`, the `NullDbBlocker` shim, and `EvalDatabase` (test database lifecycle). |
| `live_server.py` | `EvalLiveServer`, a session-lifetime Uvicorn server for PostHog's full ASGI application. |
@@ -54,7 +54,7 @@ The bootstrap is deliberately synchronous and runs before any event loop exists,
3. `personhog-replica` (`:15051`) and `personhog-router` (`:15052`) start against the test persons database — before anything can query, so a dead router never poisons the negative group-types cache.
4. `EvalLiveServer` serves PostHog's ASGI application on `0.0.0.0:18000`, including the sandbox event-ingest route.
5. The LLM gateway (`:13308`) and MCP server (`:18787`) start as subprocesses.
-6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding on a new `@posthog/agent` version or Dockerfile change). Modal only: ngrok tunnels come up, exposing the callback services publicly.
+6. Docker only: the `posthog-sandbox-base` image freshness check runs (rebuilding on a new `@posthog/agent` version or Dockerfile change). Modal only: Tailscale Funnel comes up, exposing the callback services publicly.
7. Local skills are built. Docker bind-mounts them; Modal bakes them into the image it builds.
8. The master Hedgebox team is seeded.
@@ -95,8 +95,8 @@ The Temporal worker keeps its own loop on a daemon thread, and the two communica
| | docker | modal |
| ------------------- | ----------------------------- | ------------------------- |
| `SANDBOX_PROVIDER` | `docker` | `MODAL_EVALS` |
-| Service URLs | `host.docker.internal:<port>` | ngrok public URLs |
-| `start()` | base-image freshness check | ngrok tunnels |
+| Service URLs | `host.docker.internal:<port>` | Tailscale Funnel URLs |
+| `start()` | base-image freshness check | Tailscale Funnel |
| Local skills | bind-mounted | baked into the image |
| Default sandbox cap | 4 | unbounded |
| Sandbox TTL | default | case timeout plus margin |
diff --git a/products/posthog_ai/eval_harness/harness/cli.py b/products/posthog_ai/eval_harness/harness/cli.py
index 7f929856c1a6..ba5d052973e7 100644
--- a/products/posthog_ai/eval_harness/harness/cli.py
+++ b/products/posthog_ai/eval_harness/harness/cli.py
@@ -87,7 +87,7 @@ def build_parser() -> argparse.ArgumentParser:
"--provider",
choices=get_args(SandboxProvider),
default=None,
- help="Where sandboxes run (default: docker). 'modal' starts ngrok tunnels so remote sandboxes can reach this host.",
+ help="Where sandboxes run (default: docker). 'modal' exposes this host via Tailscale Funnel so remote sandboxes can reach it.",
)
parser.add_argument("--eval", dest="case_filter", default=None, help="Only run cases whose name contains this.")
parser.add_argument(
diff --git a/products/posthog_ai/eval_harness/harness/lifecycle.py b/products/posthog_ai/eval_harness/harness/lifecycle.py
index 868e445f5bb8..cc7f5ac49abd 100644
--- a/products/posthog_ai/eval_harness/harness/lifecycle.py
+++ b/products/posthog_ai/eval_harness/harness/lifecycle.py
@@ -236,7 +236,7 @@ class SandboxedEvalHarness:
overrides.update(
DEBUG=True, # Required for sandbox URL validation to allow http://localhost
# The sandbox reaches the Django live server with a non-loopback
- # Host header (host.docker.internal, or the ngrok domain); allow it
+ # Host header (host.docker.internal, or the Tailscale Funnel host); allow it
# (test-only) so the agent's event-ingest stream isn't rejected with
# an invalid-host 400.
ALLOWED_HOSTS=["*"],
diff --git a/products/posthog_ai/eval_harness/harness/ports.py b/products/posthog_ai/eval_harness/harness/ports.py
index 4bab2053b998..d91f62b32340 100644
--- a/products/posthog_ai/eval_harness/harness/ports.py
+++ b/products/posthog_ai/eval_harness/harness/ports.py
@@ -9,10 +9,6 @@ DJANGO_LIVE_PORT = 18000
LLM_GATEWAY_PORT = 13308
"""Non-default port to avoid conflicts with a running dev LLM gateway."""
-NGROK_WEB_PORT = 14040
-"""Dedicated ngrok agent API port, so the harness never adopts or collides with
-a developer's already-running ngrok agent on the default 4040."""
-
PERSONHOG_REPLICA_PORT = 15051
"""Non-default port so a dev-stack personhog-replica on 50051 never collides."""
diff --git a/products/posthog_ai/eval_harness/harness/providers.py b/products/posthog_ai/eval_harness/harness/providers.py
index 2b67e7073aa2..0206cf3ff603 100644
--- a/products/posthog_ai/eval_harness/harness/providers.py
+++ b/products/posthog_ai/eval_harness/harness/providers.py
@@ -10,7 +10,7 @@ from pathlib import Path
from typing import Any, ClassVar, Literal
from .ports import DJANGO_LIVE_PORT, LLM_GATEWAY_PORT, MCP_PORT
-from .tunnels import NgrokTunnels, resolve_authtoken
+from .tunnels import TailscaleFunnel, funnel_preflight_error
logger = logging.getLogger(__name__)
@@ -232,7 +232,7 @@ class DockerProviderStrategy(SandboxProviderStrategy):
class ModalProviderStrategy(SandboxProviderStrategy):
- """Remote Modal sandboxes, reached from Modal's network through ngrok tunnels.
+ """Remote Modal sandboxes, reached from Modal's network through Tailscale Funnel.
Runs under the ``MODAL_EVALS`` provider — the same ``ModalSandbox`` class
against the ``posthog-sandbox-evals`` app, so DEBUG-mode eval image builds
@@ -244,23 +244,13 @@ class ModalProviderStrategy(SandboxProviderStrategy):
def __init__(self) -> None:
super().__init__()
- self._tunnels: NgrokTunnels | None = None
+ self._tunnels: TailscaleFunnel | None = None
self._sandbox_app_name: str | None = None
def preflight(self) -> None:
- if shutil.which("ngrok") is None:
- raise PreflightError(
- "`ngrok` not found on PATH. Modal sandboxes run outside this host, so the "
- f"Django API, LLM gateway, and MCP server must be publicly reachable. See {SETUP_GUIDE}."
- )
- if resolve_authtoken() is None:
- # Three simultaneous tunnels need a paid, authenticated agent. Without a
- # token ngrok starts and then fails per-tunnel, which would otherwise
- # surface only as a 60s startup timeout.
- raise PreflightError(
- "No ngrok authtoken found. Set NGROK_AUTHTOKEN, or run `ngrok config add-authtoken <token>` "
- f"with a token from https://dashboard.ngrok.com/get-started/your-authtoken. See {SETUP_GUIDE}."
- )
+ funnel_problem = funnel_preflight_error()
+ if funnel_problem is not None:
+ raise PreflightError(funnel_problem)
has_env_tokens = bool(os.environ.get("MODAL_TOKEN_ID") and os.environ.get("MODAL_TOKEN_SECRET"))
if not has_env_tokens and not (Path.home() / ".modal.toml").exists():
raise PreflightError(
@@ -269,7 +259,7 @@ class ModalProviderStrategy(SandboxProviderStrategy):
)
# SANDBOX_JWT_PRIVATE_KEY and the other env-only prerequisites are validated
# earlier by env_preflight.validate_eval_env(); only checks with non-env
- # fallbacks (ngrok config file, ~/.modal.toml) live here.
+ # fallbacks (the Tailscale daemon, ~/.modal.toml) live here.
def start(self, stack: ExitStack) -> None:
# Resolve the eval sandbox app now, while Django is configured, so cleanup()
@@ -280,7 +270,7 @@ class ModalProviderStrategy(SandboxProviderStrategy):
except Exception:
logger.warning("Could not resolve the Modal eval app; end-of-run sandbox sweep is disabled")
- tunnels = NgrokTunnels(
+ tunnels = TailscaleFunnel(
{
"django": DJANGO_LIVE_PORT,
"gateway": LLM_GATEWAY_PORT,
diff --git a/products/posthog_ai/eval_harness/harness/tunnels.py b/products/posthog_ai/eval_harness/harness/tunnels.py
index 8915fe4055c3..c7af0dc315c9 100644
--- a/products/posthog_ai/eval_harness/harness/tunnels.py
+++ b/products/posthog_ai/eval_harness/harness/tunnels.py
@@ -1,197 +1,227 @@
from __future__ import annotations
-import os
import json
-import time
import shutil
-import signal
import logging
-import tempfile
import subprocess
-from pathlib import Path
+from dataclasses import dataclass
from typing import Any
-from urllib.error import URLError
-from urllib.request import urlopen
-
-import yaml
-
-from .ports import NGROK_WEB_PORT
logger = logging.getLogger(__name__)
SETUP_GUIDE = "docs/internal/sandboxes-setup-guide.md"
-NGROK_DEFAULT_CONFIG_PATHS: tuple[Path, ...] = (
- Path.home() / ".config" / "ngrok" / "ngrok.yml",
- Path.home() / "Library" / "Application Support" / "ngrok" / "ngrok.yml",
- Path.home() / ".ngrok2" / "ngrok.yml",
-)
-"""Where the ngrok agent keeps the token written by ``ngrok config add-authtoken``,
-on Linux, macOS, and the legacy v2 location respectively."""
+FUNNEL_PUBLIC_PORTS: tuple[int, ...] = (443, 8443, 10000)
+"""The only public ports Tailscale Funnel will serve — the daemon rejects any
+other. Three is exactly enough for the harness's Django, LLM gateway, and MCP
+callbacks; each requested service is assigned one in the order the caller lists
+them."""
-class NgrokError(RuntimeError):
- """ngrok tunnels could not be established for the eval run."""
+class TailscaleFunnelError(RuntimeError):
+ """Tailscale Funnel could not expose the host services for the eval run."""
-def resolve_authtoken() -> str | None:
- """Find the user's ngrok authtoken without inheriting the rest of their config.
+@dataclass(frozen=True, kw_only=True)
+class _Assignment:
+ """A service's local port and the public Funnel port it is served on. Both are
+ ports, so keyword-only construction keeps the two from being swapped."""
- The harness generates its own config (its tunnels point at eval ports, not the
- dev-stack ports the setup guide documents), so it cannot just hand ngrok the
- user's file. The token is the one thing worth lifting out of it.
- """
- from_env = os.environ.get("NGROK_AUTHTOKEN")
- if from_env:
- return from_env
+ local_port: int
+ public_port: int
- for path in NGROK_DEFAULT_CONFIG_PATHS:
- if not path.is_file():
- continue
- try:
- config = yaml.safe_load(path.read_text(encoding="utf-8"))
- except (OSError, yaml.YAMLError):
- continue
- if not isinstance(config, dict):
- continue
- # Config version 3 nests it under ``agent``; version 2 keeps it top-level.
- agent = config.get("agent")
- token = agent.get("authtoken") if isinstance(agent, dict) else None
- token = token or config.get("authtoken")
- if isinstance(token, str) and token:
- return token
- return None
+def _run_tailscale(args: list[str], *, timeout: int) -> subprocess.CompletedProcess[str]:
+ return subprocess.run(["tailscale", *args], capture_output=True, text=True, timeout=timeout)
-class NgrokTunnels:
- """Modal-only ngrok lifecycle: publicly exposes the host services a remote
- Modal sandbox must reach (Django API, LLM gateway, MCP server).
- While a run is live the tunnel URLs are reachable by anyone on the internet
- who learns them, so they exist only for the duration of the run.
- """
+def tailscale_status() -> dict[str, Any] | None:
+ """Return the parsed ``tailscale status --json`` payload, or ``None`` when the
+ binary is missing, the daemon is unreachable, or the output is unparseable."""
+ try:
+ result = _run_tailscale(["status", "--json"], timeout=15)
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ try:
+ payload = json.loads(result.stdout)
+ except json.JSONDecodeError:
+ return None
+ return payload if isinstance(payload, dict) else None
- def __init__(self, ports: dict[str, int]) -> None:
- self._ports: dict[str, int] = dict(ports)
- self._proc: subprocess.Popen[bytes] | None = None
- self._config_dir: Path | None = None
- self._log_path: Path | None = None
- self._public_urls: dict[str, str] = {}
- def start(self) -> None:
- self._config_dir = Path(tempfile.mkdtemp(prefix="posthog-eval-ngrok-"))
- config_path = self._config_dir / "ngrok.yml"
- self._log_path = self._config_dir / "ngrok.log"
- config_path.write_text(yaml.safe_dump(self._build_config(), sort_keys=False), encoding="utf-8")
-
- # ngrok's own log goes to a file, never to a pipe: nothing drains a pipe
- # for the length of a run, and a full 64 KB buffer would block the agent
- # and stall every tunnel mid-eval.
- self._proc = subprocess.Popen(
- ["ngrok", "start", "--all", "--config", str(config_path)],
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- start_new_session=True,
+def funnel_preflight_error() -> str | None:
+ """Return a one-line-fixable message if Tailscale Funnel can't be used yet, else None.
+
+ Checked before any infrastructure boots so a missing binary or an unauthenticated
+ node fails fast, rather than surfacing only when the first sandbox can't reach the host.
+ Funnel enablement (tailnet ACLs, HTTPS certs) is left to ``TailscaleFunnel.start``,
+ which surfaces the daemon's own actionable error immediately.
+ """
+ if shutil.which("tailscale") is None:
+ return (
+ "`tailscale` not found on PATH. Modal sandboxes run outside this host, so the "
+ "Django API, LLM gateway, and MCP server must be publicly reachable via Tailscale Funnel. "
+ f"See {SETUP_GUIDE}."
+ )
+ status = tailscale_status()
+ if status is None:
+ return f"Could not reach the Tailscale daemon. Start tailscaled and run `tailscale up`. See {SETUP_GUIDE}."
+ state = status.get("BackendState")
+ if state != "Running":
+ return (
+ f"Tailscale is not connected (backend state: {state or 'unknown'}). "
+ f"Run `tailscale up` and sign in. See {SETUP_GUIDE}."
)
+ return None
- deadline = time.monotonic() + 60
- while time.monotonic() < deadline:
- if self._proc.poll() is not None:
- detail = f"ngrok exited early with code {self._proc.returncode}.\n{self._read_log_tail()}"
- self.stop()
- raise NgrokError(self._failure_message(detail))
- urls = self._read_tunnel_urls()
- if all(name in urls for name in self._ports):
- self._public_urls = {name: urls[name] for name in self._ports}
- logger.info("ngrok tunnels ready: %s", self._public_urls)
- return
+def _public_url(host: str, public_port: int) -> str:
+ # Funnel always terminates TLS. Port 443 is implicit in an https URL; the other
+ # two Funnel ports must be spelled out.
+ if public_port == 443:
+ return f"https://{host}"
+ return f"https://{host}:{public_port}"
+
+
+def _configured_public_ports() -> set[int]:
+ """Public ports that already carry Tailscale Serve/Funnel config, parsed from
+ ``tailscale serve status --json``. Empty when nothing is configured or the
+ status can't be read — so a collision is only ever reported on evidence, never
+ guessed."""
+ try:
+ result = _run_tailscale(["serve", "status", "--json"], timeout=15)
+ except (OSError, subprocess.SubprocessError):
+ return set()
+ if result.returncode != 0:
+ return set()
+ try:
+ payload = json.loads(result.stdout)
+ except json.JSONDecodeError:
+ return set()
+ if not isinstance(payload, dict):
+ return set()
+ ports: set[int] = set()
+ # Web/AllowFunnel keys are "host:port"; TCP keys are a bare port.
+ for section in ("Web", "AllowFunnel", "TCP"):
+ entries = payload.get(section)
+ if not isinstance(entries, dict):
+ continue
+ for key in entries:
+ try:
+ ports.add(int(str(key).rsplit(":", 1)[-1]))
+ except ValueError:
+ continue
+ return ports
+
+
+class TailscaleFunnel:
+ """Modal-only Tailscale Funnel lifecycle: publicly exposes the host services a
+ remote Modal sandbox must reach (Django API, LLM gateway, MCP server).
+
+ Each service is served over HTTPS on one of Tailscale's three permitted public
+ ports and is reachable by anyone on the internet who learns the URL, so the
+ mappings exist only for the duration of the run and are turned off on ``stop``.
+ Unlike a tunnel agent that drops its tunnels when killed, ``--bg`` Funnel config
+ lives in tailscaled and outlives this process, so teardown must run — the caller
+ registers ``stop`` on its cleanup stack.
+ """
- time.sleep(0.5)
+ def __init__(self, ports: dict[str, int]) -> None:
+ if len(ports) > len(FUNNEL_PUBLIC_PORTS):
+ raise TailscaleFunnelError(
+ f"Tailscale Funnel exposes at most {len(FUNNEL_PUBLIC_PORTS)} public ports "
+ f"({', '.join(map(str, FUNNEL_PUBLIC_PORTS))}), but {len(ports)} services were requested."
+ )
+ self._assignments: dict[str, _Assignment] = {
+ name: _Assignment(local_port=local_port, public_port=public_port)
+ for (name, local_port), public_port in zip(ports.items(), FUNNEL_PUBLIC_PORTS)
+ }
+ self._public_urls: dict[str, str] = {}
+ self._enabled_ports: list[int] = []
- detail = f"Timed out waiting for all tunnels to report a public URL.\n{self._read_log_tail()}"
- self.stop()
- raise NgrokError(self._failure_message(detail))
+ def start(self) -> None:
+ host = self._resolve_public_host()
+ # Refuse rather than clobber: Funnel's three ports are all we have, so if the
+ # developer already serves one, overwriting it (and turning it off on teardown)
+ # would silently take down their service. Bail with a fix instead.
+ occupied = _configured_public_ports()
+ conflicts = sorted(a.public_port for a in self._assignments.values() if a.public_port in occupied)
+ if conflicts:
+ raise TailscaleFunnelError(
+ self._failure_message(
+ f"Tailscale Serve/Funnel is already configured on port(s) {', '.join(map(str, conflicts))}. "
+ f"Free them (e.g. `tailscale funnel --https {conflicts[0]} off`) before running Modal evals."
+ )
+ )
+ for name, assignment in self._assignments.items():
+ self._enable_funnel(assignment.public_port, assignment.local_port)
+ self._enabled_ports.append(assignment.public_port)
+ self._public_urls[name] = _public_url(host, assignment.public_port)
+ logger.info("Tailscale Funnel ready: %s", self._public_urls)
def url_for(self, name: str) -> str:
return self._public_urls[name].rstrip("/")
def stop(self) -> None:
- proc = self._proc
- if proc is not None:
- self._proc = None
- self._terminate_process_group(proc)
-
- config_dir = self._config_dir
- if config_dir is not None:
- self._config_dir = None
- self._log_path = None
- shutil.rmtree(config_dir, ignore_errors=True)
-
- def _build_config(self) -> dict[str, Any]:
- # Config version 3: agent-level options live under ``agent``, tunnels stay
- # top-level. Same shape as the config in the setup guide.
- agent: dict[str, Any] = {
- # A dedicated web_addr so the harness never adopts, or collides with,
- # a developer's already-running ngrok agent on the default 4040.
- "web_addr": f"127.0.0.1:{NGROK_WEB_PORT}",
- "log": str(self._log_path),
- "log_level": "info",
- }
- authtoken = resolve_authtoken()
- if authtoken:
- agent["authtoken"] = authtoken
-
- tunnels = {name: {"proto": "http", "addr": port, "schemes": ["https"]} for name, port in self._ports.items()}
- return {"version": "3", "agent": agent, "tunnels": tunnels}
-
- def _read_tunnel_urls(self) -> dict[str, str]:
- try:
- # The fixed loopback HTTP origin prevents callers from selecting another urllib scheme.
- # nosemgrep: python.lang.security.audit.dynamic-urllib-use-detected.dynamic-urllib-use-detected
- with urlopen(f"http://127.0.0.1:{NGROK_WEB_PORT}/api/tunnels", timeout=2) as resp:
- payload = json.loads(resp.read().decode("utf-8"))
- except (URLError, OSError, json.JSONDecodeError):
- return {}
-
- urls: dict[str, str] = {}
- for tunnel in payload.get("tunnels", []):
- # A tunnel restricted to ``schemes: [https]`` is reported under its
- # config name; strip any ``" (https)"``-style suffix defensively.
- name = str(tunnel.get("name", "")).split(" ", 1)[0]
- public_url = tunnel.get("public_url")
- if name and public_url:
- urls[name] = public_url
- return urls
-
- def _terminate_process_group(self, proc: subprocess.Popen[bytes]) -> None:
- if proc.poll() is not None:
- return
- try:
- os.killpg(os.getpgid(proc.pid), signal.SIGTERM)
- except (ProcessLookupError, PermissionError):
- return
- try:
- proc.wait(timeout=5)
- except subprocess.TimeoutExpired:
+ # Turn off only the ports this run enabled — start() refused any port that was
+ # already configured, so these are ours to reclaim. A port whose `off` fails
+ # stays public, so keep it tracked and log loudly: the caller registers stop()
+ # on its cleanup stack (and atexit), so a later invocation retries it.
+ still_public: list[int] = []
+ for port in self._enabled_ports:
try:
- os.killpg(os.getpgid(proc.pid), signal.SIGKILL)
- except (ProcessLookupError, PermissionError):
- pass
-
- def _read_log_tail(self, lines: int = 20) -> str:
- if self._log_path is None or not self._log_path.is_file():
- return ""
+ result = _run_tailscale(["funnel", "--https", str(port), "off"], timeout=15)
+ except Exception:
+ logger.warning(
+ "Failed to turn off Tailscale Funnel on port %s; it is still public", port, exc_info=True
+ )
+ still_public.append(port)
+ continue
+ if result.returncode != 0:
+ detail = (result.stderr or result.stdout or "").strip()
+ logger.error(
+ "Tailscale Funnel port %s is still public: `tailscale funnel --https %s off` failed: %s",
+ port,
+ port,
+ detail,
+ )
+ still_public.append(port)
+ self._enabled_ports = still_public
+ if not still_public:
+ self._public_urls = {}
+
+ def _resolve_public_host(self) -> str:
+ status = tailscale_status()
+ if status is None:
+ raise TailscaleFunnelError(self._failure_message("could not read `tailscale status --json`."))
+ self_node = status.get("Self")
+ dns_name = self_node.get("DNSName") if isinstance(self_node, dict) else None
+ if not isinstance(dns_name, str) or not dns_name:
+ raise TailscaleFunnelError(
+ self._failure_message("`tailscale status` did not report this node's MagicDNS name.")
+ )
+ return dns_name.rstrip(".")
+
+ def _enable_funnel(self, public_port: int, local_port: int) -> None:
+ # `--bg` registers the mapping and returns; a bare local port target proxies
+ # to http://127.0.0.1:<local_port>, matching each plain-HTTP host service.
try:
- return "\n".join(self._log_path.read_text(encoding="utf-8", errors="replace").splitlines()[-lines:])
- except OSError:
- return ""
+ result = _run_tailscale(["funnel", "--bg", f"--https={public_port}", str(local_port)], timeout=30)
+ except (OSError, subprocess.SubprocessError) as e:
+ self.stop()
+ raise TailscaleFunnelError(self._failure_message(str(e))) from e
+ if result.returncode != 0:
+ detail = (result.stderr or result.stdout or "").strip()
+ self.stop()
+ raise TailscaleFunnelError(self._failure_message(detail))
def _failure_message(self, detail: str) -> str:
return (
f"{detail}\n"
- "ngrok could not serve the Django, LLM gateway, and MCP tunnels simultaneously. "
- "The free ngrok plan covers a single tunnel, so multi-tunnel eval runs need an "
- "authtoken on a paid plan (ngrok Hobbyist or above), or Cloudflare Tunnel instead. "
- f"See {SETUP_GUIDE}."
+ "Tailscale Funnel could not serve the Django, LLM gateway, and MCP services. "
+ "Make sure tailscaled is running and this node is logged in (`tailscale up`), that Funnel "
+ "is enabled for the tailnet and this node in the admin console's ACLs, and that HTTPS "
+ f"certificates are enabled for the tailnet. See {SETUP_GUIDE}."
)