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(dev): survive dev-stack port collisions and stop silent zookeeper data loss (#73306)

Phil Haackefb255734031
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index f936e5ef6786..4d18ae1e6ff8 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -246,7 +246,10 @@ procs:
tech: Python
docker-compose:
- shell: 'if [ "${POSTHOG_SANDBOX:-}" = "1" ]; then echo "Sandbox: infra managed by docker compose externally" && echo "docker-compose ready" && sleep infinity; else docker compose -f docker-compose.dev.yml up --pull always -d && echo "docker-compose ready" && docker compose -f docker-compose.dev.yml logs --tail=100 -f; fi'
+ # Keep the sandbox guard and failure message in sync with
+ # _generate_docker_compose_config in
+ # tools/hogli-commands/hogli_commands/devenv/generator.py (the generated config).
+ shell: 'if [ "${POSTHOG_SANDBOX:-}" = "1" ]; then echo "Sandbox: infra managed by docker compose externally" && echo "docker-compose ready" && sleep infinity; else docker compose -f docker-compose.dev.yml up --pull always -d || { echo "docker compose up failed (see the error above). A common cause: another stack or process holding a required port (see the pre-flight output from bin/start). Inspect with: docker ps --all"; exit 1; } && echo "docker-compose ready" && docker compose -f docker-compose.dev.yml logs --tail=100 -f; fi'
capability: core_infra
ready_pattern: 'docker-compose ready'
groups:
diff --git a/bin/start b/bin/start
index 754e1ad9820b..4f4dd8b43758 100755
--- a/bin/start
+++ b/bin/start
@@ -147,22 +147,45 @@ if [[ -z "${HOGLI_SKIP_ZOMBIE_CHECK:-}" ]] && command -v hogli &>/dev/null; then
hogli doctor:zombies --yes || true
fi
-# Warn about a duplicate infra stack under a different compose project. It binds the
-# same host ports as "$COMPOSE_PROJECT_NAME", so our clickhouse/kafka can't start and
-# get stuck in "Created" — the "database missing" hang. Advisory only (never fail).
-foreign_stacks=$(docker ps --filter 'label=com.docker.compose.service=clickhouse' \
- --format '{{.Label "com.docker.compose.project"}}' 2>/dev/null \
- | grep -vx "$COMPOSE_PROJECT_NAME" | sort -u || true)
-if [[ -n "$foreign_stacks" ]]; then
- echo "⚠️ Another dev infra stack is running under a different compose project:"
- while IFS= read -r stack; do
- [[ -n "$stack" ]] && echo " • $stack"
- done <<< "$foreign_stacks"
- echo " It holds the same host ports as '$COMPOSE_PROJECT_NAME', so clickhouse/kafka"
- echo " here may fail to start and get reported as 'missing'. Tear it down with:"
- while IFS= read -r stack; do
- [[ -n "$stack" ]] && echo " docker compose -p $stack -f docker-compose.dev.yml down --remove-orphans"
- done <<< "$foreign_stacks"
+# Pre-flight: detect who already holds the host ports the dev stack needs. A stale
+# stack under a *different* compose project binds the same ports, so one of our
+# containers fails to bind — and that aborts the entire `docker compose up`,
+# sometimes leaving a container detached from the compose network. In a TTY, offer
+# to tear foreign stacks down; otherwise stay advisory. Delegated to hogli (tested
+# there, see doctor_ports in hogli_commands/doctor.py).
+#
+# Also runs the one-time migration for the July 2026 named-volume switch: the named
+# volume is absent until the first `up` after the switch, which would otherwise
+# reset a clickhouse container's data that already exists under this project.
+# Auto-salvages the old anonymous volumes when the mapping is unambiguous, otherwise
+# prints the same manual-salvage warning as before. Must run before `docker compose
+# up` below (see doctor_migrate_volumes in hogli_commands/doctor.py).
+#
+# Both skipped if hogli isn't on PATH, same as doctor:zombies above. Without hogli
+# there's no auto-migration either, so warn plainly instead of silently losing data.
+if command -v hogli &>/dev/null; then
+ hogli doctor:ports || true
+ hogli doctor:migrate-volumes || true
+else
+ named_volume_reset_notice() {
+ command -v docker &>/dev/null || return 0
+ docker volume inspect "${COMPOSE_PROJECT_NAME}_clickhouse-data" &>/dev/null && return 0
+ if ! docker ps -a --filter 'label=com.docker.compose.service=clickhouse' \
+ --format '{{.Label "com.docker.compose.project"}}' 2>/dev/null \
+ | grep -qx "$COMPOSE_PROJECT_NAME"; then
+ # No clickhouse container left — either a fresh clone (nothing to lose) or
+ # `docker compose down` (removes containers but keeps volumes). Postgres has
+ # no profile gate, so its volume surviving is a reliable "not a fresh clone"
+ # signal, same as _has_prior_install in hogli_commands/doctor.py.
+ docker volume inspect "${COMPOSE_PROJECT_NAME}_postgres-15-data" &>/dev/null || return 0
+ fi
+ echo "⚠️ Switching ClickHouse/ZooKeeper to named docker volumes. This first start"
+ echo " recreates them empty, so local ClickHouse data resets once (happens once"
+ echo " per machine). Install hogli to auto-migrate your existing data instead. See"
+ echo " 'Local ClickHouse suddenly empty' in"
+ echo " docs/published/handbook/engineering/developing-locally.md to salvage old data."
+ }
+ named_volume_reset_notice || true
fi
# Geo files
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index cc4bf25e0e06..ae52ad0bc05e 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -448,6 +448,7 @@ services:
- ./docker/clickhouse/users-dev.xml:/etc/clickhouse-server/users.xml
- ./docker/clickhouse/user_defined_function.xml:/etc/clickhouse-server/user_defined_function.xml
- ./posthog/user_scripts:/var/lib/clickhouse/user_scripts
+ - clickhouse-data:/var/lib/clickhouse
extra_hosts:
- 'host.docker.internal:host-gateway'
depends_on:
@@ -460,6 +461,15 @@ services:
service: zookeeper
ports:
- '2181:2181'
+ # With persistent volumes, snapshots and txn logs accumulate forever unless
+ # autopurge is on (the image default disables it). Matches hobby.
+ environment:
+ ZOO_AUTOPURGE_PURGEINTERVAL: 1
+ ZOO_AUTOPURGE_SNAPRETAINCOUNT: 3
+ volumes:
+ - zookeeper-datalog:/datalog
+ - zookeeper-data:/data
+ - zookeeper-logs:/logs
kafka:
extends:
@@ -762,3 +772,7 @@ volumes:
seaweedfs-data:
duckgres-data:
objectstorage-data:
+ clickhouse-data:
+ zookeeper-data:
+ zookeeper-datalog:
+ zookeeper-logs:
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index 0b1c29baf032..18c4a76ba50a 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -190,6 +190,8 @@ This starts all services in the background and returns once the IPC socket is bo
- `hogli wait` – blocks until all services are ready (useful in scripts)
- `hogli down` – gracefully stops the detached stack (`hogli stop` is also available as an equivalent)
+- `hogli docker:services:down` – stops the docker compose containers, which keep running after `hogli down` or quitting phrocs (the compose stack is shared across worktrees)
+- `hogli docker:services:remove` – like `docker:services:down`, but also wipes all docker volumes (postgres, clickhouse, and the rest of the stack's data)
### Manual setup
@@ -211,6 +213,33 @@ If you see `Error while fetching server API version: 500 Server Error for http+d
**GeoLite database missing**
The feature-flags container needs the GeoLite database in `/share`. If it's missing, run `./bin/download-mmdb` and then `chmod 0755 ./share/GeoLite2-City.mmdb`.
+**Local ClickHouse suddenly empty (July 2026 named-volume switch)**
+ClickHouse and ZooKeeper store their data in named docker volumes (`clickhouse-data`, `zookeeper-data`), so their state survives container recreation.
+The first `hogli start` after updating past the July 2026 switch to named volumes would otherwise recreate both containers with fresh volumes (the data previously lived in anonymous volumes that container recreation discards).
+`hogli start` runs `hogli doctor:migrate-volumes` before bringing the stack up, which salvages the old anonymous volumes into the new named ones automatically whenever it can prove the mapping is unambiguous — no action needed, and it's a no-op on every subsequent start once migrated.
+
+If it prints a warning instead of migrating (an ambiguous or missing old container — for example two clickhouse containers left over under this same compose project, or the old container already removed by a prior cleanup), it deliberately didn't guess, and local ClickHouse data resets once instead.
+Run `hogli migrations:run` to recreate the ClickHouse schema, or `hogli dev:reset` for a full wipe plus demo data.
+The old anonymous volumes are left dangling in that case; reclaim the disk space with `docker volume prune` (check first with `docker volume ls -f dangling=true`) once you're done, or salvage them manually if you still need that data:
+
+Stop the stack (`hogli docker:services:down`), then identify the old volumes by peeking inside each dangling candidate:
+
+```bash
+docker volume ls -qf dangling=true
+docker run --rm -v <volume>:/v alpine ls /v
+```
+
+The ClickHouse volume contains `store` and `metadata`; the ZooKeeper snapshot volume has `version-2/snapshot.*`; the ZooKeeper transaction-log volume has `version-2/log.*`.
+Copy each old volume into its named replacement. The `posthog_` prefix below is the compose project name (`$COMPOSE_PROJECT_NAME`, `posthog` by default); substitute yours if you've overridden it:
+
+```bash
+docker run --rm -v <old-clickhouse-volume>:/from:ro -v posthog_clickhouse-data:/to alpine sh -c 'rm -rf /to/* && cp -a /from/. /to/'
+```
+
+Repeat for `posthog_zookeeper-data` (snapshots) and `posthog_zookeeper-datalog` (transaction logs).
+ClickHouse and ZooKeeper state must move together — restoring only one side breaks every replicated table with "replica already exists" errors.
+Then start the stack again with `hogli up`.
+
**ClickHouse "get_mempolicy" warning**
You might see `get_mempolicy: Operation not permitted` in the ClickHouse logs. This is harmless and can be ignored. To verify ClickHouse started properly, run `docker exec -it posthog-clickhouse-1 bash` then `clickhouse-client --query "SELECT 1"`.
diff --git a/hogli.yaml b/hogli.yaml
index 04cd7f92b684..938e738399d5 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -359,11 +359,11 @@ start:
preserve_exit_code: true
stop:
cmd: phrocs stop
- description: Stop the detached dev stack gracefully
+ description: Stop the detached dev stack processes (docker services stay up; use docker:services:down to stop them)
preserve_exit_code: true
down:
cmd: phrocs stop
- description: Alias for `hogli stop`
+ description: Alias for `hogli stop` (docker services stay up; use docker:services:down to stop them)
preserve_exit_code: true
start:backend:
bin_script: start-backend
@@ -865,6 +865,12 @@ tools:
doctor:zombies:
click: hogli_commands.doctor:doctor_zombies
description: Find and kill orphaned PostHog dev processes
+ doctor:ports:
+ click: hogli_commands.doctor:doctor_ports
+ description: Pre-flight check for host ports the dev stack needs
+ doctor:migrate-volumes:
+ click: hogli_commands.doctor:doctor_migrate_volumes
+ description: Auto-migrate ClickHouse/ZooKeeper data to the new named docker volumes
doctor:report:
click: hogli_commands.doctor:doctor_report
description: Dump a paste-ready dev-environment diagnostics report for devex triage
diff --git a/tools/hogli-commands/hogli_commands/devenv/generator.py b/tools/hogli-commands/hogli_commands/devenv/generator.py
index 1a3d71baf9ff..b4a8f18d3c2a 100644
--- a/tools/hogli-commands/hogli_commands/devenv/generator.py
+++ b/tools/hogli-commands/hogli_commands/devenv/generator.py
@@ -330,8 +330,23 @@ printf ' {gray}Run {reset}{blue}hogli dev:setup{reset}{gray} to tailor this to
up_cmd = build_docker_compose_command(profiles, "up --pull always -d")
logs_cmd = build_docker_compose_command(profiles, "logs --tail=100 -f")
+ # Keep the sandbox guard and failure message in sync with the
+ # docker-compose proc's shell in bin/mprocs.yaml (the static fallback
+ # used when hogli is unavailable).
+ fail_cmd = (
+ 'echo "docker compose up failed (see the error above). A common cause: another stack or process '
+ 'holding a required port (see the pre-flight output from bin/start). Inspect with: docker ps --all"; '
+ "exit 1"
+ )
+ sandbox_cmd = (
+ 'echo "Sandbox: infra managed by docker compose externally" '
+ '&& echo "docker-compose ready" && sleep infinity'
+ )
+ dev_cmd = f"{up_cmd} || {{ {fail_cmd}; }} && echo 'docker-compose ready' && {logs_cmd}"
- proc_config["shell"] = f"{message}{up_cmd} && echo 'docker-compose ready' && {logs_cmd}"
+ # Sandboxes have no docker CLI; without this guard the generated shell
+ # would fail there and misreport the cause as a port collision.
+ proc_config["shell"] = f'{message}if [ "${{POSTHOG_SANDBOX:-}}" = "1" ]; then {sandbox_cmd}; else {dev_cmd}; fi'
proc_config["ready_pattern"] = "docker-compose ready"
return proc_config
diff --git a/tools/hogli-commands/hogli_commands/doctor.py b/tools/hogli-commands/hogli_commands/doctor.py
index c1bbad44f785..fb1c82b3e68e 100644
--- a/tools/hogli-commands/hogli_commands/doctor.py
+++ b/tools/hogli-commands/hogli_commands/doctor.py
@@ -4,11 +4,15 @@ import os
import re
import sys
import enum
+import json
import time
+import fcntl
+import select
import shutil
import signal
import hashlib
import platform
+import tempfile
import importlib
import subprocess
from collections.abc import Callable, Iterable, Sequence
@@ -1568,6 +1572,579 @@ def _format_rss(rss_kb: int) -> str:
return f"{gb:.1f} GB"
+# ---------------------------------------------------------------------------
+# doctor:ports — pre-flight port collision check
+# ---------------------------------------------------------------------------
+
+# The always-on infra ports from docker-compose.dev.yml whose bind failure
+# aborts `docker compose up`. Update when those mappings change; services
+# gated by `profiles:` (in docker-compose.dev.yml or the legacy
+# docker-compose.profiles.yml overlay — e.g. temporal) are intentionally
+# excluded, since they don't start by default.
+_PREFLIGHT_PORTS: tuple[tuple[int, str], ...] = (
+ (8010, "proxy"),
+ (2181, "zookeeper"),
+ (8123, "clickhouse-http"),
+ (8443, "clickhouse-https"),
+ (9000, "clickhouse-native"),
+ (9440, "clickhouse-native-tls"),
+ (9009, "clickhouse-interserver"),
+ (9092, "kafka"),
+ (5432, "postgres"),
+ (6379, "redis"),
+ (6399, "redis-cluster"),
+ (19000, "objectstorage"),
+ (19001, "objectstorage-master"),
+)
+
+_COMPOSE_NAME_RE = re.compile(r"[^a-zA-Z0-9_.-]")
+
+
+def _sanitize_compose_name(name: str) -> str:
+ """Strip anything outside the compose project name charset.
+
+ Docker labels are attacker/environment-controllable strings headed for
+ the terminal and a `docker compose` command line.
+ """
+ return _COMPOSE_NAME_RE.sub("", name)
+
+
+def _compose_project_name() -> str:
+ """The dev stack's compose project — pinned so worktrees share one stack."""
+ return os.environ.get("COMPOSE_PROJECT_NAME") or "posthog"
+
+
+@dataclass
+class PortHolder:
+ port: int
+ name: str
+ container: str | None = None # docker container name, if docker-held
+ project: str | None = None # sanitized compose project name, if docker-held
+ process_holder: str | None = None # "COMMAND (pid N)", if lsof-held
+
+
+def _scan_port_holders() -> list[PortHolder]:
+ """Attribute each always-on infra port to whatever holds it.
+
+ One `docker ps` covers every port; the Ports column looks like
+ "127.0.0.1:8010->8000/tcp, :::8123->8123/tcp", or for a published range
+ "0.0.0.0:19000-19001->19000-19001/tcp". Matching ":<port>-" covers both
+ the plain form (":19000->") and a range start (":19000-19001->").
+ """
+ containers_output = (
+ _run_output(["docker", "ps", "--format", '{{.Names}}|{{.Label "com.docker.compose.project"}}|{{.Ports}}']) or ""
+ )
+ container_lines = containers_output.splitlines()
+
+ holders: list[PortHolder] = []
+ unheld: list[tuple[int, str]] = []
+ for port, name in _PREFLIGHT_PORTS:
+ needle = f":{port}-"
+ match = next((line for line in container_lines if needle in line), None)
+ if match is None:
+ unheld.append((port, name))
+ continue
+ parts = match.split("|", 2)
+ container = parts[0]
+ project = _sanitize_compose_name(parts[1]) if len(parts) > 1 else ""
+ holders.append(PortHolder(port=port, name=name, container=container, project=project))
+
+ if unheld:
+ holders.extend(_scan_unheld_via_lsof(unheld))
+ return holders
+
+
+def _foreign_holders(holders: Sequence[PortHolder], project_name: str) -> list[PortHolder]:
+ """Docker-held ports belonging to some compose project other than ours."""
+ return [h for h in holders if h.container is not None and h.project != project_name]
+
+
+def _scan_unheld_via_lsof(unheld: Sequence[tuple[int, str]]) -> list[PortHolder]:
+ """One lsof pass for plain-process listeners on ports with no docker holder.
+
+ Report only — killing arbitrary pids from a startup check is out of
+ bounds (`doctor:zombies` already handles orphaned PostHog processes).
+ """
+ if shutil.which("lsof") is None:
+ return [PortHolder(port=p, name=n) for p, n in unheld]
+
+ portlist = ",".join(str(port) for port, _ in unheld)
+ output = _run_output(["lsof", "-nP", f"-iTCP:{portlist}", "-sTCP:LISTEN"]) or ""
+ lines = output.splitlines()
+
+ holders: list[PortHolder] = []
+ for port, name in unheld:
+ holder = None
+ needle = f":{port}"
+ for line in lines:
+ # lsof columns: COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME;
+ # match NAME (e.g. "*:5432") ending in ":<port>".
+ fields = line.split()
+ if len(fields) < 9:
+ continue
+ if fields[8].endswith(needle) and fields[1].isdigit():
+ # Strip control bytes a process name could smuggle to the terminal.
+ command = re.sub(r"[\x00-\x1f\x7f]", "", fields[0])
+ holder = f"{command} (pid {fields[1]})"
+ break
+ holders.append(PortHolder(port=port, name=name, process_holder=holder))
+ return holders
+
+
+def _containers_for_service(service: str) -> list[tuple[str, str]]:
+ """(container ID, sanitized compose project) for every container in any
+ state running `service`, across all compose projects on this machine.
+ """
+ output = (
+ _run_output(
+ [
+ "docker",
+ "ps",
+ "-a",
+ "--filter",
+ f"label=com.docker.compose.service={service}",
+ "--format",
+ '{{.ID}}|{{.Label "com.docker.compose.project"}}',
+ ]
+ )
+ or ""
+ )
+ pairs = []
+ for line in output.splitlines():
+ parts = line.split("|", 1)
+ if len(parts) == 2:
+ pairs.append((parts[0], _sanitize_compose_name(parts[1])))
+ return pairs
+
+
+def _posthog_shaped_projects(candidates: set[str]) -> set[str]:
+ """Of the candidate foreign projects, keep only ones that look like a
+ PostHog dev stack: a clickhouse container in any state (a partial stack
+ may hold ports while its clickhouse is stopped). An unrelated project
+ that happens to hold postgres/redis ports gets reported, not torn down.
+ """
+ clickhouse_projects = {project for _container_id, project in _containers_for_service("clickhouse")}
+ return candidates & clickhouse_projects
+
+
+def _confirm_stack_teardown(stack: str, timeout: float = 30.0) -> bool:
+ """Prompt for teardown of a foreign compose stack, with a timeout.
+
+ Runs on every `hogli start`, so a hung or piped stdin must never block;
+ timeout, EOF, or any non-"y" answer means "leave it running".
+ """
+ click.echo(f" Remove foreign stack '{stack}' (compose down, volumes kept)? [y/N] ", nl=False)
+ ready, _, _ = select.select([sys.stdin], [], [], timeout)
+ if not ready:
+ click.echo()
+ return False
+ answer = sys.stdin.readline().strip()
+ return answer.lower() == "y"
+
+
+ name="doctor:ports",
+ help="Pre-flight check for host ports the dev stack needs",
+)
+ "--yes", "-y", is_flag=True, help="Auto-confirm teardown of any foreign PostHog stack found holding a port"
+)
+def doctor_ports(yes: bool) -> None:
+ """Report what's holding the dev stack's host ports, and in a TTY, offer
+ to tear down a stale foreign PostHog stack. Fail-open: never blocks
+ `bin/start`, non-interactive callers only ever see suggested commands.
+ """
+ if shutil.which("docker") is None:
+ return
+
+ project_name = _compose_project_name()
+ holders = _scan_port_holders()
+
+ foreign = _foreign_holders(holders, project_name)
+ report_lines = [
+ f" • port {h.port} ({h.name}): container '{h.container}' from compose project '{h.project or '<none>'}'"
+ for h in foreign
+ ]
+ report_lines += [
+ f" • port {h.port} ({h.name}): process {h.process_holder}"
+ for h in holders
+ if h.container is None and h.process_holder
+ ]
+ if not report_lines:
+ return
+
+ click.echo("⚠️ Some ports the dev stack needs are already held by something outside the")
+ click.echo(f" '{project_name}' compose project. 'docker compose up' will abort if any")
+ click.echo(" of its containers fails to bind, and services here may be reported as 'missing':")
+ for line in report_lines:
+ click.echo(line)
+
+ foreign_candidates = {h.project for h in foreign if h.project}
+ if not foreign_candidates:
+ return
+
+ foreign_projects = _posthog_shaped_projects(foreign_candidates)
+ if not foreign_projects:
+ return
+
+ interactive = sys.stdin.isatty() and sys.stdout.isatty()
+ if not interactive:
+ click.echo(" Tear a foreign stack down with:")
+
+ for stack in sorted(foreign_projects):
+ teardown = ["docker", "compose", "-p", stack, "-f", "docker-compose.dev.yml", "down", "--remove-orphans"]
+ teardown_str = " ".join(teardown)
+ if not interactive:
+ click.echo(f" {teardown_str}")
+ continue
+ confirmed = yes or _confirm_stack_teardown(stack)
+ if not confirmed:
+ click.echo(f" Leaving '{stack}' running. Stop it later with:")
+ click.echo(f" {teardown_str}")
+ continue
+ click.echo(f" Stopping compose project '{stack}'…")
+ result = subprocess.run(teardown, check=False)
+ if result.returncode == 0:
+ click.echo(f" Stopped '{stack}'.")
+ else:
+ click.echo(f" ⚠️ Could not stop '{stack}' (see docker's output above) — its ports may still be held.")
+
+
+# ---------------------------------------------------------------------------
+# doctor:migrate-volumes — auto-salvage anonymous ClickHouse/ZooKeeper volumes
+# ---------------------------------------------------------------------------
+
+# (compose service, mount destination inside the container, named-volume
+# suffix, human label). Must match the volumes: blocks for clickhouse/
+# zookeeper in docker-compose.dev.yml.
+_VOLUME_MIGRATIONS: tuple[tuple[str, str, str, str], ...] = (
+ ("clickhouse", "/var/lib/clickhouse", "clickhouse-data", "ClickHouse data"),
+ ("zookeeper", "/data", "zookeeper-data", "ZooKeeper snapshots"),
+ ("zookeeper", "/datalog", "zookeeper-datalog", "ZooKeeper transaction log"),
+ ("zookeeper", "/logs", "zookeeper-logs", "ZooKeeper server logs"),
+)
+
+# A prior install always has postgres's named volume, even after `docker compose
+# down` removes every container — postgres has no `profiles:` gate either, so its
+# absence is a reliable "this really is a fresh clone" signal.
+_PRIOR_INSTALL_VOLUME_SUFFIX = "postgres-15-data"
+
+
+@dataclass(frozen=True)
+class VolumeMigrationStep:
+ """One old anonymous volume to copy into its new named-volume replacement."""
+
+ container_id: str
+ source_volume: str
+ dest_volume: str
+ volume_suffix: str
+ label: str
+
+
+def _matching_containers(project_name: str, service: str) -> list[str]:
+ """Container IDs (any state) for `service` under this compose project."""
+ return [cid for cid, project in _containers_for_service(service) if project == project_name]
+
+
+def _has_prior_install(project_name: str) -> bool:
+ """Whether this looks like an existing install rather than a fresh clone.
+
+ `docker compose down` removes containers but keeps volumes, so a developer
+ who stopped the stack before updating has no clickhouse container left to
+ check but still has this one.
+ """
+ return _run_output(["docker", "volume", "inspect", f"{project_name}_{_PRIOR_INSTALL_VOLUME_SUFFIX}"]) is not None
+
+
+def _find_service_container(project_name: str, service: str) -> str | None:
+ """Return the one container ID for `service` under this project, or None
+ if there isn't exactly one — zero (already removed) and multiple
+ (ambiguous) are both unsafe to guess from.
+ """
+ matches = _matching_containers(project_name, service)
+ return matches[0] if len(matches) == 1 else None
+
+
+def _container_mounts(container_id: str) -> list[dict[str, object]] | None:
+ """Return the container's `docker inspect` Mounts array, or None if it
+ can't be fetched or isn't the list shape `docker inspect` always gives
+ for a live container (e.g. the container vanished between listing and
+ inspecting it).
+ """
+ output = _run_output(["docker", "inspect", container_id, "--format", "{{json .Mounts}}"])
+ if output is None:
+ return None
+ try:
+ mounts = json.loads(output)
+ except json.JSONDecodeError:
+ return None
+ return mounts if isinstance(mounts, list) else None
+
+
+def _find_volume_mount(mounts: list[dict[str, object]], destination: str) -> str | None:
+ """Return the single volume name backing `destination`, or None if it's
+ missing, duplicated, or not a plain named/anonymous volume mount (e.g. a
+ bind mount) — anything but a clean 1:1 match is unsafe to copy from.
+ """
+ matches: list[str] = []
+ for m in mounts:
+ name = m.get("Name")
+ if m.get("Destination") == destination and m.get("Type") == "volume" and isinstance(name, str) and name:
+ matches.append(name)
+ return matches[0] if len(matches) == 1 else None
+
+
+def _plan_volume_migration(project_name: str) -> list[VolumeMigrationStep] | None:
+ """Resolve every old anonymous volume this migration needs, or None if
+ any single one can't be pinned down unambiguously.
+
+ ClickHouse and ZooKeeper state must move together — a replicated table
+ with only one side restored fails with "replica already exists" — so any
+ ambiguity anywhere aborts the whole plan rather than migrating one
+ service and not the other. This function is read-only (no stop, no
+ copy): the caller only commits to touching anything once the full plan
+ resolves cleanly.
+ """
+ containers: dict[str, str] = {}
+ for service, _destination, _suffix, _label in _VOLUME_MIGRATIONS:
+ if service in containers:
+ continue
+ container_id = _find_service_container(project_name, service)
+ if container_id is None:
+ return None
+ containers[service] = container_id
+
+ mounts_by_container: dict[str, list[dict[str, object]] | None] = {}
+ plan: list[VolumeMigrationStep] = []
+ for service, destination, suffix, label in _VOLUME_MIGRATIONS:
+ container_id = containers[service]
+ if container_id not in mounts_by_container:
+ mounts_by_container[container_id] = _container_mounts(container_id)
+ mounts = mounts_by_container[container_id]
+ if mounts is None:
+ return None
+ source_volume = _find_volume_mount(mounts, destination)
+ if source_volume is None:
+ return None
+ dest_volume = f"{project_name}_{suffix}"
+ if source_volume == dest_volume:
+ # Already on the named volume: a retry after a partial migration must not
+ # mount the same volume as both /from and /to, or the copy's `rm -rf /to/*`
+ # would destroy the data it's supposed to be saving.
+ return None
+ plan.append(
+ VolumeMigrationStep(
+ container_id=container_id,
+ source_volume=source_volume,
+ dest_volume=dest_volume,
+ volume_suffix=suffix,
+ label=label,
+ )
+ )
+ return plan
+
+
+def _create_dest_volume(project_name: str, step: VolumeMigrationStep) -> bool:
+ """Pre-create the destination with the labels compose stamps on its own
+ volumes. Left to `docker run -v`'s auto-create, the volume has none, so
+ compose warns it "was not created by Docker Compose" on every later `up`.
+ """
+ return _run_ok(
+ [
+ "docker",
+ "volume",
+ "create",
+ "--label",
+ f"com.docker.compose.project={project_name}",
+ "--label",
+ f"com.docker.compose.volume={step.volume_suffix}",
+ step.dest_volume,
+ ],
+ timeout=15,
+ )
+
+
+def _copy_volume(source_volume: str, dest_volume: str) -> bool:
+ """Copy `source_volume` into `dest_volume` via a throwaway alpine
+ container. The command asserts the destination ended up non-empty —
+ `cp -a` can exit 0 on a no-op copy just as easily as a real one, so a
+ clean exit code alone doesn't prove data landed.
+ """
+ container = f"hogli-migrate-volumes-{os.getpid()}"
+ ok = _run_ok(
+ [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ container,
+ "-v",
+ f"{source_volume}:/from:ro",
+ "-v",
+ f"{dest_volume}:/to",
+ "alpine",
+ "sh",
+ "-c",
+ 'rm -rf /to/* && cp -a /from/. /to/ && [ -n "$(ls -A /to)" ]',
+ ],
+ timeout=900,
+ )
+ if not ok:
+ # A subprocess timeout kills the docker client, not the container it launched —
+ # without removing it explicitly, the container keeps holding the destination
+ # volume, so a later `docker volume rm -f` fails with "volume is in use" and
+ # rollback silently leaves a torn copy behind.
+ _run_output(["docker", "rm", "-f", container], timeout=30)
+ return ok
+
+
+def _remove_volumes(volume_names: Iterable[str]) -> None:
+ names = list(volume_names)
+ if names:
+ _run_output(["docker", "volume", "rm", "-f", *names], timeout=15)
+
+
+def _restart_containers(container_ids: Iterable[str]) -> None:
+ ids = list(container_ids)
+ if ids:
+ _run_output(["docker", "start", *ids], timeout=30)
+
+
+# ClickHouse needs time to flush a multi-GB dataset on shutdown; docker's 10s
+# default SIGKILLs it mid-flush, so every developer's first start after the
+# migration pays for crash recovery. The subprocess timeout is derived from this
+# so raising the grace period can't leave the docker client killed before the
+# container it's waiting on.
+_STOP_GRACE_SECONDS = 60
+
+
+def _execute_volume_migration(plan: Sequence[VolumeMigrationStep], project_name: str) -> bool:
+ """Stop the old containers, copy every planned volume, and verify each
+ one. A live `cp -a` against an actively-written ClickHouse/ZooKeeper data
+ dir can read a torn snapshot, so the containers are stopped first — the
+ same "stop the stack, then copy" order the manual salvage doc already
+ tells developers to follow. Any failure, including an interrupt, rolls
+ back: remove whatever new named volumes were already created and restart
+ whatever was stopped, so `docker compose up` sees today's fallback
+ situation (no named volumes yet) rather than a mix of migrated and
+ un-migrated state.
+ """
+ container_ids = sorted({step.container_id for step in plan})
+ if not _run_ok(
+ ["docker", "stop", "-t", str(_STOP_GRACE_SECONDS), *container_ids],
+ timeout=_STOP_GRACE_SECONDS + 30,
+ ):
+ # `docker stop` on multiple containers can partially succeed (e.g. one
+ # already vanished) and still exit non-zero overall — restart whatever
+ # did stop rather than leaving a working dev stack unexpectedly down.
+ _restart_containers(container_ids)
+ return False
+
+ migrated: list[str] = []
+ for step in plan:
+ click.echo(f" Migrating {step.label}…")
+ try:
+ copied = _create_dest_volume(project_name, step) and _copy_volume(step.source_volume, step.dest_volume)
+ except BaseException:
+ # Ctrl-C during a multi-GB copy must not leave a torn destination volume and
+ # a stopped stack behind for the next run to mistake for a completed migration.
+ _remove_volumes([*migrated, step.dest_volume])
+ _restart_containers(container_ids)
+ raise
+ if not copied:
+ click.echo(f" ⚠️ {step.label} migration failed, rolling back…")
+ # `docker run -v <dest>:/to ...` auto-creates the destination volume
+ # before the container's command runs, so a failed (or partially
+ # completed, e.g. disk-full mid-copy) attempt still leaves step's own
+ # volume behind — remove it too, not just the ones that fully
+ # succeeded, or a torn copy can survive rollback and later get
+ # mistaken for a completed migration by the idempotency check.
+ _remove_volumes([*migrated, step.dest_volume])
+ _restart_containers(container_ids)
+ return False
+ migrated.append(step.dest_volume)
+ return True
+
+
+def _print_volume_reset_warning() -> None:
+ click.echo("⚠️ Switching ClickHouse/ZooKeeper to named docker volumes. This first start")
+ click.echo(" recreates them empty, so local ClickHouse data resets once (happens once")
+ click.echo(" per machine). Run 'hogli migrations:run' after, or 'hogli dev:reset' for a")
+ click.echo(" full wipe plus demo data. See 'Local ClickHouse suddenly empty' in")
+ click.echo(" docs/published/handbook/engineering/developing-locally.md to salvage old data.")
+
+
+_MIGRATION_LOCK_DIR = Path(tempfile.gettempdir())
+
+
+ name="doctor:migrate-volumes",
+ help="Auto-migrate ClickHouse/ZooKeeper data to the new named docker volumes",
+)
+def doctor_migrate_volumes() -> None:
+ """One-time migration for the named-volume switch in docker-compose.dev.yml.
+
+ ClickHouse and ZooKeeper moved from anonymous to named volumes so that
+ recreating a container no longer wipes ZooKeeper's replica-registration
+ state. The very first `docker compose up` after that switch would
+ otherwise create the named volumes empty. This salvages the prior
+ anonymous volumes into them automatically whenever the old→new mapping
+ is unambiguous, and falls back to the same manual-salvage guidance as
+ before when it isn't. Must run before `docker compose up` (see
+ bin/start) — once that recreates the containers, the old anonymous
+ volumes are no longer discoverable from their mounts. Fail-open, like
+ doctor:ports: never blocks `bin/start`.
+ """
+ if shutil.which("docker") is None:
+ return
+
+ project_name = _compose_project_name()
+ # `bin/start`'s own lock file is per-worktree, but every worktree shares this
+ # compose project — without this, two worktrees starting at once could both plan
+ # a migration for the same destination volumes, and one's failure rollback would
+ # delete data the other just copied. Blocks rather than skips, so the second
+ # worktree waits out the first's migration instead of racing it; the OS releases
+ # the lock automatically if the holding process dies, so a crash can't wedge it.
+ lock_path = _MIGRATION_LOCK_DIR / f"hogli-migrate-volumes-{project_name}.lock"
+ try:
+ # The path is predictable and, on Linux, sits in world-writable /tmp. Opening it
+ # with "w" would follow a symlink planted there by another local user and truncate
+ # whatever it points at. O_NOFOLLOW refuses the symlink outright, and omitting
+ # O_TRUNC means there's nothing to destroy either way — the file is only ever a
+ # flock handle, never written to.
+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
+ with os.fdopen(fd, "r+") as lock_file:
+ fcntl.flock(lock_file, fcntl.LOCK_EX)
+ _do_migrate_volumes(project_name)
+ except OSError:
+ return # couldn't lock (e.g. interrupted, or a symlink squatting the path) — fail-open
+
+
+def _do_migrate_volumes(project_name: str) -> None:
+ # `docker volume inspect` exits non-zero unless *every* named volume exists, so a
+ # migration interrupted partway through is retried instead of mistaken as finished.
+ dest_volumes = [f"{project_name}_{suffix}" for _service, _dest, suffix, _label in _VOLUME_MIGRATIONS]
+ if _run_output(["docker", "volume", "inspect", *dest_volumes]) is not None:
+ return # already migrated (or a fresh named-volume install) — nothing to do
+
+ if not _matching_containers(project_name, "clickhouse"):
+ # No clickhouse container left to salvage from — either a fresh clone, or a
+ # stack that was stopped with `docker compose down` (which keeps volumes but
+ # removes containers). Only warn in the latter case; a fresh clone has nothing
+ # to lose and shouldn't see a reset notice.
+ if _has_prior_install(project_name):
+ _print_volume_reset_warning()
+ return
+
+ plan = _plan_volume_migration(project_name)
+ if plan is not None and _execute_volume_migration(plan, project_name):
+ click.echo("✅ Migrated ClickHouse/ZooKeeper data to the new named docker volumes automatically.")
+ click.echo(" ClickHouse and ZooKeeper are stopped; run 'hogli start' to bring them back up.")
+ return
+
+ _print_volume_reset_warning()
+
+
# ---------------------------------------------------------------------------
# doctor — unified health check
# ---------------------------------------------------------------------------
@@ -1756,6 +2333,22 @@ def _check_migrations() -> CheckResult:
)
+def _check_ports() -> CheckResult:
+ """Quick scan for a foreign stack holding a port the dev stack needs."""
+ if shutil.which("docker") is None:
+ return CheckResult(name="Port conflicts", status=CheckStatus.OK, summary="docker not installed")
+ project_name = _compose_project_name()
+ foreign = _foreign_holders(_scan_port_holders(), project_name)
+ if foreign:
+ return CheckResult(
+ name="Port conflicts",
+ status=CheckStatus.WARNING,
+ summary=f"{len(foreign)} port(s) held by a foreign stack",
+ remediation="run `hogli doctor:ports`",
+ )
+ return CheckResult(name="Port conflicts", status=CheckStatus.OK, summary="clear")
+
+
_STATUS_COLORS = {
CheckStatus.OK: "green",
CheckStatus.WARNING: "yellow",
@@ -1787,6 +2380,7 @@ def _run_checks(repo_root: Path) -> list[CheckResult]:
lambda: _check_zombies(repo_root),
_check_docker,
_check_migrations,
+ _check_ports,
]
# Each check is I/O-bound and independent, so fan them out across threads.
@@ -1852,6 +2446,26 @@ def _run_output(cmd: Sequence[str], timeout: float = 5.0) -> str | None:
return result.stdout.strip() or None
+def _run_ok(cmd: Sequence[str], timeout: float = 5.0) -> bool:
+ """Run a command and report whether it exited zero.
+
+ Unlike `_run_output`, success doesn't depend on stdout being non-empty —
+ for commands whose exit code alone carries the result (e.g. a shell
+ script with no output on success), treating empty stdout as failure
+ would misreport a clean run. On failure, echoes captured stderr so a
+ docker-level error (permission denied, disk full, daemon hiccup) isn't
+ silently lost before the caller falls back to the generic warning.
+ """
+ try:
+ result = subprocess.run(list(cmd), capture_output=True, text=True, timeout=timeout, check=False)
+ except (FileNotFoundError, OSError, subprocess.SubprocessError) as exc:
+ click.echo(f" ⚠️ {cmd[0]}: {exc}")
+ return False
+ if result.returncode != 0 and result.stderr.strip():
+ click.echo(f" ⚠️ {result.stderr.strip()}")
+ return result.returncode == 0
+
+
def _format_kv_block(pairs: Sequence[tuple[str, str]]) -> list[str]:
"""Render label/value pairs as left-aligned ``label value`` lines."""
width = max((len(label) for label, _ in pairs), default=0)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_detached.py b/tools/hogli-commands/hogli_commands/tests/test_detached.py
index 57423aff84b3..e8f3b3d6f968 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_detached.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_detached.py
@@ -21,7 +21,7 @@ def test_stop_command_registered() -> None:
result = runner.invoke(cli, ["stop", "--help"])
assert result.exit_code == 0
- assert "Stop the detached dev stack gracefully" in result.output
+ assert "Stop the detached dev stack processes" in result.output
def test_up_command_registered_as_start_alias() -> None:
diff --git a/tools/hogli-commands/hogli_commands/tests/test_devenv.py b/tools/hogli-commands/hogli_commands/tests/test_devenv.py
index ca52c9f27069..fd665ee8c6e6 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_devenv.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_devenv.py
@@ -7,6 +7,7 @@ import sys
import shlex
import shutil
import tempfile
+import subprocess
from pathlib import Path
from typing import Any
@@ -978,3 +979,64 @@ class TestParseExcludeInput:
excluded, out_of_range = _parse_exclude_input(raw, self.UNITS)
assert excluded == expected_excluded
assert out_of_range == expected_out_of_range
+
+
+class TestDockerComposeShellFailurePath:
+ """The docker-compose proc shell must not emit the ready marker when `up` fails.
+
+ `up_cmd || { fail_cmd; exit 1; } && echo 'docker-compose ready'` only adds
+ a friendlier failure message over a plain `up_cmd && echo ready` chain —
+ both already skip the ready marker on failure. What this guards against is
+ someone dropping the `exit 1` from `fail_cmd`: then the `{ ...; }` group
+ exits 0, the `||` is satisfied, and `docker-compose ready` fires even
+ though `up` failed, so every dependent proc starts against a dead stack.
+ Covers both the generated shell and its independently maintained twin in
+ bin/mprocs.yaml (the static fallback used when hogli is unavailable).
+ """
+
+ @staticmethod
+ def _shells() -> list[tuple[str, str]]:
+ generated = MprocsGenerator(MockRegistry({}))._generate_docker_compose_config({}, [])["shell"]
+ repo_root = Path(__file__).resolve().parents[4]
+ static = yaml.safe_load((repo_root / "bin" / "mprocs.yaml").read_text())["procs"]["docker-compose"]["shell"]
+ return [("generated", generated), ("static", static)]
+
+ @parameterized.expand(
+ [
+ ("generated", 0, True),
+ ("generated", 1, False),
+ ("static", 0, True),
+ ("static", 1, False),
+ ]
+ )
+ def test_ready_marker_tracks_up_result(self, source: str, up_exit: int, expect_ready: bool) -> None:
+ shell = dict(self._shells())[source]
+ with tempfile.TemporaryDirectory() as tmp:
+ fake = Path(tmp) / "docker"
+ fake.write_text(f'#!/bin/sh\ncase "$*" in *" up "*) exit {up_exit};; esac\nexit 0\n')
+ fake.chmod(0o755)
+ env = {**os.environ, "PATH": f"{tmp}:{os.environ['PATH']}"}
+ env.pop("POSTHOG_SANDBOX", None)
+ result = subprocess.run(
+ ["bash", "-c", shell], env=env, capture_output=True, text=True, timeout=10, check=False
+ )
+ assert ("docker-compose ready" in result.stdout) == expect_ready
+ assert (result.returncode == 0) == expect_ready
+
+ @parameterized.expand([("generated",), ("static",)])
+ def test_sandbox_guard_short_circuits_before_docker(self, source: str) -> None:
+ # Sandboxes have no docker CLI; the shell must report ready without
+ # invoking docker at all. A fake docker that always fails proves the
+ # guard short-circuits; a fake sleep lets the sandbox branch terminate.
+ shell = dict(self._shells())[source]
+ with tempfile.TemporaryDirectory() as tmp:
+ for name, body in [("docker", "#!/bin/sh\nexit 1\n"), ("sleep", "#!/bin/sh\nexit 0\n")]:
+ fake = Path(tmp) / name
+ fake.write_text(body)
+ fake.chmod(0o755)
+ env = {**os.environ, "PATH": f"{tmp}:{os.environ['PATH']}", "POSTHOG_SANDBOX": "1"}
+ result = subprocess.run(
+ ["bash", "-c", shell], env=env, capture_output=True, text=True, timeout=10, check=False
+ )
+ assert "docker-compose ready" in result.stdout
+ assert result.returncode == 0
diff --git a/tools/hogli-commands/hogli_commands/tests/test_doctor.py b/tools/hogli-commands/hogli_commands/tests/test_doctor.py
index 127f2e4d0bcb..3e177457e4e3 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_doctor.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_doctor.py
@@ -1,17 +1,28 @@
import os
+import json
import time
+import fcntl
import hashlib
+import threading
+import subprocess
+from collections.abc import Callable, Sequence
from pathlib import Path
from types import SimpleNamespace
import pytest
+from click.testing import CliRunner
from hogli_commands.doctor import (
FLOX_LOG_MAX_AGE_DAYS,
FLOX_LOG_MAX_TOTAL_BYTES,
_binary_arches,
_collect_import_targets,
_config_procs,
+ _confirm_stack_teardown,
+ _container_mounts,
+ _copy_volume,
+ _find_service_container,
+ _find_volume_mount,
_format_kv_block,
_generated_config_path,
_get_process_cwds,
@@ -20,15 +31,35 @@ from hogli_commands.doctor import (
_phrocs_info,
_phrocs_runtime_pairs,
_phrocs_socket_path,
+ _posthog_shaped_projects,
_probe_command_imports,
+ _run_ok,
+ _sanitize_compose_name,
+ _scan_port_holders,
+ _scan_unheld_via_lsof,
_select_flox_logs_to_remove,
_tail,
+ doctor_migrate_volumes,
+ doctor_ports,
)
_QUARTER_BUDGET = FLOX_LOG_MAX_TOTAL_BYTES // 4
_TWO_FIFTHS_BUDGET = int(FLOX_LOG_MAX_TOTAL_BYTES * 0.4)
[email protected](autouse=True)
+def _neutralize_compose_project(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # Several tests in this module hardcode "posthog"-prefixed volume/project
+ # names, matching production code that reads COMPOSE_PROJECT_NAME from the
+ # environment — without this, a developer with a legitimately overridden
+ # project name (e.g. COMPOSE_PROJECT_NAME=ai-gateway) gets a red suite here.
+ monkeypatch.setenv("COMPOSE_PROJECT_NAME", "posthog")
+ # doctor_migrate_volumes locks a file named after the project to serialize
+ # across worktrees; point it at a per-test directory so parallel test runs
+ # don't contend on the same real /tmp path.
+ monkeypatch.setattr("hogli_commands.doctor._MIGRATION_LOCK_DIR", tmp_path)
+
+
@pytest.mark.parametrize(
"specs, expected_doomed, expected_retained",
[
@@ -218,7 +249,7 @@ def test_get_process_cwds_parses_and_batches(monkeypatch: pytest.MonkeyPatch) ->
def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
captured["cmd"] = cmd
- return SimpleNamespace(returncode=1, stdout="p100\nn/repo/a\np200\nn/repo/b\n")
+ return SimpleNamespace(returncode=1, stdout="p100\nn/repo/a\np200\nn/repo/b\n", stderr="")
monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
@@ -387,3 +418,757 @@ def test_phrocs_runtime_pairs_flags_missing_config(tmp_path: Path) -> None:
pairs = dict(_phrocs_runtime_pairs(tmp_path))
assert "MISSING" in pairs["generated_config"]
assert "hogli dev:generate" in pairs["generated_config"]
+
+
+def test_sanitize_compose_name_strips_shell_metacharacters() -> None:
+ # This value heads for a `docker compose -p <name> down` argv; if the
+ # sanitizer regresses, a crafted compose label becomes shell injection.
+ assert _sanitize_compose_name("posthog-evil$(touch /tmp/pwned);rm -rf /") == "posthog-eviltouchtmppwnedrm-rf"
+
+
+def _fake_docker_ps(
+ monkeypatch: pytest.MonkeyPatch,
+ port_scan_stdout: str = "",
+ clickhouse_stdout: str = "",
+ extra: Callable[[list[str]], SimpleNamespace | None] | None = None,
+) -> None:
+ """Fake the two `docker ps` calls `doctor:ports` makes. `extra`, if given,
+ handles any other command (e.g. the teardown `docker compose` call) —
+ callers that need one don't have to reimplement the `docker ps` branches.
+ """
+
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ if cmd[:2] == ["docker", "ps"] and "-a" not in cmd:
+ return SimpleNamespace(returncode=0, stdout=port_scan_stdout, stderr="")
+ if cmd[:3] == ["docker", "ps", "-a"]:
+ return SimpleNamespace(returncode=0, stdout=clickhouse_stdout, stderr="")
+ if extra is not None:
+ result = extra(cmd)
+ if result is not None:
+ return result
+ return SimpleNamespace(returncode=1, stdout="", stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+
+ ("ports_line", "expected_port", "expected_holder"),
+ [
+ pytest.param("evilbox|otherproj|127.0.0.1:8010->8000/tcp", 8010, "otherproj", id="plain-published-port"),
+ pytest.param(
+ "evilbox|otherproj|0.0.0.0:19000-19001->19000-19001/tcp", 19000, "otherproj", id="published-range-start"
+ ),
+ pytest.param(
+ "evilbox|otherproj|0.0.0.0:19000-19001->19000-19001/tcp",
+ 9000,
+ None,
+ id="range-does-not-false-match-shorter-port",
+ ),
+ ],
+)
+def test_scan_port_holders_matches_published_port_forms(
+ monkeypatch: pytest.MonkeyPatch, ports_line: str, expected_port: int, expected_holder: str | None
+) -> None:
+ # code-reviewer-testing's top concern on the bash version: a substring
+ # match between port 9000 and 19000 would misattribute a collision.
+ _fake_docker_ps(monkeypatch, port_scan_stdout=ports_line)
+ holders = {h.port: h for h in _scan_port_holders()}
+ if expected_holder is None:
+ assert holders[expected_port].container is None
+ else:
+ assert holders[expected_port].container == "evilbox"
+ assert holders[expected_port].project == expected_holder
+
+
+def test_scan_port_holders_own_project_is_not_flagged_foreign(monkeypatch: pytest.MonkeyPatch) -> None:
+ _fake_docker_ps(monkeypatch, port_scan_stdout="clickhouse|posthog|127.0.0.1:8123->8123/tcp")
+ holders = {h.port: h for h in _scan_port_holders()}
+ assert holders[8123].project == "posthog"
+
+
+def test_scan_port_holders_sanitizes_malicious_project_label(monkeypatch: pytest.MonkeyPatch) -> None:
+ _fake_docker_ps(monkeypatch, port_scan_stdout="evilbox|posthog-evil$(rm -rf /)|127.0.0.1:8010->8000/tcp")
+ holders = {h.port: h for h in _scan_port_holders()}
+ assert holders[8010].project == "posthog-evilrm-rf"
+
+
+def test_posthog_shaped_projects_filters_by_clickhouse_label(monkeypatch: pytest.MonkeyPatch) -> None:
+ # This is the exact partial-stack gap Greptile flagged (P1) against the
+ # bash version: `docker ps -a` (all states) means a project whose
+ # clickhouse container is stopped, but another service still holds a
+ # port, is still offered for teardown — not just one whose CH is running.
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ assert "label=com.docker.compose.service=clickhouse" in cmd
+ return SimpleNamespace(returncode=0, stdout="ch1|stopped-proj\n", stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ result = _posthog_shaped_projects({"stopped-proj", "unrelated-proj"})
+ assert result == {"stopped-proj"}
+
+
+def test_scan_unheld_via_lsof_disambiguates_port_and_range(monkeypatch: pytest.MonkeyPatch) -> None:
+ lsof_output = "\n".join(
+ [
+ "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME",
+ "orbstack 111 phil 10u IPv4 0x1 0t0 TCP *:9000",
+ "orbstack 111 phil 11u IPv4 0x2 0t0 TCP *:19000",
+ ]
+ )
+
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ assert cmd[0] == "lsof"
+ return SimpleNamespace(returncode=0, stdout=lsof_output, stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/lsof")
+
+ holders = {h.port: h for h in _scan_unheld_via_lsof([(9000, "clickhouse-native"), (19000, "objectstorage")])}
+ assert holders[9000].process_holder == "orbstack (pid 111)"
+ assert holders[19000].process_holder == "orbstack (pid 111)"
+
+
+def test_confirm_stack_teardown_times_out_to_no(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Runs on every `hogli start`; if the timeout path regresses, a piped or
+ # abandoned terminal hangs every developer's startup indefinitely.
+ monkeypatch.setattr("hogli_commands.doctor.select.select", lambda *_a, **_k: ([], [], []))
+ assert _confirm_stack_teardown("some-stack", timeout=0.01) is False
+
+
+def test_confirm_stack_teardown_accepts_yes(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("hogli_commands.doctor.select.select", lambda *a, **_k: (a[0], [], []))
+ monkeypatch.setattr("hogli_commands.doctor.sys.stdin.readline", lambda: "y\n")
+ assert _confirm_stack_teardown("some-stack", timeout=0.01) is True
+
+
+def test_doctor_ports_silent_when_nothing_foreign(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ _fake_docker_ps(monkeypatch, port_scan_stdout="clickhouse|posthog|127.0.0.1:8123->8123/tcp")
+ result = CliRunner().invoke(doctor_ports, [])
+ assert result.exit_code == 0
+ assert result.output == ""
+
+
+def test_doctor_ports_reports_foreign_stack_noninteractively(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Proves the command wires scan -> shape-filter -> report together; each
+ # piece has its own unit test above, but not that they're called in order.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ _fake_docker_ps(
+ monkeypatch,
+ port_scan_stdout="evilbox|foreign-proj|127.0.0.1:8010->8000/tcp",
+ clickhouse_stdout="ch1|foreign-proj\n",
+ )
+ # CliRunner's stdin/stdout are never a TTY, so this exercises the
+ # non-interactive (print-only, no subprocess teardown) branch.
+ result = CliRunner().invoke(doctor_ports, [])
+ assert result.exit_code == 0
+ assert "foreign-proj" in result.output
+ assert "docker compose -p foreign-proj -f docker-compose.dev.yml down --remove-orphans" in result.output
+
+
+ ("confirmed", "expected_teardown_calls"),
+ [
+ pytest.param(True, 1, id="confirmed-tears-down"),
+ pytest.param(False, 0, id="declined-leaves-stack-alone"),
+ ],
+)
+def test_doctor_ports_teardown_respects_confirmation(
+ monkeypatch: pytest.MonkeyPatch, confirmed: bool, expected_teardown_calls: int
+) -> None:
+ # CliRunner always simulates a non-tty stdin/stdout with no override hook,
+ # so the interactive branch is exercised by calling the command function
+ # directly instead of through Click's dispatcher. A declined prompt must
+ # leave the foreign stack running, not tear it down anyway.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ monkeypatch.setattr("hogli_commands.doctor.sys.stdin.isatty", lambda: True)
+ monkeypatch.setattr("hogli_commands.doctor.sys.stdout.isatty", lambda: True)
+ monkeypatch.setattr("hogli_commands.doctor._confirm_stack_teardown", lambda *_a, **_k: confirmed)
+
+ teardown_calls: list[list[str]] = []
+
+ def record_teardown(cmd: list[str]) -> SimpleNamespace | None:
+ if cmd[:2] == ["docker", "compose"]:
+ teardown_calls.append(cmd)
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+ return None
+
+ _fake_docker_ps(
+ monkeypatch,
+ port_scan_stdout="evilbox|foreign-proj|127.0.0.1:8010->8000/tcp",
+ clickhouse_stdout="ch1|foreign-proj\n",
+ extra=record_teardown,
+ )
+
+ assert doctor_ports.callback is not None
+ doctor_ports.callback(yes=False)
+ assert len(teardown_calls) == expected_teardown_calls
+ if confirmed:
+ # Verifies the exact teardown argv — a reordered or dropped arg here
+ # would tear down the wrong compose file.
+ assert teardown_calls == [
+ ["docker", "compose", "-p", "foreign-proj", "-f", "docker-compose.dev.yml", "down", "--remove-orphans"]
+ ]
+
+
+# ---------------------------------------------------------------------------
+# doctor:migrate-volumes
+# ---------------------------------------------------------------------------
+
+
+def _mounts_json(entries: Sequence[tuple[str, str, str]]) -> str:
+ """entries: (destination, volume name, mount type)."""
+ return json.dumps([{"Destination": dest, "Name": name, "Type": type_} for dest, name, type_ in entries])
+
+
+# Realistic mounts for a container built from docker-compose.dev.yml: the
+# clickhouse service has one named-volume mount plus several bind mounts for
+# config files; zookeeper has three named-volume mounts.
+_CLICKHOUSE_MOUNTS = _mounts_json(
+ [
+ ("/idl", "", "bind"),
+ ("/etc/clickhouse-server/config.xml", "", "bind"),
+ ("/var/lib/clickhouse", "old-ch-vol", "volume"),
+ ]
+)
+_ZOOKEEPER_MOUNTS = _mounts_json(
+ [
+ ("/datalog", "old-zk-datalog-vol", "volume"),
+ ("/data", "old-zk-data-vol", "volume"),
+ ("/logs", "old-zk-logs-vol", "volume"),
+ ]
+)
+
+
+ ("ids_by_service", "service", "project", "expected"),
+ [
+ pytest.param({"clickhouse": []}, "clickhouse", "posthog", None, id="no-containers"),
+ pytest.param({"clickhouse": ["ch1"]}, "clickhouse", "posthog", "ch1", id="single-match"),
+ pytest.param({"clickhouse": ["ch1", "ch2"]}, "clickhouse", "posthog", None, id="ambiguous-two-matches"),
+ ],
+)
+def test_find_service_container(
+ monkeypatch: pytest.MonkeyPatch,
+ ids_by_service: dict[str, list[str]],
+ service: str,
+ project: str,
+ expected: str | None,
+) -> None:
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ svc = cmd[4].split("=")[-1]
+ ids = ids_by_service.get(svc, [])
+ return SimpleNamespace(returncode=0, stdout="\n".join(f"{cid}|{project}" for cid in ids), stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ assert _find_service_container(project, service) == expected
+
+
+def test_find_service_container_ignores_matches_from_other_projects(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A container from a sibling worktree's compose project must not be mistaken
+ # for this project's — that would copy the wrong developer's data.
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ return SimpleNamespace(returncode=0, stdout="ch1|other-project\n", stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ assert _find_service_container("posthog", "clickhouse") is None
+
+
+ ("mounts", "destination", "expected"),
+ [
+ pytest.param(
+ [
+ {"Destination": "/idl", "Name": "", "Type": "bind"},
+ {"Destination": "/var/lib/clickhouse", "Name": "old-ch-vol", "Type": "volume"},
+ ],
+ "/var/lib/clickhouse",
+ "old-ch-vol",
+ id="single-volume-match-among-bind-mounts",
+ ),
+ pytest.param(
+ [{"Destination": "/idl", "Name": "", "Type": "bind"}],
+ "/var/lib/clickhouse",
+ None,
+ id="destination-not-mounted",
+ ),
+ pytest.param(
+ [
+ {"Destination": "/logs", "Name": "vol-a", "Type": "volume"},
+ {"Destination": "/logs", "Name": "vol-b", "Type": "volume"},
+ ],
+ "/logs",
+ None,
+ id="duplicate-destination-is-ambiguous",
+ ),
+ pytest.param(
+ [{"Destination": "/var/lib/clickhouse", "Name": "/host/path", "Type": "bind"}],
+ "/var/lib/clickhouse",
+ None,
+ id="bind-mount-is-not-a-volume",
+ ),
+ ],
+)
+def test_find_volume_mount(mounts: list[dict[str, object]], destination: str, expected: str | None) -> None:
+ assert _find_volume_mount(mounts, destination) == expected
+
+
+ ("run_output", "expected"),
+ [
+ pytest.param(_CLICKHOUSE_MOUNTS, json.loads(_CLICKHOUSE_MOUNTS), id="valid-mounts-json"),
+ pytest.param("not json", None, id="unparseable-inspect-output"),
+ pytest.param(None, None, id="inspect-failed"),
+ ],
+)
+def test_container_mounts(
+ monkeypatch: pytest.MonkeyPatch, run_output: str | None, expected: list[dict[str, object]] | None
+) -> None:
+ monkeypatch.setattr("hogli_commands.doctor._run_output", lambda *_a, **_k: run_output)
+ assert _container_mounts("some-container") == expected
+
+
+ ("returncode", "expected"),
+ [
+ pytest.param(1, False, id="copy-or-verify-fails"),
+ pytest.param(0, True, id="copy-and-verify-succeed"),
+ ],
+)
+def test_copy_volume(monkeypatch: pytest.MonkeyPatch, returncode: int, expected: bool) -> None:
+ calls: list[list[str]] = []
+
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ calls.append(cmd)
+ return SimpleNamespace(returncode=returncode, stdout="", stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ monkeypatch.setattr("hogli_commands.doctor.os.getpid", lambda: 4242)
+ assert _copy_volume("old-vol", "new-vol") == expected
+ # The destination-empty check now lives inside the copy container's own
+ # command (there's no second container call left to catch it separately)
+ # — lock in that the check itself doesn't silently disappear.
+ assert calls[0] == [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ "hogli-migrate-volumes-4242",
+ "-v",
+ "old-vol:/from:ro",
+ "-v",
+ "new-vol:/to",
+ "alpine",
+ "sh",
+ "-c",
+ 'rm -rf /to/* && cp -a /from/. /to/ && [ -n "$(ls -A /to)" ]',
+ ]
+ # A failed copy cleans up the named container so a later `docker volume rm -f`
+ # on the destination doesn't fail with "volume is in use".
+ if not expected:
+ assert calls[1] == ["docker", "rm", "-f", "hogli-migrate-volumes-4242"]
+
+
+def _fake_migrate_dispatcher(
+ *,
+ project: str = "posthog",
+ named_volume_exists: bool = False,
+ clickhouse_ids: Sequence[str] = ("ch1",),
+ zookeeper_ids: Sequence[str] = ("zk1",),
+ mounts_by_container: dict[str, str] | None = None,
+ copy_returncode_by_dest: dict[str, int] | None = None,
+ stop_returncode: int = 0,
+) -> tuple[Callable[..., SimpleNamespace], list[list[str]]]:
+ """Fake `subprocess.run` covering every docker call doctor_migrate_volumes
+ can make, keyed off the same argv shapes the implementation builds.
+ Records every call so tests can assert exactly what ran (or didn't).
+ """
+ calls: list[list[str]] = []
+ mounts_by_container = mounts_by_container or {"ch1": _CLICKHOUSE_MOUNTS, "zk1": _ZOOKEEPER_MOUNTS}
+ copy_returncode_by_dest = copy_returncode_by_dest or {}
+
+ def fake_run(cmd: list[str], **_kwargs: object) -> SimpleNamespace:
+ calls.append(cmd)
+
+ if cmd[:3] == ["docker", "volume", "inspect"]:
+ return SimpleNamespace(
+ returncode=0 if named_volume_exists else 1, stdout="[]" if named_volume_exists else ""
+ )
+
+ if cmd[:3] == ["docker", "ps", "-a"]:
+ service = cmd[4].split("=")[-1]
+ ids = clickhouse_ids if service == "clickhouse" else zookeeper_ids
+ return SimpleNamespace(returncode=0, stdout="\n".join(f"{cid}|{project}" for cid in ids), stderr="")
+
+ if cmd[:2] == ["docker", "inspect"]:
+ return SimpleNamespace(returncode=0, stdout=mounts_by_container.get(cmd[2], "[]"), stderr="")
+
+ if cmd[:2] == ["docker", "stop"]:
+ return SimpleNamespace(returncode=stop_returncode, stdout="", stderr="")
+
+ if cmd[:3] == ["docker", "volume", "create"]:
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ if cmd[:2] == ["docker", "run"] and "sh" in cmd:
+ # argv: docker run --rm --name <container> -v <src>:/from:ro -v <dest>:/to alpine sh -c ...
+ dest = cmd[8].split(":")[0]
+ return SimpleNamespace(returncode=copy_returncode_by_dest.get(dest, 0), stdout="", stderr="")
+
+ if cmd[:3] == ["docker", "volume", "rm"]:
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ if cmd[:2] == ["docker", "start"]:
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ return SimpleNamespace(returncode=1, stdout="", stderr="")
+
+ return fake_run, calls
+
+
+def test_doctor_migrate_volumes_noop_when_already_migrated(monkeypatch: pytest.MonkeyPatch) -> None:
+ # This runs on every `hogli start`; once the named volume exists, it must
+ # be a single fast check, not a full docker ps/inspect sweep every time.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(named_volume_exists=True)
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert result.output == ""
+ # All four destination volumes are checked in one call — the idempotency
+ # check must not rely on clickhouse-data alone, or a migration interrupted
+ # after the first volume would be mistaken for fully complete forever.
+ assert calls == [
+ [
+ "docker",
+ "volume",
+ "inspect",
+ "posthog_clickhouse-data",
+ "posthog_zookeeper-data",
+ "posthog_zookeeper-datalog",
+ "posthog_zookeeper-logs",
+ ]
+ ]
+
+
+def test_doctor_migrate_volumes_noop_on_fresh_install(monkeypatch: pytest.MonkeyPatch) -> None:
+ # No named volumes yet *and* no prior clickhouse container or postgres
+ # volume means there was never any old data — must stay silent, not warn
+ # a brand new checkout.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(named_volume_exists=False, clickhouse_ids=(), zookeeper_ids=())
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert result.output == ""
+ # dest-volumes inspect + clickhouse existence check + prior-install (postgres) check
+ assert len(calls) == 3
+
+
+def test_doctor_migrate_volumes_warns_when_stack_was_stopped(monkeypatch: pytest.MonkeyPatch) -> None:
+ # `docker compose down` removes containers but keeps volumes, so a developer
+ # who stopped the stack (rather than never having one) has no clickhouse
+ # container to salvage from, but still has real prior data. Silence here
+ # would mean an empty ClickHouse with no explanation.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(named_volume_exists=False, clickhouse_ids=(), zookeeper_ids=())
+
+ def with_prior_install(cmd: list[str], **kwargs: object) -> SimpleNamespace:
+ if cmd[:3] == ["docker", "volume", "inspect"] and cmd[3:] == ["posthog_postgres-15-data"]:
+ return SimpleNamespace(returncode=0, stdout="[]", stderr="")
+ return fake_run(cmd, **kwargs)
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", with_prior_install)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert "Switching ClickHouse/ZooKeeper to named docker volumes" in result.output
+ assert "developing-locally.md" in result.output
+ assert not any(c[:2] == ["docker", "stop"] for c in calls)
+
+
+def test_doctor_migrate_volumes_happy_path_migrates_both_services(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ monkeypatch.setattr("hogli_commands.doctor.os.getpid", lambda: 4242)
+ fake_run, calls = _fake_migrate_dispatcher()
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert "Migrated ClickHouse/ZooKeeper data" in result.output
+
+ # Both containers are stopped together before anything is copied — a live
+ # `cp -a` against an actively-written data dir can read a torn snapshot. The
+ # explicit grace period gives ClickHouse time to flush a multi-GB dataset;
+ # docker's 10s default SIGKILLs it into crash recovery.
+ assert ["docker", "stop", "-t", "60", "ch1", "zk1"] in calls
+
+ # Each destination is pre-created with compose's own labels before the copy,
+ # so compose doesn't warn "not created by Docker Compose" on every later `up`.
+ assert [
+ "docker",
+ "volume",
+ "create",
+ "--label",
+ "com.docker.compose.project=posthog",
+ "--label",
+ "com.docker.compose.volume=clickhouse-data",
+ "posthog_clickhouse-data",
+ ] in calls
+
+ # Exact copy argv for both services — a reordered or missing flag here
+ # would silently copy from (or into) the wrong volume.
+ assert [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ "hogli-migrate-volumes-4242",
+ "-v",
+ "old-ch-vol:/from:ro",
+ "-v",
+ "posthog_clickhouse-data:/to",
+ "alpine",
+ "sh",
+ "-c",
+ 'rm -rf /to/* && cp -a /from/. /to/ && [ -n "$(ls -A /to)" ]',
+ ] in calls
+ assert [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ "hogli-migrate-volumes-4242",
+ "-v",
+ "old-zk-data-vol:/from:ro",
+ "-v",
+ "posthog_zookeeper-data:/to",
+ "alpine",
+ "sh",
+ "-c",
+ 'rm -rf /to/* && cp -a /from/. /to/ && [ -n "$(ls -A /to)" ]',
+ ] in calls
+ assert [
+ "docker",
+ "run",
+ "--rm",
+ "--name",
+ "hogli-migrate-volumes-4242",
+ "-v",
+ "old-zk-datalog-vol:/from:ro",
+ "-v",
+ "posthog_zookeeper-datalog:/to",
+ "alpine",
+ "sh",
+ "-c",
+ 'rm -rf /to/* && cp -a /from/. /to/ && [ -n "$(ls -A /to)" ]',
+ ] in calls
+
+
+ ("clickhouse_ids", "zookeeper_ids", "mounts_by_container"),
+ [
+ pytest.param(("ch1",), (), None, id="zookeeper-container-already-removed"),
+ pytest.param(("ch1", "ch2"), ("zk1",), None, id="ambiguous-clickhouse-containers"),
+ pytest.param(
+ ("ch1",),
+ ("zk1",),
+ {
+ "ch1": _CLICKHOUSE_MOUNTS,
+ # zookeeper's own container and two of its three volumes resolve
+ # fine — only /logs is duplicated. The whole plan must still be
+ # discarded, not just the ambiguous piece.
+ "zk1": _mounts_json(
+ [
+ ("/datalog", "old-zk-datalog-vol", "volume"),
+ ("/data", "old-zk-data-vol", "volume"),
+ ("/logs", "vol-a", "volume"),
+ ("/logs", "vol-b", "volume"),
+ ]
+ ),
+ },
+ id="one-side-ambiguous-migrates-neither",
+ ),
+ ],
+)
+def test_doctor_migrate_volumes_falls_back_without_touching_anything(
+ monkeypatch: pytest.MonkeyPatch,
+ clickhouse_ids: Sequence[str],
+ zookeeper_ids: Sequence[str],
+ mounts_by_container: dict[str, str] | None,
+) -> None:
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(
+ clickhouse_ids=clickhouse_ids, zookeeper_ids=zookeeper_ids, mounts_by_container=mounts_by_container
+ )
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert "Switching ClickHouse/ZooKeeper to named docker volumes" in result.output
+ assert "developing-locally.md" in result.output
+ # Never guess: an ambiguous or missing piece must abort before any stop
+ # or copy call, not just skip that one piece.
+ assert not any(c[:2] == ["docker", "stop"] for c in calls)
+ assert not any(c[:2] == ["docker", "run"] for c in calls)
+
+
+def test_doctor_migrate_volumes_copy_failure_rolls_back(monkeypatch: pytest.MonkeyPatch) -> None:
+ # ClickHouse and zookeeper-data copy cleanly, but zookeeper-datalog fails
+ # verification. Restoring only clickhouse+zookeeper-data would leave a
+ # replicated table with "replica already exists" once ClickHouse starts
+ # against restored state but ZooKeeper doesn't know about it.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(copy_returncode_by_dest={"posthog_zookeeper-datalog": 1})
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert "Switching ClickHouse/ZooKeeper to named docker volumes" in result.output
+ assert "Migrated" not in result.output
+
+ # The two volumes that copied successfully before the failure are rolled
+ # back in one call, alongside the failed step's own (possibly
+ # partially-written) volume — `docker run -v <dest>:/to ...` auto-creates
+ # the destination volume before its command runs, so it must be removed
+ # too, or a torn copy can survive rollback and get mistaken for a
+ # completed migration on the next run. The containers we stopped are
+ # restarted.
+ assert [
+ "docker",
+ "volume",
+ "rm",
+ "-f",
+ "posthog_clickhouse-data",
+ "posthog_zookeeper-data",
+ "posthog_zookeeper-datalog",
+ ] in calls
+ assert ["docker", "start", "ch1", "zk1"] in calls
+ # The step after the failed one must never run.
+ assert not any(c[:2] == ["docker", "run"] and "posthog_zookeeper-logs:/to" in c for c in calls)
+
+
+def test_doctor_migrate_volumes_copy_timeout_rolls_back(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A large ClickHouse volume on a slow disk can exceed the copy timeout.
+ # subprocess.run raising TimeoutExpired must not skip rollback and leave
+ # the old containers stopped with a half-written destination volume.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher()
+
+ def timing_out_run(cmd: list[str], **kwargs: object) -> SimpleNamespace:
+ if cmd[:2] == ["docker", "run"] and "posthog_clickhouse-data:/to" in cmd:
+ raise subprocess.TimeoutExpired(cmd=cmd, timeout=120)
+ return fake_run(cmd, **kwargs)
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", timing_out_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert "Switching ClickHouse/ZooKeeper to named docker volumes" in result.output
+ assert ["docker", "volume", "rm", "-f", "posthog_clickhouse-data"] in calls
+ assert ["docker", "start", "ch1", "zk1"] in calls
+
+
+def test_doctor_migrate_volumes_interrupt_rolls_back(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Ctrl-C during a multi-GB copy raises KeyboardInterrupt, which isn't a
+ # subprocess.SubprocessError, so it wouldn't be caught by the same except
+ # clause that handles a copy failure or timeout. Without an explicit
+ # rollback on it, the destination volume survives half-written and the
+ # next start's idempotency check mistakes it for a completed migration.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher()
+
+ def interrupted_run(cmd: list[str], **kwargs: object) -> SimpleNamespace:
+ if cmd[:2] == ["docker", "run"] and "posthog_clickhouse-data:/to" in cmd:
+ raise KeyboardInterrupt
+ return fake_run(cmd, **kwargs)
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", interrupted_run)
+
+ assert doctor_migrate_volumes.callback is not None
+ with pytest.raises(KeyboardInterrupt):
+ doctor_migrate_volumes.callback()
+ assert ["docker", "volume", "rm", "-f", "posthog_clickhouse-data"] in calls
+ assert ["docker", "start", "ch1", "zk1"] in calls
+
+
+def test_doctor_migrate_volumes_stop_failure_restarts_containers(monkeypatch: pytest.MonkeyPatch) -> None:
+ # `docker stop` on multiple containers can exit non-zero after partially
+ # succeeding (e.g. one already vanished). Without a restart here, a
+ # container that *did* stop would stay down even though no migration
+ # happened — leaving a working dev stack unexpectedly offline.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(stop_returncode=1)
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert "Switching ClickHouse/ZooKeeper to named docker volumes" in result.output
+ assert ["docker", "start", "ch1", "zk1"] in calls
+ # Nothing was copied, so nothing needs to be rolled back.
+ assert not any(c[:2] == ["docker", "run"] for c in calls)
+
+
+def test_run_ok_echoes_stderr_on_failure(monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]) -> None:
+ # `_run_ok` used to swallow captured stderr entirely on failure, so a real
+ # docker-level error (permission denied, disk full, daemon hiccup) was
+ # indistinguishable from any other failure once the caller fell back to its
+ # generic warning.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda *_a, **_k: SimpleNamespace(returncode=1, stdout="", stderr="permission denied\n"),
+ )
+ assert _run_ok(["docker", "volume", "create", "x"]) is False
+ assert "permission denied" in capsys.readouterr().out
+
+
+def test_doctor_migrate_volumes_serializes_across_concurrent_worktrees(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # `bin/start`'s own lock is per-worktree, but every worktree shares one compose
+ # project, so two worktrees starting at once could both plan a migration for the
+ # same destination volumes — one's rollback then deletes data the other just
+ # copied. Prove a held lock blocks a concurrent invocation instead of letting it
+ # race in unlocked.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(named_volume_exists=True)
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ lock_path = tmp_path / "hogli-migrate-volumes-posthog.lock"
+ holder = open(lock_path, "w")
+ fcntl.flock(holder, fcntl.LOCK_EX)
+
+ done = threading.Event()
+ thread = threading.Thread(target=lambda: (doctor_migrate_volumes.callback(), done.set())) # type: ignore[misc]
+ thread.start()
+ try:
+ # Still blocked on the lock: no docker call has run yet.
+ assert not done.wait(timeout=0.1)
+ assert calls == []
+ finally:
+ fcntl.flock(holder, fcntl.LOCK_UN)
+ holder.close()
+
+ thread.join(timeout=5)
+ assert done.is_set()
+ assert calls # released promptly and ran through once unblocked
+
+
+def test_doctor_migrate_volumes_refuses_symlinked_lock_path(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # The lock path is predictable and, on Linux, lives in world-writable /tmp.
+ # Opening it with "w" follows a symlink another local user planted there and
+ # truncates the target, handing them a file-destruction primitive in the
+ # developer's account. Runs on every `hogli start`, so this must stay a
+ # no-follow open — and must still fail open rather than crash the startup.
+ monkeypatch.setattr("hogli_commands.doctor.shutil.which", lambda _: "/usr/bin/docker")
+ fake_run, calls = _fake_migrate_dispatcher(named_volume_exists=True)
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ victim = tmp_path / "victim"
+ victim.write_text("precious")
+ (tmp_path / "hogli-migrate-volumes-posthog.lock").symlink_to(victim)
+
+ result = CliRunner().invoke(doctor_migrate_volumes, [])
+ assert result.exit_code == 0
+ assert victim.read_text() == "precious"
+ assert calls == [] # bailed before touching docker
diff --git a/tools/phrocs/README.md b/tools/phrocs/README.md
index 082a30e9cd7f..feacd289b3a3 100644
--- a/tools/phrocs/README.md
+++ b/tools/phrocs/README.md
@@ -85,10 +85,13 @@ You typically run phrocs via `hogli start` rather than directly.
| `esc` | Exit copy, search, and filter modes |
| `↵` | Send keystrokes to the process (output pane) |
| `?` | Toggle full help |
-| `q` | Quit |
+| `q` | Quit (docker containers keep running; see below) |
Mouse clicks switch focus; mouse wheel scrolls the output pane.
+Quitting stops the processes phrocs supervises, but the docker compose containers keep running: `docker compose up` runs detached (`-d`), and the compose stack is deliberately shared across worktrees.
+To fully tear it down, run `hogli docker:services:down` (or `hogli docker:services:remove` to also wipe volumes).
+
### Copy mode
Press `c` to enter copy mode in the output pane.
diff --git a/tools/phrocs/internal/docker/docker.go b/tools/phrocs/internal/docker/docker.go
index 1f98c82266c8..679e7f284ead 100644
--- a/tools/phrocs/internal/docker/docker.go
+++ b/tools/phrocs/internal/docker/docker.go
@@ -96,8 +96,16 @@ func StripComposeLogsTail(shell string) string {
return shell
}
last := strings.TrimSpace(segments[len(segments)-1])
+ // The logs tail may sit inside an if/else (e.g. the POSTHOG_SANDBOX guard),
+ // leaving "; fi" attached to the final segment. Preserve the closer so the
+ // stripped shell still parses.
+ suffix := ""
+ if trimmed, ok := strings.CutSuffix(last, "; fi"); ok {
+ last = strings.TrimSpace(trimmed)
+ suffix = "; fi"
+ }
if IsDockerComposeShell(last) && strings.Contains(last, "logs") {
- return strings.TrimRight(strings.Join(segments[:len(segments)-1], "&&"), " ")
+ return strings.TrimRight(strings.Join(segments[:len(segments)-1], "&&"), " ") + suffix
}
return shell
}
diff --git a/tools/phrocs/internal/docker/docker_test.go b/tools/phrocs/internal/docker/docker_test.go
index 1f2608be317a..8a1c7858e08e 100644
--- a/tools/phrocs/internal/docker/docker_test.go
+++ b/tools/phrocs/internal/docker/docker_test.go
@@ -3,11 +3,13 @@ package docker
import (
"fmt"
"os"
+ "os/exec"
"path/filepath"
"strings"
"testing"
"github.com/charmbracelet/x/ansi"
+ "github.com/posthog/posthog/phrocs/internal/config"
)
func installFakeDocker(t *testing.T, script string) {
@@ -108,6 +110,11 @@ func TestStripComposeLogsTail(t *testing.T) {
shell: "docker compose up",
want: "docker compose up",
},
+ {
+ name: "logs tail inside if/else keeps the fi",
+ shell: `if [ "$S" = "1" ]; then sleep infinity; else docker compose -f a.yml up -d && echo ready && docker compose -f a.yml logs --tail=100 -f; fi`,
+ want: `if [ "$S" = "1" ]; then sleep infinity; else docker compose -f a.yml up -d && echo ready; fi`,
+ },
}
for _, tc := range tests {
@@ -119,6 +126,32 @@ func TestStripComposeLogsTail(t *testing.T) {
}
}
+// TestStripComposeLogsTailOnRealDockerComposeProcShell strips the actual
+// docker-compose proc shell phrocs loads at runtime (bin/mprocs.yaml, via
+// config.LoadRegistry), not just the hand-written fixtures above. If a future
+// edit to that shell leaves a dangling else/fi after stripping, the
+// docker-compose proc fails to parse and the whole dev stack fails to start,
+// with none of the fixture-based cases above able to catch it.
+func TestStripComposeLogsTailOnRealDockerComposeProcShell(t *testing.T) {
+ cfg, err := config.LoadRegistry()
+ if err != nil || cfg == nil {
+ t.Skip("bin/mprocs.yaml not found from this working directory")
+ }
+ proc, ok := cfg.Procs["docker-compose"]
+ if !ok {
+ t.Fatal("docker-compose proc not found in bin/mprocs.yaml")
+ }
+
+ stripped := StripComposeLogsTail(proc.Shell)
+
+ if strings.Contains(stripped, "logs") && strings.Contains(stripped, "--tail") {
+ t.Fatalf("expected the logs tail to be stripped, got: %q", stripped)
+ }
+ if err := exec.Command("bash", "-n", "-c", stripped).Run(); err != nil {
+ t.Fatalf("stripped shell is not valid bash: %v\nshell: %q", err, stripped)
+ }
+}
+
func TestComposeBaseArgs(t *testing.T) {
if got := composeBaseArgs(ComposeArgs{}); strings.Join(got, " ") != "compose" {
t.Fatalf("composeBaseArgs(empty) = %v", got)
diff --git a/tools/phrocs/main.go b/tools/phrocs/main.go
index ecf1014721eb..dfca5589381b 100644
--- a/tools/phrocs/main.go
+++ b/tools/phrocs/main.go
@@ -235,5 +235,12 @@ func runInteractive(configPath string, debug bool) int {
fmt.Fprintf(os.Stderr, "phrocs: %v\n", err)
return 1
}
+ // Quitting phrocs stops its supervised processes, but docker compose runs
+ // detached (`up -d`), so containers keep running by design: the compose
+ // stack is shared across worktrees. Say so, since nothing else does.
+ // (printDockerTeardownHint itself stays quiet in sandboxes.)
+ if _, ok := cfg.Procs["docker-compose"]; ok {
+ printDockerTeardownHint()
+ }
return 0
}
diff --git a/tools/phrocs/subcommands.go b/tools/phrocs/subcommands.go
index d1b78eecc766..8f20e3917811 100644
--- a/tools/phrocs/subcommands.go
+++ b/tools/phrocs/subcommands.go
@@ -195,6 +195,27 @@ func printJSON(v any) {
_ = json.NewEncoder(os.Stdout).Encode(v)
}
+// printDockerTeardownHint reminds the user that docker containers outlive
+// phrocs: docker compose runs detached (`up -d`) and the stack is shared
+// across worktrees, so stopping phrocs never stops them. In a sandbox the
+// infra is managed externally, so the hint would be wrong there.
+func printDockerTeardownHint() {
+ if os.Getenv("POSTHOG_SANDBOX") == "1" {
+ return
+ }
+ fmt.Println("Docker services keep running after phrocs stops (the compose stack is shared across worktrees).")
+ fmt.Println("Full teardown: hogli docker:services:down (also wipe volumes: hogli docker:services:remove)")
+}
+
+// phrocsStopped prints msg, reminds the user docker containers keep running,
+// and returns the standard success code. Not used by the SIGKILL path, which
+// writes to stderr with different wording.
+func phrocsStopped(msg string) int {
+ fmt.Println(msg)
+ printDockerTeardownHint()
+ return 0
+}
+
// runStop sends a quit command to the detached phrocs, waits for the socket
// to disappear, and falls back to SIGTERM → SIGKILL via the pidfile if needed.
func runStop(timeoutSec int) int {
@@ -226,8 +247,7 @@ func runStop(timeoutSec int) int {
// Lock-check errors are treated as "still held" to avoid
// false-positive cleanup on transient failures.
if cleaned, lerr := cleanIfStale(""); lerr == nil && cleaned {
- fmt.Println("phrocs stopped")
- return 0
+ return phrocsStopped("phrocs stopped")
}
}
time.Sleep(100 * time.Millisecond)
@@ -236,8 +256,7 @@ func runStop(timeoutSec int) int {
// check whether the detached phrocs finished its graceful shutdown
// between our last dial and this check.
if cleaned, lerr := cleanIfStale(sock); lerr == nil && cleaned {
- fmt.Println("phrocs stopped")
- return 0
+ return phrocsStopped("phrocs stopped")
}
fmt.Fprintln(os.Stderr, "phrocs: detached phrocs did not exit in time; escalating")
}
@@ -266,8 +285,7 @@ func stopViaPidfile(sock string, deadline time.Time) int {
// phrocs has already exited cleanly. Clean up any leftover socket
// and report success rather than a confusing "file not found".
_ = os.Remove(sock)
- fmt.Println("phrocs stopped")
- return 0
+ return phrocsStopped("phrocs stopped")
}
if err != nil {
fmt.Fprintf(os.Stderr, "phrocs: %v\n", err)
@@ -284,8 +302,7 @@ func stopViaPidfile(sock string, deadline time.Time) int {
if !pidAlive(pid) {
_ = os.Remove(pidFilePath())
_ = os.Remove(sock)
- fmt.Println("phrocs stopped (SIGTERM)")
- return 0
+ return phrocsStopped("phrocs stopped (SIGTERM)")
}
time.Sleep(100 * time.Millisecond)
}
@@ -296,6 +313,7 @@ func stopViaPidfile(sock string, deadline time.Time) int {
_ = os.Remove(pidFilePath())
_ = os.Remove(sock)
fmt.Fprintln(os.Stderr, "phrocs killed (SIGKILL)")
+ printDockerTeardownHint()
return 0
}
diff --git a/tools/phrocs/subcommands_test.go b/tools/phrocs/subcommands_test.go
index fe38ebbd5a76..ffecc98be31c 100644
--- a/tools/phrocs/subcommands_test.go
+++ b/tools/phrocs/subcommands_test.go
@@ -102,6 +102,24 @@ func TestRunWait_shortTimeoutBeforeBindIsNotReachable(t *testing.T) {
}
}
+func TestPhrocsStopped_sandboxSuppressesDockerHint(t *testing.T) {
+ // In a sandbox, docker infra is managed externally, so telling the user
+ // to run `hogli docker:services:down` points at infra phrocs doesn't own.
+ t.Setenv("POSTHOG_SANDBOX", "1")
+ _, out := captureStdout(t, func() int { return phrocsStopped("phrocs stopped") })
+ if strings.Contains(out, "docker:services:down") {
+ t.Fatalf("sandbox must not print the docker teardown hint: %q", out)
+ }
+}
+
+func TestPhrocsStopped_printsDockerHintOutsideSandbox(t *testing.T) {
+ t.Setenv("POSTHOG_SANDBOX", "")
+ _, out := captureStdout(t, func() int { return phrocsStopped("phrocs stopped") })
+ if !strings.Contains(out, "docker:services:down") {
+ t.Fatalf("expected the docker teardown hint outside a sandbox: %q", out)
+ }
+}
+
func TestRunStop_quitPathRemovesPidfile(t *testing.T) {
t.Chdir(t.TempDir())
if err := os.MkdirAll(generatedDir(), 0o755); err != nil {