:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(hogli): postgres schema fast path for local dev (#57317)
Raúl Negrón-Otero71f7865a116b
diff --git a/bin/mprocs.yaml b/bin/mprocs.yamlindex 46b588120dad..6b3affa17819 100755--- a/bin/mprocs.yaml+++ b/bin/mprocs.yaml@@ -432,7 +432,7 @@ procs:tech: Pythonmigrate-postgres:- shell: 'bin/wait-for-docker && bin/migrate --scope=postgres'+ shell: 'bin/wait-for-docker && bin/hogli db:restore-schema-if-fresh && bin/migrate --scope=postgres'capability: core_infraready_pattern: 'All migrations completed successfully'groups:diff --git a/bin/start b/bin/startindex 391f83149881..8f9226e99d54 100755--- a/bin/start+++ b/bin/start@@ -74,6 +74,8 @@ if [ -f .env ]; thenset +o allexportfi+export POSTHOG_SCHEMA_RESTORE_IN_DEV=${POSTHOG_SCHEMA_RESTORE_IN_DEV:-auto}+# Ducklakeexport DUCKLAKE_RDS_HOST=${DUCKLAKE_RDS_HOST:-db}export DUCKLAKE_RDS_PORT=${DUCKLAKE_RDS_PORT:-5432}diff --git a/hogli.yaml b/hogli.yamlindex 14e50f475903..2ac6af325605 100644--- a/hogli.yaml+++ b/hogli.yaml@@ -629,32 +629,7 @@ db:- postgresql- dockerdb:restore-test-db:- cmd: |- set -e- TARGET_DB="${TARGET_DB:-test_posthog}"- # Validate before interpolating into psql -c. Postgres unquoted identifiers- # must start with a letter or underscore, contain only [A-Za-z0-9_], and- # fit in NAMEDATALEN-1 (63 chars). Reject anything else outright rather- # than trying to escape — callers always pass static names like- # `test_posthog` or `posthog_e2e_test`. POSIX-only (no bash `[[ =~ ]]`)- # since hogli runs cmd blocks via /bin/sh.- if ! printf '%s' "$TARGET_DB" | grep -Eq '^[A-Za-z_][A-Za-z0-9_]{0,62}$'; then- echo "❌ TARGET_DB must be a simple SQL identifier (got: $TARGET_DB)"- exit 1- fi- if [ ! -f .postgres-backups/schema-latest.sql.gz ]; then- echo "❌ No schema at .postgres-backups/schema-latest.sql.gz — run db:download-schema first"- exit 1- fi- # Validate up front; substitutes for `set -o pipefail` (dash doesn't support it).- gunzip -t .postgres-backups/schema-latest.sql.gz- docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "DROP DATABASE IF EXISTS $TARGET_DB;"- docker compose -f docker-compose.dev.yml exec -T db psql -U posthog -c "CREATE DATABASE $TARGET_DB;"- gunzip -c .postgres-backups/schema-latest.sql.gz | docker compose -f docker-compose.dev.yml exec -T db psql -q -U posthog "$TARGET_DB"- # Schema-only dumps skip RunPython data migrations (e.g. the Default Theme row from 0537).- # Reseed defaults so tests don't hit empty tables. Idempotent.- DATABASE_URL="postgres://posthog:posthog@localhost:5432/$TARGET_DB" python manage.py ensure_migration_defaults- echo "✅ Restored $TARGET_DB from .postgres-backups/schema-latest.sql.gz"+ click: hogli_commands.db_schema:db_restore_test_dbdescription: 'Restore a fresh DB from a local schema dump (no download). Drops andrecreates the target DB then loads schema-latest.sql.gz into it. Target DBdefaults to test_posthog; override via TARGET_DB env var. Used by CI after@@ -663,42 +638,26 @@ db:- postgresql- dockerdb:restore-schema-fresh:- steps:- - db:restore-test-db+ click: hogli_commands.db_schema:db_restore_schema_freshdescription: Alias for db:restore-test-db. Kept so PR branches that pulled in theshort-lived rename (#57657) still resolve a valid command after the revert.Safe to remove once those branches are merged or rebased.db:download-schema:- cmd: "set -e\nmkdir -p .postgres-backups\necho \"Finding latest CI run with migrated-schema\- \ artifact...\"\nRUN_ID=$(gh api 'repos/PostHog/posthog/actions/artifacts?name=migrated-schema&per_page=10'\- \ --jq '[.artifacts[] | select(.expired == false and .size_in_bytes > 10000)]\- \ | .[0].workflow_run.id')\nif [ -z \"$RUN_ID\" ]; then\n echo \"\u274C No\- \ migrated-schema artifact found. Has CI run on master yet?\"\n exit 1\n\- fi\necho \"Downloading from run $RUN_ID...\"\ngh run download \"$RUN_ID\" --name\- \ migrated-schema -R PostHog/posthog -D /tmp/migrated-schema-dl\nmv /tmp/migrated-schema-dl/schema.sql.gz\- \ .postgres-backups/schema-latest.sql.gz\nrm -rf /tmp/migrated-schema-dl\necho\- \ \"\u2705 Downloaded to .postgres-backups/schema-latest.sql.gz\"\n"- description: Download pre-migrated schema artifact from CI (requires gh CLI)+ click: hogli_commands.db_schema:db_download_schema+ description: Download the newest compatible pre-migrated schema artifact from CI+ (requires gh auth or GH_TOKEN)+ db:restore-schema-if-fresh:+ click: hogli_commands.db_schema:db_restore_schema_if_fresh+ description: Restore a compatible schema into an empty local dev database before+ migrations. Defaults to best-effort auto mode; set POSTHOG_SCHEMA_RESTORE_IN_DEV=off+ to disable or on to fail on restore errors.+ services:+ - postgresql+ - dockerdb:restore-schema:- steps:- - db:download-schema- - db:dump- - name: restore-schema- cmd: "set -e\nset -o pipefail\necho \"Restoring schema to database...\"\ngunzip\- \ -c .postgres-backups/schema-latest.sql.gz | docker compose exec -T db psql\- \ -q -U posthog posthog\necho \"\u2705 Schema restored\"\n"- - db:migrate- - name: ensure-migration-defaults- cmd: 'set -e-- echo "Ensuring default migration data..."-- python manage.py ensure_migration_defaults-- '+ click: hogli_commands.db_schema:db_restore_schemadescription: Fetch pre-migrated schema from CI, restore it, and run any pendingmigrations (creates backup first)- prompt: trueservices:- postgresql- dockerdiff --git a/tools/hogli-commands/hogli_commands/db_schema.py b/tools/hogli-commands/hogli_commands/db_schema.pynew file mode 100644index 000000000000..7f040a7a0dad--- /dev/null+++ b/tools/hogli-commands/hogli_commands/db_schema.py@@ -0,0 +1,616 @@+"""Postgres schema restore helpers for hogli."""++from __future__ import annotations++import os+import re+import gzip+import shutil+import zipfile+import tempfile+import subprocess+from collections.abc import Iterable, Mapping+from dataclasses import dataclass+from datetime import UTC, datetime+from pathlib import Path+from typing import Literal, TypeVar, cast++import click+import requests++ArtifactMode = Literal["off", "auto", "on"]++GITHUB_REPOSITORY = "PostHog/posthog"+SCHEMA_ARTIFACT_NAME = "migrated-schema"+SCHEMA_DUMP_NAME = "schema.sql.gz"+LOCAL_SCHEMA_PATH = Path(".postgres-backups/schema-latest.sql.gz")+MIN_SCHEMA_ARTIFACT_BYTES = 10_000+DEFAULT_BASE_BRANCH = "master"+DIAGNOSTIC_CANDIDATE_LIMIT = 3+DOCKER_COMPOSE = ["docker", "compose", "-f", "docker-compose.dev.yml"]+DB_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]{0,62}$")++T = TypeVar("T")+++def _require_type(value: object, expected: type[T]) -> T:+ if not isinstance(value, expected):+ raise TypeError(f"expected {expected.__name__}, got {type(value).__name__}")+ return value+++class SchemaRestoreError(Exception):+ """Base exception for schema restore failures."""+++class SchemaRestoreUnavailable(SchemaRestoreError):+ """Raised when a schema restore is not possible in the current environment."""+++class SchemaRestoreCleanupFailed(SchemaRestoreError):+ """Raised when migrations should not run after a failed restore."""+++@dataclass(frozen=True)+class SchemaArtifact:+ id: int+ name: str+ expired: bool+ size_in_bytes: int+ archive_download_url: str+ head_sha: str+ head_branch: str+ created_at: str+++def _find_repo_root() -> Path:+ current = Path(__file__).resolve()+ for parent in current.parents:+ if (parent / "hogli.yaml").exists():+ return parent+ return Path.cwd()+++REPO_ROOT = _find_repo_root()+++def _resolve_repo_path(path: Path) -> Path:+ if path.is_absolute():+ return path+ return REPO_ROOT / path+++def _run(command: list[str], *, env: Mapping[str, str] | None = None) -> None:+ subprocess.run(+ command,+ cwd=REPO_ROOT,+ env={**os.environ, **dict(env or {})},+ check=True,+ )+++def _validate_db_identifier(target_db: str) -> str:+ if not DB_IDENTIFIER_RE.fullmatch(target_db):+ raise SchemaRestoreError(f"target database must be a simple SQL identifier (got: {target_db})")+ return target_db+++def _validate_gzip(path: Path) -> None:+ bytes_read = 0+ try:+ with gzip.open(path, "rb") as source:+ while chunk := source.read(1024 * 1024):+ bytes_read += len(chunk)+ except (OSError, EOFError) as exc:+ raise SchemaRestoreError(f"schema dump is not valid gzip: {path}") from exc+ if bytes_read == 0:+ raise SchemaRestoreError(f"schema dump is not valid gzip: {path}")+++def _run_psql_with_gzip_input(gzip_path: Path, target_db: str) -> None:+ command = [+ *DOCKER_COMPOSE,+ "exec",+ "-T",+ "db",+ "psql",+ "-q",+ "-v",+ "ON_ERROR_STOP=1",+ "--single-transaction",+ "-U",+ "posthog",+ target_db,+ ]+ process = subprocess.Popen(+ command,+ cwd=REPO_ROOT,+ env=os.environ.copy(),+ stdin=subprocess.PIPE,+ )+ assert process.stdin is not None # stdin=PIPE guarantees this++ try:+ with gzip.open(gzip_path, "rb") as source:+ shutil.copyfileobj(source, process.stdin)+ except Exception:+ process.kill()+ process.wait()+ raise+ finally:+ try:+ process.stdin.close()+ except BrokenPipeError:+ pass++ returncode = process.wait()+ if returncode != 0:+ raise subprocess.CalledProcessError(returncode, command)+++def _psql_admin(sql: str) -> None:+ """Run a one-shot SQL statement against the postgres maintenance database."""+ _run([*DOCKER_COMPOSE, "exec", "-T", "db", "psql", "-U", "posthog", "postgres", "-c", sql])+++def _recreate_database(target_db: str) -> None:+ _psql_admin(f"DROP DATABASE IF EXISTS {target_db};")+ _psql_admin(f"CREATE DATABASE {target_db};")+++def _ensure_migration_defaults(target_db: str) -> None:+ _run(+ ["python", "manage.py", "ensure_migration_defaults"],+ env={"DATABASE_URL": f"postgres://posthog:posthog@localhost:5432/{target_db}"},+ )+++def restore_schema_dump(+ *,+ target_db: str,+ recreate: bool,+ schema_path: Path = LOCAL_SCHEMA_PATH,+ ensure_defaults: bool = True,+) -> None:+ target_db = _validate_db_identifier(target_db)+ resolved_schema_path = _resolve_repo_path(schema_path)+ if not resolved_schema_path.is_file():+ raise SchemaRestoreError(f"no schema at {schema_path}; run db:download-schema first")++ _validate_gzip(resolved_schema_path)++ if recreate:+ _recreate_database(target_db)++ try:+ _run_psql_with_gzip_input(resolved_schema_path, target_db)++ if ensure_defaults:+ _ensure_migration_defaults(target_db)+ except Exception as exc:+ if recreate:+ try:+ _recreate_database(target_db)+ except Exception as cleanup_exc:+ raise SchemaRestoreCleanupFailed(+ f"schema restore failed and cleanup failed for {target_db}: {cleanup_exc}"+ ) from exc+ raise++ click.echo(f"Restored {target_db} from {schema_path}")+++def _github_token() -> str | None:+ for env_var in ("GH_TOKEN", "GITHUB_TOKEN"):+ token = os.environ.get(env_var)+ if token:+ return token++ gh_path = shutil.which("gh")+ if gh_path is None:+ return None++ try:+ result = subprocess.run(+ [gh_path, "auth", "token"],+ cwd=REPO_ROOT,+ capture_output=True,+ text=True,+ timeout=10,+ check=False,+ )+ except (OSError, subprocess.TimeoutExpired):+ return None++ token = result.stdout.strip()+ if result.returncode == 0 and token:+ return token+ return None+++def _github_headers(token: str | None) -> dict[str, str]:+ headers = {+ "Accept": "application/vnd.github+json",+ "X-GitHub-Api-Version": "2022-11-28",+ }+ if token:+ headers["Authorization"] = f"Bearer {token}"+ return headers+++def _artifact_from_api(raw: Mapping[str, object]) -> SchemaArtifact | None:+ workflow_run = raw.get("workflow_run")+ if not isinstance(workflow_run, Mapping):+ return None+ try:+ return SchemaArtifact(+ id=_require_type(raw.get("id"), int),+ name=_require_type(raw.get("name"), str),+ expired=_require_type(raw.get("expired"), bool),+ size_in_bytes=_require_type(raw.get("size_in_bytes"), int),+ archive_download_url=_require_type(raw.get("archive_download_url"), str),+ head_sha=_require_type(workflow_run.get("head_sha"), str),+ head_branch=_require_type(workflow_run.get("head_branch"), str),+ created_at=_require_type(raw.get("created_at"), str),+ )+ except TypeError:+ return None+++def _parse_github_datetime(value: str) -> datetime:+ try:+ return datetime.fromisoformat(value.replace("Z", "+00:00"))+ except ValueError:+ return datetime.min.replace(tzinfo=UTC)+++def _filter_and_sort_candidates(+ artifacts: Iterable[SchemaArtifact],+ *,+ base_branch: str,+) -> list[SchemaArtifact]:+ candidates = [+ artifact+ for artifact in artifacts+ if artifact.name == SCHEMA_ARTIFACT_NAME+ and not artifact.expired+ and artifact.size_in_bytes > MIN_SCHEMA_ARTIFACT_BYTES+ and artifact.head_sha+ and artifact.head_branch == base_branch+ ]+ candidates.sort(key=lambda artifact: (_parse_github_datetime(artifact.created_at), artifact.id), reverse=True)+ return candidates+++def select_newest_compatible_artifact(+ artifacts: Iterable[SchemaArtifact],+ *,+ base_branch: str = DEFAULT_BASE_BRANCH,+) -> SchemaArtifact | None:+ candidates = _filter_and_sort_candidates(artifacts, base_branch=base_branch)+ return candidates[0] if candidates else None+++def fetch_schema_artifacts(*, token: str | None, session: requests.Session | None = None) -> list[SchemaArtifact]:+ http = session or requests.Session()+ artifacts: list[SchemaArtifact] = []+ page = 1++ while True:+ response = http.get(+ f"https://api.github.com/repos/{GITHUB_REPOSITORY}/actions/artifacts",+ params={"name": SCHEMA_ARTIFACT_NAME, "per_page": 100, "page": page},+ headers=_github_headers(token),+ timeout=30,+ )+ response.raise_for_status()+ payload = response.json()+ if not isinstance(payload, Mapping):+ raise SchemaRestoreError("GitHub artifacts API returned an unexpected payload")++ raw_artifacts = payload.get("artifacts")+ if not isinstance(raw_artifacts, list):+ raise SchemaRestoreError("GitHub artifacts API returned no artifact list")++ for raw_artifact in raw_artifacts:+ if isinstance(raw_artifact, Mapping):+ artifact = _artifact_from_api(raw_artifact)+ if artifact is not None:+ artifacts.append(artifact)++ if "next" not in response.links:+ break+ page += 1++ return artifacts+++def download_schema_artifact(+ artifact: SchemaArtifact,+ *,+ token: str | None,+ destination: Path = LOCAL_SCHEMA_PATH,+ session: requests.Session | None = None,+) -> None:+ if token is None:+ raise SchemaRestoreUnavailable("no GitHub token found; run `gh auth login` or set GH_TOKEN")++ http = session or requests.Session()+ response = http.get(+ artifact.archive_download_url,+ headers=_github_headers(token),+ stream=True,+ timeout=60,+ )+ response.raise_for_status()++ resolved_destination = _resolve_repo_path(destination)+ resolved_destination.parent.mkdir(parents=True, exist_ok=True)++ with tempfile.TemporaryDirectory(prefix="migrated-schema-") as temp_dir_name:+ temp_dir = Path(temp_dir_name)+ archive_path = temp_dir / "artifact.zip"+ with open(archive_path, "wb") as archive_file:+ for chunk in response.iter_content(chunk_size=1024 * 1024):+ if chunk:+ archive_file.write(chunk)++ with zipfile.ZipFile(archive_path) as archive:+ schema_members = [+ member+ for member in archive.namelist()+ if Path(member).name == SCHEMA_DUMP_NAME and not member.endswith("/")+ ]+ if not schema_members:+ raise SchemaRestoreError(f"artifact {artifact.id} does not contain {SCHEMA_DUMP_NAME}")++ partial_destination = resolved_destination.with_suffix(resolved_destination.suffix + ".tmp")+ with archive.open(schema_members[0]) as source, open(partial_destination, "wb") as destination_file:+ shutil.copyfileobj(source, destination_file)+ partial_destination.replace(resolved_destination)++ click.echo(f"Downloaded schema artifact {artifact.id} to {destination}")+++def _emit_selection_diagnostics(+ artifacts: list[SchemaArtifact],+ *,+ base_branch: str,+) -> None:+ candidates = _filter_and_sort_candidates(artifacts, base_branch=base_branch)+ click.echo(+ f"Fetched {len(artifacts)} {SCHEMA_ARTIFACT_NAME} artifact(s) from GitHub Actions",+ err=True,+ )+ click.echo(+ f"After name/expiry/size/branch filters: {len(candidates)} candidate(s) (base_branch={base_branch})",+ err=True,+ )+ for artifact in candidates[:DIAGNOSTIC_CANDIDATE_LIMIT]:+ click.echo(+ f" candidate id={artifact.id} sha={artifact.head_sha[:8]} created_at={artifact.created_at}",+ err=True,+ )+++def download_latest_compatible_schema(+ *,+ destination: Path = LOCAL_SCHEMA_PATH,+ base_branch: str = DEFAULT_BASE_BRANCH,+ session: requests.Session | None = None,+) -> SchemaArtifact:+ token = _github_token()+ artifacts = fetch_schema_artifacts(token=token, session=session)+ artifact = select_newest_compatible_artifact(artifacts, base_branch=base_branch)+ if artifact is None:+ _emit_selection_diagnostics(artifacts, base_branch=base_branch)+ raise SchemaRestoreUnavailable(+ f"no compatible {SCHEMA_ARTIFACT_NAME} artifact found for base_branch={base_branch}"+ )++ download_schema_artifact(artifact, token=token, destination=destination, session=session)+ return artifact+++def is_database_empty(target_db: str) -> bool:+ target_db = _validate_db_identifier(target_db)+ query = """+ SELECT COUNT(*)+ FROM pg_catalog.pg_class c+ JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')+ AND n.nspname !~ '^pg_toast'+ AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f');+ """+ result = subprocess.run(+ [*DOCKER_COMPOSE, "exec", "-T", "db", "psql", "-qAt", "-U", "posthog", target_db, "-c", query],+ cwd=REPO_ROOT,+ env=os.environ.copy(),+ capture_output=True,+ text=True,+ check=False,+ )+ if result.returncode != 0:+ raise SchemaRestoreError(result.stderr.strip() or f"failed to inspect database {target_db}")++ try:+ relation_count = int(result.stdout.strip() or "0")+ except ValueError as exc:+ raise SchemaRestoreError(f"unexpected relation count from database {target_db}: {result.stdout!r}") from exc++ return relation_count == 0+++def restore_schema_if_fresh(*, target_db: str, mode: ArtifactMode) -> bool:+ if mode == "off":+ click.echo("Schema restore disabled; running migrations normally")+ return False++ if not is_database_empty(target_db):+ click.echo(f"Database {target_db} is not empty; running migrations normally")+ return False++ click.echo(f"Database {target_db} is empty; restoring latest compatible schema before migrations")+ download_latest_compatible_schema(base_branch=_effective_base_branch(None))++ # Re-check emptiness after the download. The artifact fetch takes seconds;+ # if a parallel process populated the DB in that window we must not DROP it.+ if not is_database_empty(target_db):+ click.echo(f"Database {target_db} is no longer empty; running migrations normally")+ return False++ restore_schema_dump(target_db=target_db, recreate=True, ensure_defaults=True)+ return True+++def _handle_restore_failure(exc: Exception, *, mode: ArtifactMode) -> None:+ if mode == "auto" and not isinstance(exc, SchemaRestoreCleanupFailed):+ click.echo(f"Schema restore skipped; falling back to migrations: {exc}", err=True)+ return+ raise click.ClickException(str(exc)) from exc+++def _effective_mode(mode: str | None) -> ArtifactMode:+ value = mode or os.environ.get("POSTHOG_SCHEMA_RESTORE_IN_DEV", "auto")+ if value not in {"off", "auto", "on"}:+ raise click.UsageError("mode must be one of: off, auto, on")+ return cast(ArtifactMode, value)+++def _create_postgres_backup() -> Path:+ backup_dir = REPO_ROOT / ".postgres-backups"+ backup_dir.mkdir(parents=True, exist_ok=True)+ backup_file = backup_dir / f"posthog_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.sql.gz"+ command = [*DOCKER_COMPOSE, "exec", "-T", "db", "pg_dumpall", "--clean", "-U", "posthog"]+ dump = subprocess.Popen(+ command,+ cwd=REPO_ROOT,+ env=os.environ.copy(),+ stdout=subprocess.PIPE,+ )+ assert dump.stdout is not None # stdout=PIPE guarantees this++ try:+ with open(backup_file, "wb") as raw_backup, gzip.GzipFile(fileobj=raw_backup, mode="wb") as compressed_backup:+ shutil.copyfileobj(dump.stdout, compressed_backup)+ except Exception:+ dump.kill()+ dump.wait()+ backup_file.unlink(missing_ok=True)+ raise+ finally:+ dump.stdout.close()++ returncode = dump.wait()+ if returncode != 0:+ backup_file.unlink(missing_ok=True)+ raise subprocess.CalledProcessError(returncode, command)++ click.echo(f"Backup saved to: {backup_file.relative_to(REPO_ROOT)}")+ return backup_file+++def _confirm_restore_schema(yes: bool) -> bool:+ if yes:+ return True++ click.echo()+ click.secho("Warning: this command may overwrite your local PostgreSQL schema.", fg="yellow", bold=True)+ click.echo("A backup will be created before restoring.")+ click.echo()+ if click.confirm("Are you sure you want to continue?", default=False):+ return True++ click.secho("Aborted.", fg="red")+ return False+++def _effective_base_branch(base_branch: str | None) -> str:+ return base_branch or os.environ.get("POSTHOG_SCHEMA_RESTORE_BASE_BRANCH") or DEFAULT_BASE_BRANCH+++# hogli's CompositeCommand wrapper forwards --yes/-y to every child step+# (tools/hogli/src/hogli/command_types.py). YAML-backed children silently+# accept it via the hogli registration wrapper; `click:` entries are loaded+# as-is, so each non-confirming command must declare a no-op --yes itself.+_hogli_yes_compat = click.option(+ "--yes",+ "-y",+ is_flag=True,+ expose_value=False,+ hidden=True,+ help="Compatibility flag; accepted when forwarded by composite hogli commands.",+)++[email protected](name="db:download-schema", help="Download the latest compatible pre-migrated schema artifact")+ "--base-branch",+ default=None,+ help="Source branch of the workflow run to pull artifacts from. "+ "Defaults to POSTHOG_SCHEMA_RESTORE_BASE_BRANCH or master.",+)+@_hogli_yes_compat+def db_download_schema(base_branch: str | None) -> None:+ try:+ download_latest_compatible_schema(base_branch=_effective_base_branch(base_branch))+ except Exception as exc:+ raise click.ClickException(str(exc)) from exc+++def _recreate_test_db() -> None:+ try:+ restore_schema_dump(target_db=os.environ.get("TARGET_DB", "test_posthog"), recreate=True, ensure_defaults=True)+ except Exception as exc:+ raise click.ClickException(str(exc)) from exc+++ name="db:restore-test-db", help="Restore a fresh test database from .postgres-backups/schema-latest.sql.gz"+)+@_hogli_yes_compat+def db_restore_test_db() -> None:+ _recreate_test_db()++[email protected](name="db:restore-schema-fresh", help="Alias for db:restore-test-db")+@_hogli_yes_compat+def db_restore_schema_fresh() -> None:+ _recreate_test_db()+++ name="db:restore-schema-if-fresh", help="Restore schema into an empty local dev database before migrations"+)+ "--mode",+ type=click.Choice(["off", "auto", "on"]),+ default=None,+ help="Restore mode. Defaults to POSTHOG_SCHEMA_RESTORE_IN_DEV or auto.",+)[email protected]("--target-db", default="posthog", show_default=True, help="Database to inspect and restore")+@_hogli_yes_compat+def db_restore_schema_if_fresh(mode: str | None, target_db: str) -> None:+ effective_mode = _effective_mode(mode)+ try:+ restore_schema_if_fresh(target_db=target_db, mode=effective_mode)+ except Exception as exc:+ _handle_restore_failure(exc, mode=effective_mode)+++ name="db:restore-schema", help="Fetch and restore the latest compatible schema into the local posthog database"+)[email protected]("--yes", "-y", is_flag=True, help="Skip confirmation prompt")+def db_restore_schema(yes: bool) -> None:+ if not _confirm_restore_schema(yes):+ return++ try:+ download_latest_compatible_schema(base_branch=_effective_base_branch(None))+ _create_postgres_backup()+ restore_schema_dump(target_db="posthog", recreate=False, ensure_defaults=False)+ _run([str(REPO_ROOT / "bin" / "migrate")])+ _ensure_migration_defaults("posthog")+ except Exception as exc:+ raise click.ClickException(str(exc)) from excdiff --git a/tools/hogli-commands/hogli_commands/tests/test_db_schema.py b/tools/hogli-commands/hogli_commands/tests/test_db_schema.pynew file mode 100644index 000000000000..ff43bfa5151d--- /dev/null+++ b/tools/hogli-commands/hogli_commands/tests/test_db_schema.py@@ -0,0 +1,361 @@+from __future__ import annotations++import gzip+from pathlib import Path+from typing import Any++import pytest++from click.testing import CliRunner+from hogli_commands import db_schema++runner = CliRunner()+++def _artifact(+ artifact_id: int,+ head_sha: str,+ created_at: str,+ *,+ expired: bool = False,+ size_in_bytes: int = db_schema.MIN_SCHEMA_ARTIFACT_BYTES + 1,+ name: str = db_schema.SCHEMA_ARTIFACT_NAME,+ head_branch: str = db_schema.DEFAULT_BASE_BRANCH,+) -> db_schema.SchemaArtifact:+ return db_schema.SchemaArtifact(+ id=artifact_id,+ name=name,+ expired=expired,+ size_in_bytes=size_in_bytes,+ archive_download_url=f"https://api.github.com/artifacts/{artifact_id}/zip",+ head_sha=head_sha,+ head_branch=head_branch,+ created_at=created_at,+ )+++def _write_schema(path: Path) -> None:+ with gzip.open(path, "wb") as schema:+ schema.write(b"SELECT 1;\n")+++ "name,content",+ [+ ("not-gzip", b"this is not gzip data"),+ ("empty", b""),+ ("partial-header", b"\x1f\x8b"),+ ],+)+def test_validate_gzip_rejects_corrupt_inputs(tmp_path: Path, name: str, content: bytes) -> None:+ path = tmp_path / f"{name}.sql.gz"+ path.write_bytes(content)+ with pytest.raises(db_schema.SchemaRestoreError):+ db_schema._validate_gzip(path)+++def test_validate_gzip_rejects_truncated_stream(tmp_path: Path) -> None:+ full = tmp_path / "good.sql.gz"+ _write_schema(full)+ truncated = tmp_path / "truncated.sql.gz"+ raw = full.read_bytes()+ truncated.write_bytes(raw[: len(raw) // 2])+ with pytest.raises(db_schema.SchemaRestoreError):+ db_schema._validate_gzip(truncated)+++def test_select_newest_compatible_artifact_returns_most_recent() -> None:+ artifacts = [+ _artifact(1, "older", "2026-01-01T00:00:00Z"),+ _artifact(2, "newer", "2026-01-02T00:00:00Z"),+ ]++ assert db_schema.select_newest_compatible_artifact(artifacts) == artifacts[1]+++ "artifact",+ [+ _artifact(1, "sha", "2026-01-01T00:00:00Z", expired=True),+ _artifact(1, "sha", "2026-01-01T00:00:00Z", size_in_bytes=100),+ _artifact(1, "", "2026-01-01T00:00:00Z"),+ _artifact(1, "sha", "2026-01-01T00:00:00Z", name="other"),+ _artifact(1, "sha", "2026-01-01T00:00:00Z", head_branch="some-pr-branch"),+ ],+)+def test_select_ignores_invalid_artifacts(artifact: db_schema.SchemaArtifact) -> None:+ assert db_schema.select_newest_compatible_artifact([artifact]) is None+++def test_select_honors_custom_base_branch() -> None:+ master_artifact = _artifact(1, "sha-a", "2026-01-01T00:00:00Z", head_branch="master")+ release_artifact = _artifact(2, "sha-b", "2026-01-02T00:00:00Z", head_branch="release-26.1")++ selected = db_schema.select_newest_compatible_artifact(+ [master_artifact, release_artifact],+ base_branch="release-26.1",+ )++ assert selected == release_artifact+++def test_download_diagnostics_on_no_compatible_artifact(monkeypatch: pytest.MonkeyPatch) -> None:+ artifacts = [+ _artifact(10, "pr-sha", "2026-01-01T00:00:00Z", head_branch="some-pr"),+ _artifact(11, "master-sha", "2026-01-02T00:00:00Z", head_branch="some-other-pr"),+ ]+ monkeypatch.setattr(db_schema, "_github_token", lambda: "token")+ monkeypatch.setattr(db_schema, "fetch_schema_artifacts", lambda **kwargs: artifacts)++ split_runner = CliRunner(mix_stderr=False)+ result = split_runner.invoke(db_schema.db_download_schema, [])++ assert result.exit_code != 0+ assert "Fetched 2 migrated-schema artifact(s)" in result.stderr+ assert "After name/expiry/size/branch filters: 0 candidate(s)" in result.stderr+++def test_effective_base_branch_prefers_env(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("POSTHOG_SCHEMA_RESTORE_BASE_BRANCH", "release-26.1")+ assert db_schema._effective_base_branch(None) == "release-26.1"+ assert db_schema._effective_base_branch("override") == "override"++ monkeypatch.delenv("POSTHOG_SCHEMA_RESTORE_BASE_BRANCH", raising=False)+ assert db_schema._effective_base_branch(None) == db_schema.DEFAULT_BASE_BRANCH+++ "mode,is_empty,expected_inspections",+ [+ ("off", True, []),+ ("auto", False, ["posthog"]),+ ],+)+def test_restore_schema_if_fresh_skips_without_download(+ mode: db_schema.ArtifactMode,+ is_empty: bool,+ expected_inspections: list[str],+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ inspections: list[str] = []++ def fake_is_database_empty(target_db: str) -> bool:+ inspections.append(target_db)+ return is_empty++ monkeypatch.setattr(db_schema, "is_database_empty", fake_is_database_empty)+ monkeypatch.setattr(+ db_schema,+ "download_latest_compatible_schema",+ lambda **kwargs: pytest.fail("download should not run"),+ )++ assert db_schema.restore_schema_if_fresh(target_db="posthog", mode=mode) is False+ assert inspections == expected_inspections+++def test_restore_schema_if_fresh_recreates_empty_db(monkeypatch: pytest.MonkeyPatch) -> None:+ restore_calls: list[dict[str, Any]] = []+ monkeypatch.setattr(db_schema, "is_database_empty", lambda target_db: True)+ monkeypatch.setattr(db_schema, "download_latest_compatible_schema", lambda **kwargs: None)+ monkeypatch.setattr(db_schema, "restore_schema_dump", lambda **kwargs: restore_calls.append(kwargs))++ assert db_schema.restore_schema_if_fresh(target_db="posthog", mode="auto") is True+ assert restore_calls == [{"target_db": "posthog", "recreate": True, "ensure_defaults": True}]+++def test_restore_schema_if_fresh_skips_when_db_populated_after_download(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """If another process writes to the DB during the artifact download, the+ post-download re-check must abort before DROP/CREATE."""+ empty_responses = iter([True, False])+ monkeypatch.setattr(db_schema, "is_database_empty", lambda target_db: next(empty_responses))+ monkeypatch.setattr(db_schema, "download_latest_compatible_schema", lambda **kwargs: None)+ monkeypatch.setattr(+ db_schema,+ "restore_schema_dump",+ lambda **kwargs: pytest.fail("restore must not run when DB stopped being empty"),+ )++ assert db_schema.restore_schema_if_fresh(target_db="posthog", mode="auto") is False+++def test_run_psql_with_gzip_input_uses_transactional_error_stopping(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ schema_path = tmp_path / "schema.sql.gz"+ _write_schema(schema_path)+ commands: list[list[str]] = []++ class FakeStdin:+ def __init__(self) -> None:+ self.data = b""++ def write(self, chunk: bytes) -> int:+ self.data += chunk+ return len(chunk)++ def close(self) -> None:+ pass++ class SuccessfulProcess:+ def __init__(self) -> None:+ self.stdin = FakeStdin()++ def wait(self) -> int:+ return 0++ def kill(self) -> None:+ pytest.fail("process should not be killed")++ def fake_popen(command: list[str], **kwargs: object) -> SuccessfulProcess:+ commands.append(command)+ return SuccessfulProcess()++ monkeypatch.setattr(db_schema.subprocess, "Popen", fake_popen)++ db_schema._run_psql_with_gzip_input(schema_path, "posthog")++ assert len(commands) == 1+ assert "-v" in commands[0]+ assert "ON_ERROR_STOP=1" in commands[0]+ assert "--single-transaction" in commands[0]+++def test_restore_schema_dump_recreate_drops_and_creates(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ schema_path = tmp_path / "schema.sql.gz"+ _write_schema(schema_path)+ commands: list[list[str]] = []+ restored: list[tuple[Path, str]] = []+ defaults: list[str] = []++ monkeypatch.setattr(db_schema, "_run", lambda command, env=None: commands.append(command))+ monkeypatch.setattr(+ db_schema,+ "_run_psql_with_gzip_input",+ lambda gzip_path, target_db: restored.append((gzip_path, target_db)),+ )+ monkeypatch.setattr(db_schema, "_ensure_migration_defaults", lambda target_db: defaults.append(target_db))++ db_schema.restore_schema_dump(target_db="test_posthog", recreate=True, schema_path=schema_path)++ assert any("DROP DATABASE IF EXISTS test_posthog;" in command for call in commands for command in call)+ assert any("CREATE DATABASE test_posthog;" in command for call in commands for command in call)+ assert restored == [(schema_path, "test_posthog")]+ assert defaults == ["test_posthog"]+++def test_restore_schema_dump_recreate_cleans_up_after_failure(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ schema_path = tmp_path / "schema.sql.gz"+ _write_schema(schema_path)+ commands: list[list[str]] = []++ monkeypatch.setattr(db_schema, "_run", lambda command, env=None: commands.append(command))+ monkeypatch.setattr(+ db_schema,+ "_run_psql_with_gzip_input",+ lambda gzip_path, target_db: (_ for _ in ()).throw(db_schema.SchemaRestoreError("restore failed")),+ )+ monkeypatch.setattr(+ db_schema,+ "_ensure_migration_defaults",+ lambda target_db: pytest.fail("defaults should not run after restore failure"),+ )++ with pytest.raises(db_schema.SchemaRestoreError, match="restore failed"):+ db_schema.restore_schema_dump(target_db="test_posthog", recreate=True, schema_path=schema_path)++ admin_sql = [command[-1] for command in commands]+ assert admin_sql == [+ "DROP DATABASE IF EXISTS test_posthog;",+ "CREATE DATABASE test_posthog;",+ "DROP DATABASE IF EXISTS test_posthog;",+ "CREATE DATABASE test_posthog;",+ ]+++def test_restore_schema_dump_without_recreate_does_not_drop(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ schema_path = tmp_path / "schema.sql.gz"+ _write_schema(schema_path)+ commands: list[list[str]] = []++ monkeypatch.setattr(db_schema, "_run", lambda command, env=None: commands.append(command))+ monkeypatch.setattr(db_schema, "_run_psql_with_gzip_input", lambda gzip_path, target_db: None)+ monkeypatch.setattr(db_schema, "_ensure_migration_defaults", lambda target_db: None)++ db_schema.restore_schema_dump(target_db="posthog", recreate=False, schema_path=schema_path)++ assert not any("DROP DATABASE" in command for call in commands for command in call)+ assert not any("CREATE DATABASE" in command for call in commands for command in call)+++ "mode,expected_exit,expected_output",+ [+ ("auto", 0, "falling back to migrations"),+ ("on", 1, "no compatible artifact"),+ ],+)+def test_restore_schema_if_fresh_handles_unavailable_artifact(+ mode: str, expected_exit: int, expected_output: str, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(db_schema, "is_database_empty", lambda target_db: True)+ monkeypatch.setattr(+ db_schema,+ "download_latest_compatible_schema",+ lambda **kwargs: (_ for _ in ()).throw(db_schema.SchemaRestoreUnavailable("no compatible artifact")),+ )++ result = runner.invoke(db_schema.db_restore_schema_if_fresh, [f"--mode={mode}"])++ assert result.exit_code == expected_exit+ assert expected_output in result.output+++def test_restore_schema_if_fresh_auto_does_not_fallback_when_cleanup_failed(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ db_schema,+ "restore_schema_if_fresh",+ lambda **kwargs: (_ for _ in ()).throw(db_schema.SchemaRestoreCleanupFailed("cleanup failed")),+ )++ result = runner.invoke(db_schema.db_restore_schema_if_fresh, ["--mode=auto"])++ assert result.exit_code == 1+ assert "cleanup failed" in result.output+++def test_restore_schema_fresh_recreates_target_db(monkeypatch: pytest.MonkeyPatch) -> None:+ calls: list[dict[str, Any]] = []+ monkeypatch.setenv("TARGET_DB", "posthog_e2e_test")+ monkeypatch.setattr(db_schema, "restore_schema_dump", lambda **kwargs: calls.append(kwargs))++ result = runner.invoke(db_schema.db_restore_schema_fresh)++ assert result.exit_code == 0+ assert calls == [{"target_db": "posthog_e2e_test", "recreate": True, "ensure_defaults": True}]+++ "command",+ [+ db_schema.db_download_schema,+ db_schema.db_restore_test_db,+ db_schema.db_restore_schema_fresh,+ db_schema.db_restore_schema_if_fresh,+ ],+ ids=lambda cmd: cmd.name,+)+def test_converted_commands_accept_forwarded_yes_flag(command: Any, monkeypatch: pytest.MonkeyPatch) -> None:+ """hogli composite commands forward --yes to children; converted click+ commands must silently accept it (regression for db:prime-test-db --yes)."""+ monkeypatch.setattr(db_schema, "download_latest_compatible_schema", lambda **kwargs: None)+ monkeypatch.setattr(db_schema, "restore_schema_dump", lambda **kwargs: None)+ monkeypatch.setattr(db_schema, "restore_schema_if_fresh", lambda **kwargs: None)++ for flag in ("--yes", "-y"):+ result = runner.invoke(command, [flag])+ assert result.exit_code == 0, f"{command.name} {flag} failed: {result.output}"