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.

fix(tasks): make hogli resolvable in the cloud sandbox (#100173)

Alessandro Pogliaghiddcd598dbac9
diff --git a/products/tasks/backend/logic/services/modal_sandbox.py b/products/tasks/backend/logic/services/modal_sandbox.py
index 80f5a319f449..bca3d0745dca 100644
--- a/products/tasks/backend/logic/services/modal_sandbox.py
+++ b/products/tasks/backend/logic/services/modal_sandbox.py
@@ -272,6 +272,7 @@ LOCAL_MODAL_DOCKERFILES = {
LOCAL_MODAL_INSTALL_SKILLS_SCRIPT = Path("products/tasks/backend/sandbox/images/install-skills.sh")
LOCAL_MODAL_GIT_GUARD_SCRIPT = Path("products/tasks/backend/sandbox/images/git-guard.sh")
LOCAL_MODAL_GH_GUARD_SCRIPT = Path("products/tasks/backend/sandbox/images/gh-guard.sh")
+LOCAL_MODAL_HOGLI_SHIM_SCRIPT = Path("products/tasks/backend/sandbox/images/hogli-shim.sh")
# The notebook image bakes the notebooks SQLV2 kernel and stamps its content hash,
# so a local build context needs the package and the module that computes the hash.
LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE = Path("products/notebooks/backend/kernel_package.py")
@@ -630,6 +631,10 @@ def _prepare_local_modal_build_context(template: SandboxTemplate) -> tuple[str,
shutil.copy2(base_dir / LOCAL_MODAL_CPU_BILLING_SAMPLER, destination_sampler_path)
if template == SandboxTemplate.DEFAULT_BASE:
+ destination_hogli_shim_path = context_dir / LOCAL_MODAL_HOGLI_SHIM_SCRIPT
+ destination_hogli_shim_path.parent.mkdir(parents=True, exist_ok=True)
+ shutil.copy2(base_dir / LOCAL_MODAL_HOGLI_SHIM_SCRIPT, destination_hogli_shim_path)
+
source_install_script_path = base_dir / LOCAL_MODAL_INSTALL_SKILLS_SCRIPT
destination_install_script_path = context_dir / LOCAL_MODAL_INSTALL_SKILLS_SCRIPT
destination_install_script_path.parent.mkdir(parents=True, exist_ok=True)
diff --git a/products/tasks/backend/logic/services/test_modal_sandbox.py b/products/tasks/backend/logic/services/test_modal_sandbox.py
index 9bec4f472742..2b1e758f6033 100644
--- a/products/tasks/backend/logic/services/test_modal_sandbox.py
+++ b/products/tasks/backend/logic/services/test_modal_sandbox.py
@@ -13,6 +13,7 @@ from products.tasks.backend.exceptions import SandboxExecutionError
from products.tasks.backend.logic.services.modal_sandbox import (
DEFAULT_MODAL_APP_NAME,
LOCAL_MODAL_AGENT_SHADOW_DIR,
+ LOCAL_MODAL_HOGLI_SHIM_SCRIPT,
LOCAL_MODAL_NOTEBOOK_KERNEL_DIR,
LOCAL_MODAL_NOTEBOOK_KERNEL_MODULE,
NOTEBOOK_MODAL_APP_NAME,
@@ -356,9 +357,10 @@ class TestSelfDrivingWorkloadMapping:
class TestLocalModalBuildContext:
- def test_base_context_carries_the_agent_shadow_sources(self):
- # The base Dockerfile's first stage COPYs and builds the agent-shadow observer, so the
- # trimmed DEBUG context must carry its sources or every local sandbox fails at image build.
+ def test_base_context_carries_the_sources_its_dockerfile_copies(self):
+ # The base Dockerfile's first stage COPYs and builds the agent-shadow observer, and it
+ # COPYs the hogli shim onto PATH, so the trimmed DEBUG context must carry both or every
+ # local sandbox fails at image build.
_prepare_local_modal_build_context.cache_clear()
with (
patch("products.tasks.backend.logic.services.modal_sandbox.LocalSkillsCache"),
@@ -369,6 +371,7 @@ class TestLocalModalBuildContext:
root = Path(context_dir)
assert (root / LOCAL_MODAL_AGENT_SHADOW_DIR / "go.mod").is_file()
assert (root / LOCAL_MODAL_AGENT_SHADOW_DIR / "main.go").is_file()
+ assert (root / LOCAL_MODAL_HOGLI_SHIM_SCRIPT).is_file()
finally:
shutil.rmtree(context_dir, ignore_errors=True)
_prepare_local_modal_build_context.cache_clear()
diff --git a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
index 137de7de3913..2f8c863142cf 100644
--- a/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
+++ b/products/tasks/backend/sandbox/images/Dockerfile.sandbox-base
@@ -186,6 +186,8 @@ RUN chmod +x /opt/posthog/bin/git
# non-interactive `bash -c`; the agent's interactive shell needs this shim).
COPY products/tasks/backend/sandbox/images/gh-guard.sh /opt/posthog/bin/gh
RUN chmod +x /opt/posthog/bin/gh
+COPY products/tasks/backend/sandbox/images/hogli-shim.sh /opt/posthog/bin/hogli
+RUN chmod +x /opt/posthog/bin/hogli
COPY products/tasks/backend/sandbox/images/cpu_billing_sampler.py /usr/local/bin/posthog-cpu-billing-sampler
RUN chmod +x /usr/local/bin/posthog-cpu-billing-sampler
COPY --from=agent-shadow-builder /agent-shadow /usr/local/bin/agent-shadow
diff --git a/products/tasks/backend/sandbox/images/hogland/bake-golden.sh b/products/tasks/backend/sandbox/images/hogland/bake-golden.sh
index d99809a9b0e4..8cd8dacd6b23 100755
--- a/products/tasks/backend/sandbox/images/hogland/bake-golden.sh
+++ b/products/tasks/backend/sandbox/images/hogland/bake-golden.sh
@@ -47,11 +47,12 @@ log() { printf '[tasks-bake] %s\n' "$*" >&2; }
GIT_GUARD="$IMAGES_DIR/git-guard.sh"
GH_GUARD="$IMAGES_DIR/gh-guard.sh"
+HOGLI_SHIM="$IMAGES_DIR/hogli-shim.sh"
CPU_SAMPLER="$IMAGES_DIR/cpu_billing_sampler.py"
SETUP_SCRIPT="$IMAGES_DIR/hogland/setup-golden.sh"
INSTALL_SKILLS="$IMAGES_DIR/install-skills.sh"
-for f in "$GIT_GUARD" "$GH_GUARD" "$CPU_SAMPLER" "$SETUP_SCRIPT" "$INSTALL_SKILLS" "$SKILLS_TARBALL" "${SSH_KEY}.pub"; do
+for f in "$GIT_GUARD" "$GH_GUARD" "$HOGLI_SHIM" "$CPU_SAMPLER" "$SETUP_SCRIPT" "$INSTALL_SKILLS" "$SKILLS_TARBALL" "${SSH_KEY}.pub"; do
test -f "$f" || { log "FAIL: required file missing: $f"; exit 1; }
done
@@ -192,6 +193,7 @@ deliver() {
# under /tmp for setup-golden.sh to consume.
deliver "$GIT_GUARD" /opt/posthog/bin/git 0755
deliver "$GH_GUARD" /opt/posthog/bin/gh 0755
+deliver "$HOGLI_SHIM" /opt/posthog/bin/hogli 0755
deliver "$CPU_SAMPLER" /usr/local/bin/posthog-cpu-billing-sampler 0755
deliver "$SKILLS_TARBALL" /tmp/golden-skills.tar.gz 0644
deliver "$INSTALL_SKILLS" /tmp/install-skills.sh 0755
diff --git a/products/tasks/backend/sandbox/images/hogland/setup-golden.sh b/products/tasks/backend/sandbox/images/hogland/setup-golden.sh
index 9dabd639a668..107e78e3b379 100755
--- a/products/tasks/backend/sandbox/images/hogland/setup-golden.sh
+++ b/products/tasks/backend/sandbox/images/hogland/setup-golden.sh
@@ -336,6 +336,7 @@ log "guards + cpu sampler (delivered over ssh by bake-golden.sh)"
# fails the bake if a hand run omitted them.
test -x /opt/posthog/bin/git
test -x /opt/posthog/bin/gh
+test -x /opt/posthog/bin/hogli
test -x /usr/local/bin/posthog-cpu-billing-sampler
log "git identity"
@@ -430,6 +431,7 @@ agentsh --version
test -x /scripts/node_modules/.bin/agent-server
test -x /opt/posthog/bin/git
test -x /opt/posthog/bin/gh
+test -x /opt/posthog/bin/hogli
# LAST step: strip the ephemeral CI ssh key so it does not persist into the
# snapshot and therefore into every restored task box. Production restores with
diff --git a/products/tasks/backend/sandbox/images/hogli-shim.sh b/products/tasks/backend/sandbox/images/hogli-shim.sh
new file mode 100644
index 000000000000..1397d107edda
--- /dev/null
+++ b/products/tasks/backend/sandbox/images/hogli-shim.sh
@@ -0,0 +1,40 @@
+#!/bin/bash
+set -euo pipefail
+
+dir="$PWD"
+while [ "$dir" != "/" ]; do
+ if [ -x "$dir/bin/hogli" ]; then
+ if [ -z "${VIRTUAL_ENV:-}" ] && [ ! -d "$dir/.venv" ]; then
+ {
+ printf '%s\n' "error: $dir has no .venv, so hogli cannot run yet." ""
+ if [ -f /opt/posthog/dev-stack-bake.json ]; then
+ printf '%s\n' \
+ "Boot the prebaked dev stack from that checkout:" \
+ " bootstrap-dev-stack" \
+ " uv sync" \
+ " source .venv/bin/activate" \
+ "" \
+ "This image already ships a migrated Postgres and ClickHouse, plus a seeded" \
+ "test_posthog database. Start them with 'hogli start -y -d && hogli wait' when" \
+ "a test needs one. Never hand-roll a database container: it takes the ports the" \
+ "baked stack needs, and pytest then replays the whole migration history." \
+ "" \
+ "See docs/internal/cloud-task-sandbox.md."
+ else
+ printf '%s\n' \
+ "Install it from that checkout:" \
+ " uv sync" \
+ " source .venv/bin/activate"
+ fi
+ } >&2
+ exit 127
+ fi
+ exec "$dir/bin/hogli" "$@"
+ fi
+ dir="$(dirname "$dir")"
+done
+
+printf '%s\n' \
+ "error: no posthog checkout found at or above $PWD." \
+ "hogli runs from inside a posthog checkout; change into one and retry." >&2
+exit 127
diff --git a/tools/hogli-commands/hogli_commands/test_runner.py b/tools/hogli-commands/hogli_commands/test_runner.py
index 7f9e595f35fb..f45b7a887902 100644
--- a/tools/hogli-commands/hogli_commands/test_runner.py
+++ b/tools/hogli-commands/hogli_commands/test_runner.py
@@ -138,12 +138,45 @@ class TestRunConfig:
_DIRECTORY_HINT_MIN_FILES = 10
_PYTEST_VERBOSITY_ARGS = {"-q", "--quiet", "-v", "-vv", "-vvv", "--verbose", "-s", "--capture"}
+_DEV_STACK_BAKE_MANIFEST = Path("/opt/posthog/dev-stack-bake.json")
def _in_cloud_task_sandbox() -> bool:
return bool(os.environ.get("POSTHOG_TASK_RUN_ID")) and not os.environ.get("HOGLI_TEST_VERBOSE")
+def _seeded_test_database_ready() -> bool:
+ try:
+ import psycopg
+
+ with psycopg.connect(
+ host=os.environ.get("PGHOST", "localhost"),
+ port=os.environ.get("PGPORT", "5432"),
+ user=os.environ.get("PGUSER", "posthog"),
+ password=os.environ.get("PGPASSWORD", "posthog"),
+ dbname="test_posthog",
+ connect_timeout=2,
+ ) as connection:
+ row = connection.execute("SELECT to_regclass('posthog_team')").fetchone()
+ return bool(row and row[0] is not None)
+ except Exception:
+ return False
+
+
+def _warn_if_dev_stack_is_down(command: list[str]) -> None:
+ if command[:1] != ["pytest"] or not os.environ.get("POSTHOG_TASK_RUN_ID"):
+ return
+ if not _DEV_STACK_BAKE_MANIFEST.exists() or _seeded_test_database_ready():
+ return
+ click.secho(
+ "The migrated test_posthog database is not reachable, so a test that needs one will "
+ "fail or replay every migration. This image ships it: run `bootstrap-dev-stack`, then "
+ "`hogli start -y -d && hogli wait`. Do not start your own database container, because "
+ "it takes the port the baked stack needs. See docs/internal/cloud-task-sandbox.md.",
+ fg="yellow",
+ )
+
+
def _quiet_pytest_in_cloud_sandbox(command: list[str], extra_args: list[str]) -> list[str]:
"""A cloud task agent reads pytest output as tokens, so in a sandbox the default swaps
``-s`` (stream every print) for ``-q`` unless the agent chose a verbosity."""
@@ -672,6 +705,7 @@ def _run_grouped(detected: list[tuple[str, TestRunConfig]], extra_args: list[str
cfg = entries[0][1]
command = cfg.command[:-1] + [f for f, _ in entries]
click.secho(f"Running {len(entries)} Python test file(s)...", fg="cyan")
+ _warn_if_dev_stack_is_down(command)
_run(_quiet_pytest_in_cloud_sandbox(command, extra_args) + extra_args, env=cfg.env_or_none, cwd=cfg.cwd)
elif test_type == "jest":
# Sub-group by package so each pnpm --filter is correct
@@ -833,6 +867,7 @@ def test_command(ctx: click.Context, file_path: str | None, changed: bool, watch
config = detect_test_type(resolved)
click.secho(f"Detected: {config.description}", fg="cyan")
extra_args = list(ctx.args)
+ _warn_if_dev_stack_is_down(config.command)
_run(
_quiet_pytest_in_cloud_sandbox(config.command, extra_args) + extra_args, env=config.env_or_none, cwd=config.cwd
)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
index 321a0cd7956f..566978943102 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_test_runner.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import io
+import contextlib
from pathlib import Path
import pytest
@@ -21,6 +23,7 @@ from hogli_commands.test_runner import (
_resolve_to_repo_relative,
_run_changed,
_run_grouped,
+ _warn_if_dev_stack_is_down,
detect_test_type,
)
from parameterized import parameterized
@@ -547,7 +550,8 @@ class TestRunGrouped:
class TestCliPassthrough:
@patch("hogli_commands.test_runner._run")
- def test_hogli_test_passes_unknown_options_to_runner(self, mock_run: MagicMock) -> None:
+ def test_hogli_test_passes_unknown_options_to_runner(self, mock_run: MagicMock, monkeypatch) -> None:
+ monkeypatch.delenv("POSTHOG_TASK_RUN_ID", raising=False)
result = runner.invoke(
cli,
[
@@ -624,3 +628,30 @@ class TestScopedRunHints:
_hint_scoped_run("posthog/api/test")
assert ("hogli test --changed" in capsys.readouterr().out) is hinted
+
+ @parameterized.expand(
+ [
+ ("database_down_on_a_baked_image_warns", ["pytest", "a.py"], True, True, False, True),
+ ("seeded_database_ready_is_quiet", ["pytest", "a.py"], True, True, True, False),
+ ("outside_a_sandbox_is_quiet", ["pytest", "a.py"], False, True, False, False),
+ ("unbaked_image_is_quiet", ["pytest", "a.py"], True, False, False, False),
+ ("non_pytest_runner_is_quiet", ["pnpm", "exec", "jest", "a.test.ts"], True, True, False, False),
+ ],
+ )
+ def test_a_down_dev_stack_is_only_reported_where_the_advice_applies(
+ self, _name: str, command, in_sandbox, baked_image, database_ready, warned
+ ):
+ stdout = io.StringIO()
+ with pytest.MonkeyPatch.context() as monkeypatch, contextlib.redirect_stdout(stdout):
+ if in_sandbox:
+ monkeypatch.setenv("POSTHOG_TASK_RUN_ID", "run-1")
+ else:
+ monkeypatch.delenv("POSTHOG_TASK_RUN_ID", raising=False)
+ monkeypatch.setattr("hogli_commands.test_runner._seeded_test_database_ready", lambda: database_ready)
+ monkeypatch.setattr(
+ "hogli_commands.test_runner._DEV_STACK_BAKE_MANIFEST", MagicMock(exists=lambda: baked_image)
+ )
+
+ _warn_if_dev_stack_is_down(command)
+
+ assert ("bootstrap-dev-stack" in stdout.getvalue()) is warned