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.

feat(growth): add local project bootstrapper from S3 dump (#66022)

Fernando Gomese88cd506b66d
diff --git a/hogli.yaml b/hogli.yaml
index 592e55864ab7..32963d34108a 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -256,6 +256,13 @@ core:
services:
- postgresql
- clickhouse
+ dev:bootstrap-project:
+ cmd: python manage.py bootstrap_local_project
+ description: Bootstrap a local project from an S3 events/persons dump (batch-export format)
+ services:
+ - postgresql
+ - clickhouse
+ - django
dev:sync-flags:
cmd: python manage.py sync_feature_flags
description: Sync feature flags from configuration
diff --git a/posthog/local_bootstrap/__init__.py b/posthog/local_bootstrap/__init__.py
new file mode 100644
index 000000000000..c1b92cd0c2d0
--- /dev/null
+++ b/posthog/local_bootstrap/__init__.py
@@ -0,0 +1,32 @@
+"""Bootstrap a local PostHog project from an S3 dump of the events and persons tables.
+
+The dumps are produced by the PostHog S3 batch export feature (Parquet/JSONLines, optionally
+compressed). See ``posthog/management/commands/bootstrap_local_project.py`` for the CLI entry point.
+"""
+
+from posthog.local_bootstrap.config import (
+ BootstrapConfig,
+ BootstrapConfigError,
+ DiscoveredFile,
+ S3Location,
+ TableImportConfig,
+ TablePlan,
+ TableResult,
+)
+from posthog.local_bootstrap.importer import BootstrapReport, Progress, run_bootstrap
+from posthog.local_bootstrap.source import iter_table_rows, list_files
+
+__all__ = [
+ "BootstrapConfig",
+ "BootstrapConfigError",
+ "BootstrapReport",
+ "DiscoveredFile",
+ "Progress",
+ "S3Location",
+ "TableImportConfig",
+ "TablePlan",
+ "TableResult",
+ "iter_table_rows",
+ "list_files",
+ "run_bootstrap",
+]
diff --git a/posthog/local_bootstrap/config.py b/posthog/local_bootstrap/config.py
new file mode 100644
index 000000000000..f8bef2460cbc
--- /dev/null
+++ b/posthog/local_bootstrap/config.py
@@ -0,0 +1,115 @@
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Literal
+
+# Mirrors the file formats and compression methods supported by the PostHog S3 batch export
+# feature (see products/batch_exports/.../destinations/constants.py). Kept as a local copy so the
+# bootstrapper has no import-time dependency on the Temporal batch-export package.
+SUPPORTED_FILE_FORMATS = ("Parquet", "JSONLines")
+
+S3_SUPPORTED_COMPRESSIONS: dict[str, tuple[str, ...]] = {
+ "Parquet": ("zstd", "lz4", "snappy", "gzip", "brotli"),
+ "JSONLines": ("gzip", "brotli"),
+}
+
+# Extension a file of a given format/compression carries in the export bucket.
+FILE_FORMAT_EXTENSIONS = {"Parquet": "parquet", "JSONLines": "jsonl"}
+COMPRESSION_EXTENSIONS = {"gzip": "gz", "snappy": "sz", "brotli": "br", "zstd": "zst", "lz4": "lz4"}
+
+Table = Literal["events", "persons"]
+
+
+class BootstrapConfigError(Exception):
+ """Raised when the import configuration is invalid (bad format, missing bucket, etc.)."""
+
+
+@dataclass
+class S3Location:
+ """Where a dump lives and how to authenticate against it."""
+
+ bucket: str
+ prefix: str = ""
+ access_key_id: str | None = None
+ secret_access_key: str | None = None
+ region: str | None = None
+ # Custom S3-compatible endpoint (MinIO, SeaweedFS, Cloudflare R2, ...). None uses AWS.
+ endpoint_url: str | None = None
+
+
+@dataclass
+class TableImportConfig:
+ """Everything needed to import one table from one location."""
+
+ table: Table
+ location: S3Location
+ file_format: str = "Parquet"
+ compression: str | None = "zstd"
+
+ def validate(self) -> None:
+ if self.file_format not in SUPPORTED_FILE_FORMATS:
+ raise BootstrapConfigError(
+ f"Unsupported file format {self.file_format!r}. Supported: {', '.join(SUPPORTED_FILE_FORMATS)}"
+ )
+ if self.compression is not None and self.compression not in S3_SUPPORTED_COMPRESSIONS[self.file_format]:
+ allowed = ", ".join(S3_SUPPORTED_COMPRESSIONS[self.file_format])
+ raise BootstrapConfigError(
+ f"Compression {self.compression!r} is not supported for {self.file_format} "
+ f"(supported: {allowed}, or none)"
+ )
+ if not self.location.bucket:
+ raise BootstrapConfigError(f"A bucket is required for the {self.table} table")
+
+
+@dataclass
+class BootstrapConfig:
+ """Full configuration for a bootstrap run."""
+
+ project_name: str
+ email: str = ""
+ password: str = ""
+ tables: list[TableImportConfig] = field(default_factory=list)
+ batch_size: int = 10_000
+
+ def validate(self, require_identity: bool = True) -> None:
+ if require_identity and not self.project_name:
+ raise BootstrapConfigError("A project name is required")
+ if require_identity and not self.email:
+ raise BootstrapConfigError("An email is required")
+ if not self.tables:
+ raise BootstrapConfigError("At least one of the events or persons tables must be configured")
+ for table in self.tables:
+ table.validate()
+
+
+@dataclass
+class DiscoveredFile:
+ """A single object found in the export bucket that will be imported."""
+
+ key: str
+ size_bytes: int
+
+
+@dataclass
+class TablePlan:
+ """The set of files discovered for a table, ready to be shown to the user before import."""
+
+ config: TableImportConfig
+ files: list[DiscoveredFile]
+
+ @property
+ def file_count(self) -> int:
+ return len(self.files)
+
+ @property
+ def total_size_bytes(self) -> int:
+ return sum(f.size_bytes for f in self.files)
+
+
+@dataclass
+class TableResult:
+ """The outcome of importing one table."""
+
+ table: Table
+ rows_imported: int
+ distinct_ids_imported: int = 0
diff --git a/posthog/local_bootstrap/importer.py b/posthog/local_bootstrap/importer.py
new file mode 100644
index 000000000000..46869c4d7462
--- /dev/null
+++ b/posthog/local_bootstrap/importer.py
@@ -0,0 +1,388 @@
+from __future__ import annotations
+
+import json
+import uuid
+from collections.abc import Callable
+from contextlib import AbstractContextManager
+from dataclasses import dataclass, field
+from datetime import UTC, datetime
+from typing import Any
+
+from dateutil.parser import isoparse
+
+from posthog.clickhouse.client import sync_execute
+from posthog.clickhouse.query_tagging import Feature, Product, tags_context
+from posthog.local_bootstrap.config import (
+ BootstrapConfig,
+ DiscoveredFile,
+ Table,
+ TableImportConfig,
+ TablePlan,
+ TableResult,
+)
+from posthog.local_bootstrap.source import iter_table_rows
+from posthog.models import Organization, OrganizationMembership, Person, PersonDistinctId, Team, User
+from posthog.models.event.sql import EVENTS_DATA_TABLE
+
+ZERO_UUID = "00000000-0000-0000-0000-000000000000"
+ZERO_DT = datetime(1970, 1, 1)
+
+# Columns we write directly into sharded_events (mirrors INSERT_EVENT_SQL minus computed columns).
+_EVENT_COLUMNS = [
+ "uuid",
+ "event",
+ "properties",
+ "timestamp",
+ "team_id",
+ "distinct_id",
+ "elements_chain",
+ "person_id",
+ "person_properties",
+ "person_created_at",
+ "group0_properties",
+ "group1_properties",
+ "group2_properties",
+ "group3_properties",
+ "group4_properties",
+ "group0_created_at",
+ "group1_created_at",
+ "group2_created_at",
+ "group3_created_at",
+ "group4_created_at",
+ "person_mode",
+ "created_at",
+ "_timestamp",
+ "_offset",
+]
+
+_PERSON_COLUMNS = [
+ "id",
+ "created_at",
+ "team_id",
+ "properties",
+ "is_identified",
+ "_timestamp",
+ "_offset",
+ "is_deleted",
+ "version",
+ "last_seen_at",
+]
+
+_PERSON_DISTINCT_ID_COLUMNS = [
+ "distinct_id",
+ "person_id",
+ "team_id",
+ "is_deleted",
+ "version",
+ "_timestamp",
+ "_offset",
+ "_partition",
+]
+
+
+@dataclass
+class Progress:
+ """Optional progress callbacks. ``on_file`` fires before each file is read; ``on_rows`` fires
+ after each batch with the running total for the table."""
+
+ on_file: Callable[[Table, DiscoveredFile, int, int], None] | None = None
+ on_rows: Callable[[Table, int], None] | None = None
+
+ def file(self, table: Table, discovered: DiscoveredFile, index: int, total: int) -> None:
+ if self.on_file is not None:
+ self.on_file(table, discovered, index, total)
+
+ def rows(self, table: Table, total: int) -> None:
+ if self.on_rows is not None:
+ self.on_rows(table, total)
+
+
+@dataclass
+class BootstrapReport:
+ team_id: int
+ project_name: str
+ email: str
+ created_user: bool
+ results: list[TableResult] = field(default_factory=list)
+
+ def rows_for(self, table: Table) -> int:
+ return sum(r.rows_imported for r in self.results if r.table == table)
+
+
+def _ch_tags(team_id: int) -> AbstractContextManager[None]:
+ return tags_context(product=Product.GROWTH, feature=Feature.MANAGEMENT_COMMAND, team_id=team_id)
+
+
+def _aware_utc(value: Any, default: datetime) -> datetime:
+ if value is None:
+ value = default
+ if isinstance(value, int | float):
+ # Batch-export persons store created_at as epoch seconds (uint32), not a parquet timestamp.
+ return datetime.fromtimestamp(value, tz=UTC)
+ if isinstance(value, str):
+ value = isoparse(value)
+ if value.tzinfo is None:
+ return value.replace(tzinfo=UTC)
+ return value.astimezone(UTC)
+
+
+def _naive_utc(value: Any, default: datetime) -> datetime:
+ return _aware_utc(value, default).replace(tzinfo=None)
+
+
+def ensure_project(config: BootstrapConfig) -> tuple[Team, User, bool]:
+ """Create the local project. If the email already exists, attach a fresh org+team to that user;
+ otherwise bootstrap a brand-new org, user (password from config), and team. Returns
+ ``(team, user, created_user)``."""
+ existing = User.objects.filter(email=config.email).first()
+ if existing is None:
+ _organization, team, user = User.objects.bootstrap(
+ organization_name=config.project_name,
+ email=config.email,
+ password=config.password,
+ team_fields={"name": config.project_name},
+ )
+ return team, user, True
+
+ organization = Organization.objects.create(name=config.project_name)
+ team = Team.objects.create_with_data(initiating_user=existing, organization=organization, name=config.project_name)
+ existing.join(organization=organization, level=OrganizationMembership.Level.OWNER)
+ return team, existing, False
+
+
+def _event_row_to_ch(row: dict[str, Any], team_id: int, now: datetime) -> dict[str, Any]:
+ return {
+ "uuid": str(row.get("uuid") or uuid.uuid4()),
+ "event": row.get("event") or "",
+ "properties": row.get("properties") or "",
+ "timestamp": _naive_utc(row.get("timestamp"), now),
+ "team_id": team_id,
+ "distinct_id": str(row.get("distinct_id") or ""),
+ "elements_chain": row.get("elements_chain") or "",
+ "person_id": str(row.get("person_id") or ZERO_UUID),
+ "person_properties": row.get("person_properties") or "",
+ "person_created_at": ZERO_DT,
+ "group0_properties": "",
+ "group1_properties": "",
+ "group2_properties": "",
+ "group3_properties": "",
+ "group4_properties": "",
+ "group0_created_at": ZERO_DT,
+ "group1_created_at": ZERO_DT,
+ "group2_created_at": ZERO_DT,
+ "group3_created_at": ZERO_DT,
+ "group4_created_at": ZERO_DT,
+ "person_mode": "full",
+ "created_at": _naive_utc(row.get("created_at"), now),
+ "_timestamp": now,
+ "_offset": 0,
+ }
+
+
+def _insert_events_batch(rows: list[dict[str, Any]], team_id: int) -> None:
+ sql = f"INSERT INTO {EVENTS_DATA_TABLE()} ({', '.join(_EVENT_COLUMNS)}) VALUES"
+ with _ch_tags(team_id):
+ sync_execute(sql, rows)
+
+
+def import_events(
+ team: Team, config: TableImportConfig, files: list[DiscoveredFile], batch_size: int, progress: Progress
+) -> TableResult:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ total = 0
+ batch: list[dict[str, Any]] = []
+
+ def on_file_start(discovered: DiscoveredFile, index: int) -> None:
+ progress.file("events", discovered, index, len(files))
+
+ for row in iter_table_rows(config, files, batch_size, on_file_start=on_file_start):
+ batch.append(_event_row_to_ch(row, team.id, now))
+ if len(batch) >= batch_size:
+ _insert_events_batch(batch, team.id)
+ total += len(batch)
+ batch = []
+ progress.rows("events", total)
+
+ if batch:
+ _insert_events_batch(batch, team.id)
+ total += len(batch)
+ progress.rows("events", total)
+
+ return TableResult(table="events", rows_imported=total)
+
+
+@dataclass
+class _PersonAccumulator:
+ properties: str
+ version: int
+ created_at: datetime
+ is_deleted: bool
+ distinct_ids: dict[str, int]
+
+
+def _accumulate_persons(
+ config: TableImportConfig, files: list[DiscoveredFile], batch_size: int, progress: Progress
+) -> dict[str, _PersonAccumulator]:
+ """Collapse the denormalized (person, distinct_id) export rows into one entry per person.
+ Persons must be deduped across the whole dump, so this holds them in memory — fine for the
+ person-sized slice of a project, which is far smaller than the events table."""
+ now = datetime.now(UTC)
+ persons: dict[str, _PersonAccumulator] = {}
+ read = 0
+
+ def on_file_start(discovered: DiscoveredFile, index: int) -> None:
+ progress.file("persons", discovered, index, len(files))
+
+ for row in iter_table_rows(config, files, batch_size, on_file_start=on_file_start):
+ read += 1
+ person_id = str(row.get("person_id") or "")
+ if not person_id or person_id == ZERO_UUID:
+ continue
+ is_deleted = bool(row.get("is_deleted"))
+ version = int(row.get("person_version") or 0)
+ entry = persons.get(person_id)
+ if entry is None:
+ entry = _PersonAccumulator(
+ properties=row.get("properties") or "{}",
+ version=version,
+ created_at=_aware_utc(row.get("created_at"), now),
+ is_deleted=is_deleted,
+ distinct_ids={},
+ )
+ persons[person_id] = entry
+ else:
+ entry.version = max(entry.version, version)
+ entry.is_deleted = entry.is_deleted or is_deleted
+
+ distinct_id = row.get("distinct_id")
+ if distinct_id:
+ did_version = int(row.get("person_distinct_id_version") or 0)
+ entry.distinct_ids[distinct_id] = max(entry.distinct_ids.get(distinct_id, 0), did_version)
+
+ if read % batch_size == 0:
+ progress.rows("persons", read)
+
+ return persons
+
+
+def _write_persons_to_postgres(team: Team, persons: dict[str, _PersonAccumulator]) -> list[Person]:
+ person_objs: list[Person] = []
+ desired_created_at: list[datetime] = []
+ for person_id, entry in persons.items():
+ try:
+ properties = json.loads(entry.properties)
+ except (json.JSONDecodeError, TypeError):
+ properties = {}
+ person_objs.append(
+ Person( # nosemgrep: no-direct-persons-db-orm
+ team=team,
+ uuid=uuid.UUID(person_id),
+ properties=properties,
+ is_identified=True,
+ version=entry.version,
+ )
+ )
+ desired_created_at.append(entry.created_at)
+
+ # created_at is auto_now_add, so bulk_create stamps "now"; restore the dump's value afterwards.
+ Person.objects.bulk_create(person_objs, batch_size=1000) # nosemgrep: no-direct-persons-db-orm
+ for person, created_at in zip(person_objs, desired_created_at):
+ person.created_at = created_at
+ Person.objects.bulk_update(person_objs, ["created_at"], batch_size=1000) # nosemgrep: no-direct-persons-db-orm
+
+ distinct_objs: list[PersonDistinctId] = []
+ for person, entry in zip(person_objs, persons.values()):
+ for distinct_id, version in entry.distinct_ids.items():
+ distinct_objs.append(
+ PersonDistinctId( # nosemgrep: no-direct-persons-db-orm
+ team=team, person=person, distinct_id=distinct_id, version=version
+ )
+ )
+ PersonDistinctId.objects.bulk_create(distinct_objs, batch_size=1000) # nosemgrep: no-direct-persons-db-orm
+ return person_objs
+
+
+def _write_persons_to_clickhouse(team: Team, persons: dict[str, _PersonAccumulator]) -> None:
+ now = datetime.now(UTC).replace(tzinfo=None)
+ person_rows: list[dict[str, Any]] = []
+ distinct_rows: list[dict[str, Any]] = []
+ for person_id, entry in persons.items():
+ created_at = entry.created_at.replace(tzinfo=None)
+ person_rows.append(
+ {
+ "id": person_id,
+ "created_at": created_at,
+ "team_id": team.id,
+ "properties": entry.properties,
+ "is_identified": 1,
+ "_timestamp": now,
+ "_offset": 0,
+ "is_deleted": 0,
+ "version": entry.version,
+ "last_seen_at": created_at,
+ }
+ )
+ for distinct_id, version in entry.distinct_ids.items():
+ distinct_rows.append(
+ {
+ "distinct_id": distinct_id,
+ "person_id": person_id,
+ "team_id": team.id,
+ "is_deleted": 0,
+ "version": version,
+ "_timestamp": now,
+ "_offset": 0,
+ "_partition": 0,
+ }
+ )
+
+ with _ch_tags(team.id):
+ if person_rows:
+ sync_execute(f"INSERT INTO person ({', '.join(_PERSON_COLUMNS)}) VALUES", person_rows)
+ if distinct_rows:
+ sync_execute(
+ f"INSERT INTO person_distinct_id2 ({', '.join(_PERSON_DISTINCT_ID_COLUMNS)}) VALUES", distinct_rows
+ )
+
+
+def import_persons(
+ team: Team, config: TableImportConfig, files: list[DiscoveredFile], batch_size: int, progress: Progress
+) -> TableResult:
+ accumulated = _accumulate_persons(config, files, batch_size, progress)
+ live = {pid: entry for pid, entry in accumulated.items() if not entry.is_deleted}
+
+ _write_persons_to_postgres(team, live)
+ _write_persons_to_clickhouse(team, live)
+
+ distinct_ids = sum(len(entry.distinct_ids) for entry in live.values())
+ progress.rows("persons", len(live))
+ return TableResult(table="persons", rows_imported=len(live), distinct_ids_imported=distinct_ids)
+
+
+def run_bootstrap(
+ config: BootstrapConfig,
+ plans: list[TablePlan],
+ progress: Progress | None = None,
+ team_id: int | None = None,
+) -> BootstrapReport:
+ config.validate(require_identity=team_id is None)
+ progress = progress or Progress()
+
+ if team_id is not None:
+ team = Team.objects.get(id=team_id)
+ created_user = False
+ project_name = team.name
+ email = config.email or ""
+ else:
+ team, _user, created_user = ensure_project(config)
+ project_name = config.project_name
+ email = config.email
+
+ report = BootstrapReport(team_id=team.id, project_name=project_name, email=email, created_user=created_user)
+ for plan in plans:
+ if plan.config.table == "events":
+ report.results.append(import_events(team, plan.config, plan.files, config.batch_size, progress))
+ else:
+ report.results.append(import_persons(team, plan.config, plan.files, config.batch_size, progress))
+
+ return report
diff --git a/posthog/local_bootstrap/source.py b/posthog/local_bootstrap/source.py
new file mode 100644
index 000000000000..65697fe6eacd
--- /dev/null
+++ b/posthog/local_bootstrap/source.py
@@ -0,0 +1,126 @@
+from __future__ import annotations
+
+import os
+import gzip
+import json
+import tempfile
+import contextlib
+from collections.abc import Callable, Iterator
+from typing import IO, Any
+
+import boto3
+import pyarrow.parquet as pq
+
+from posthog.local_bootstrap.config import (
+ COMPRESSION_EXTENSIONS,
+ FILE_FORMAT_EXTENSIONS,
+ BootstrapConfigError,
+ DiscoveredFile,
+ S3Location,
+ TableImportConfig,
+)
+
+
+# boto3.client("s3") is left untyped on purpose: mypy and ty resolve it to different stub packages
+# (mypy_boto3_s3 vs types_boto3_s3), so a concrete S3Client annotation can't satisfy both checkers.
+def build_s3_client(location: S3Location):
+ """Build a boto3 S3 client for a location. Credentials fall back to the ambient AWS config
+ (env vars, instance profile) when not supplied, so the same code works against AWS and
+ S3-compatible stores like MinIO/SeaweedFS via ``endpoint_url``."""
+ return boto3.client(
+ "s3",
+ aws_access_key_id=location.access_key_id or None,
+ aws_secret_access_key=location.secret_access_key or None,
+ region_name=location.region or None,
+ endpoint_url=location.endpoint_url or None,
+ )
+
+
+def _matches_format(key: str, file_format: str) -> bool:
+ """A key belongs to a format if it carries that format's extension, optionally followed by a
+ compression extension (e.g. ``.parquet`` or ``.parquet.zst``). Manifest files are excluded."""
+ if key.endswith("/") or key.endswith("_manifest.json"):
+ return False
+ format_ext = FILE_FORMAT_EXTENSIONS[file_format]
+ suffixes = {f".{format_ext}"} | {f".{format_ext}.{c}" for c in COMPRESSION_EXTENSIONS.values()}
+ return any(key.endswith(suffix) for suffix in suffixes)
+
+
+def list_files(config: TableImportConfig) -> list[DiscoveredFile]:
+ """List every object under the configured prefix that matches the table's file format."""
+ client = build_s3_client(config.location)
+ paginator = client.get_paginator("list_objects_v2")
+ files: list[DiscoveredFile] = []
+ for page in paginator.paginate(Bucket=config.location.bucket, Prefix=config.location.prefix):
+ for obj in page.get("Contents", []):
+ key = obj["Key"]
+ if _matches_format(key, config.file_format):
+ files.append(DiscoveredFile(key=key, size_bytes=obj.get("Size", 0)))
+ files.sort(key=lambda f: f.key)
+ return files
+
+
+def _download_to_temp(client, bucket: str, key: str) -> Iterator[str]:
+ """Download an object to a temp file and yield its path, removing it afterwards. Reading from a
+ real file lets pyarrow stream row groups instead of buffering the whole object in memory."""
+ suffix = os.path.splitext(key)[1] or ".tmp"
+ fd, path = tempfile.mkstemp(suffix=suffix, prefix="ph-bootstrap-")
+ os.close(fd)
+ try:
+ client.download_file(bucket, key, path)
+ yield path
+ finally:
+ with contextlib.suppress(FileNotFoundError):
+ os.remove(path)
+
+
+def _iter_parquet_rows(path: str, batch_size: int) -> Iterator[dict[str, Any]]:
+ parquet_file = pq.ParquetFile(path)
+ for batch in parquet_file.iter_batches(batch_size=batch_size):
+ yield from batch.to_pylist()
+
+
+def _open_maybe_compressed(path: str, key: str, compression: str | None) -> IO[str]:
+ """Open a (possibly compression-wrapped) text file for JSONLines reading. Parquet handles its
+ own codec internally; this outer decompression only applies to JSONLines dumps."""
+ if key.endswith(".gz") or compression == "gzip":
+ return gzip.open(path, "rt", encoding="utf-8")
+ if key.endswith(".br") or compression == "brotli":
+ import brotli # noqa: PLC0415 — optional dep, only needed for brotli-compressed JSONLines
+
+ with open(path, "rb") as compressed:
+ data = brotli.decompress(compressed.read()).decode("utf-8")
+ import io # noqa: PLC0415
+
+ return io.StringIO(data)
+ return open(path, encoding="utf-8")
+
+
+def _iter_jsonl_rows(path: str, key: str, compression: str | None) -> Iterator[dict[str, Any]]:
+ with _open_maybe_compressed(path, key, compression) as handle:
+ for line in handle:
+ line = line.strip()
+ if line:
+ yield json.loads(line)
+
+
+def iter_table_rows(
+ config: TableImportConfig,
+ files: list[DiscoveredFile],
+ batch_size: int,
+ on_file_start: Callable[[DiscoveredFile, int], None] | None = None,
+) -> Iterator[dict[str, Any]]:
+ """Yield every row across all of a table's files as plain dicts, downloading one file at a
+ time. ``on_file_start(file, index)`` is called before each file so callers can report progress."""
+ client = build_s3_client(config.location)
+ for index, discovered in enumerate(files):
+ if on_file_start is not None:
+ on_file_start(discovered, index)
+ with _download_to_temp(client, config.location.bucket, discovered.key) as path:
+ if config.file_format == "Parquet":
+ yield from _iter_parquet_rows(path, batch_size)
+ elif config.file_format == "JSONLines":
+ yield from _iter_jsonl_rows(path, discovered.key, config.compression)
+ else: # pragma: no cover - guarded by config.validate()
+ raise BootstrapConfigError(f"Cannot read file format {config.file_format!r}")
diff --git a/posthog/local_bootstrap/test_local_bootstrap.py b/posthog/local_bootstrap/test_local_bootstrap.py
new file mode 100644
index 000000000000..9dfc98a98761
--- /dev/null
+++ b/posthog/local_bootstrap/test_local_bootstrap.py
@@ -0,0 +1,143 @@
+from datetime import UTC, datetime
+
+import pytest
+
+from parameterized import parameterized
+
+from posthog.local_bootstrap.config import BootstrapConfig, BootstrapConfigError, S3Location, TableImportConfig
+from posthog.local_bootstrap.importer import ZERO_UUID, Progress, _accumulate_persons, _event_row_to_ch
+from posthog.local_bootstrap.source import _matches_format
+
+
+def _events_config() -> TableImportConfig:
+ return TableImportConfig(
+ table="events", location=S3Location(bucket="dump"), file_format="Parquet", compression="zstd"
+ )
+
+
+class TestConfigValidation:
+ @parameterized.expand(
+ [
+ ("bad_format", "Avro", "zstd"),
+ ("bad_parquet_compression", "Parquet", "snappy_typo"),
+ ("jsonl_rejects_zstd", "JSONLines", "zstd"), # zstd is parquet-only, like the export feature
+ ]
+ )
+ def test_rejects_unsupported_format_or_compression(self, _name, file_format, compression):
+ config = TableImportConfig(
+ table="events", location=S3Location(bucket="dump"), file_format=file_format, compression=compression
+ )
+ with pytest.raises(BootstrapConfigError):
+ config.validate()
+
+ def test_rejects_missing_bucket(self):
+ with pytest.raises(BootstrapConfigError):
+ TableImportConfig(table="events", location=S3Location(bucket="")).validate()
+
+ def test_accepts_parquet_zstd_and_no_compression(self):
+ TableImportConfig(
+ table="events", location=S3Location(bucket="d"), file_format="Parquet", compression="zstd"
+ ).validate()
+ TableImportConfig(
+ table="persons", location=S3Location(bucket="d"), file_format="JSONLines", compression=None
+ ).validate()
+
+ def test_bootstrap_config_requires_at_least_one_table(self):
+ with pytest.raises(BootstrapConfigError):
+ BootstrapConfig(project_name="p", email="[email protected]", tables=[]).validate()
+
+
+class TestMatchesFormat:
+ @parameterized.expand(
+ [
+ ("plain_parquet", "exp/2024-01-01-2024-01-02.parquet", "Parquet", True),
+ ("zstd_parquet", "exp/2024-01-01-2024-01-02-0.parquet.zst", "Parquet", True),
+ ("gzip_parquet", "exp/chunk.parquet.gz", "Parquet", True),
+ ("manifest_excluded", "exp/2024-01-01-2024-01-02_manifest.json", "Parquet", False),
+ ("directory_excluded", "exp/", "Parquet", False),
+ ("wrong_format", "exp/chunk.jsonl", "Parquet", False),
+ ("jsonl_gzip", "exp/chunk.jsonl.gz", "JSONLines", True),
+ ]
+ )
+ def test_matches_format(self, _name, key, file_format, expected):
+ assert _matches_format(key, file_format) is expected
+
+
+class TestEventRowMapping:
+ def test_maps_all_clickhouse_columns_with_defaults(self):
+ from posthog.local_bootstrap.importer import _EVENT_COLUMNS
+
+ row = {
+ "uuid": "11111111-1111-1111-1111-111111111111",
+ "event": "$pageview",
+ "timestamp": "2024-01-01T00:00:00+00:00",
+ }
+ mapped = _event_row_to_ch(row, team_id=42, now=datetime(2024, 1, 1))
+
+ # Every column the INSERT lists must be present, or the block insert fails at runtime.
+ assert set(mapped.keys()) == set(_EVENT_COLUMNS)
+ assert mapped["team_id"] == 42
+ # Missing person_id must fall back to the zero UUID, not "" (which the UUID column rejects).
+ assert mapped["person_id"] == ZERO_UUID
+ assert mapped["person_mode"] == "full"
+
+ def test_coerces_null_properties_to_empty_string(self):
+ row = {"uuid": "1" * 8 + "-1111-1111-1111-111111111111", "properties": None, "person_properties": None}
+ mapped = _event_row_to_ch(row, team_id=1, now=datetime(2024, 1, 1))
+ assert mapped["properties"] == ""
+ assert mapped["person_properties"] == ""
+
+
+class TestAccumulatePersons:
+ def _run(self, monkeypatch, rows):
+ monkeypatch.setattr(
+ "posthog.local_bootstrap.importer.iter_table_rows",
+ lambda config, files, batch_size, on_file_start=None: iter(rows),
+ )
+ return _accumulate_persons(_events_config(), files=[], batch_size=1000, progress=Progress())
+
+ def test_collapses_multiple_distinct_ids_and_maxes_versions(self, monkeypatch):
+ pid = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ rows = [
+ {
+ "person_id": pid,
+ "distinct_id": "d1",
+ "properties": '{"a":1}',
+ "person_version": 0,
+ "person_distinct_id_version": 1,
+ "created_at": "2024-01-01T00:00:00+00:00",
+ },
+ {
+ "person_id": pid,
+ "distinct_id": "d2",
+ "properties": '{"a":1}',
+ "person_version": 3,
+ "person_distinct_id_version": 0,
+ "created_at": "2024-01-01T00:00:00+00:00",
+ },
+ ]
+ persons = self._run(monkeypatch, rows)
+ assert set(persons.keys()) == {pid}
+ assert persons[pid].version == 3
+ assert persons[pid].distinct_ids == {"d1": 1, "d2": 0}
+
+ def test_skips_rows_without_a_real_person_id(self, monkeypatch):
+ rows = [
+ {"person_id": "", "distinct_id": "d1"},
+ {"person_id": ZERO_UUID, "distinct_id": "d2"},
+ ]
+ assert self._run(monkeypatch, rows) == {}
+
+ def test_flags_deleted_persons(self, monkeypatch):
+ pid = "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ rows = [{"person_id": pid, "distinct_id": "d1", "is_deleted": True, "properties": "{}"}]
+ persons = self._run(monkeypatch, rows)
+ assert persons[pid].is_deleted is True
+
+ def test_parses_epoch_seconds_created_at(self, monkeypatch):
+ # Persons dumps store created_at as uint32 epoch seconds, not a parquet timestamp; an int
+ # here must not crash and must decode to the right instant.
+ pid = "cccccccc-cccc-cccc-cccc-cccccccccccc"
+ rows = [{"person_id": pid, "distinct_id": "d1", "properties": "{}", "created_at": 1_704_067_200}]
+ persons = self._run(monkeypatch, rows)
+ assert persons[pid].created_at == datetime(2024, 1, 1, tzinfo=UTC)
diff --git a/posthog/management/commands/bootstrap_local_project.py b/posthog/management/commands/bootstrap_local_project.py
new file mode 100644
index 000000000000..18580533d199
--- /dev/null
+++ b/posthog/management/commands/bootstrap_local_project.py
@@ -0,0 +1,229 @@
+import secrets
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+from posthog.local_bootstrap import (
+ BootstrapConfig,
+ BootstrapConfigError,
+ DiscoveredFile,
+ Progress,
+ S3Location,
+ TableImportConfig,
+ TablePlan,
+ list_files,
+ run_bootstrap,
+)
+from posthog.local_bootstrap.config import SUPPORTED_FILE_FORMATS
+
+
+def _format_bytes(num: int) -> str:
+ size = float(num)
+ for unit in ("B", "KB", "MB", "GB"):
+ if size < 1024:
+ return f"{int(size)} B" if unit == "B" else f"{size:.1f} {unit}"
+ size /= 1024
+ return f"{size:.1f} TB"
+
+
+class Command(BaseCommand):
+ help = (
+ "Bootstrap a local PostHog project from an S3 dump of the events and/or persons tables. "
+ "The dump must be in the PostHog batch-export format (Parquet or JSONLines, optionally "
+ "compressed). Events go to ClickHouse; persons go to Postgres and ClickHouse."
+ )
+
+ def add_arguments(self, parser: Any) -> None:
+ parser.add_argument("--name", help="Project name (prompted if omitted)")
+ parser.add_argument("--email", help="Email for the project owner account (prompted if omitted)")
+ parser.add_argument(
+ "--password",
+ help="Password for the owner account. If omitted, a random one is generated and shown once.",
+ )
+
+ parser.add_argument("--events-bucket", help="S3 bucket holding the events dump")
+ parser.add_argument("--events-prefix", default="", help="Key prefix for the events dump")
+ parser.add_argument("--persons-bucket", help="S3 bucket holding the persons dump")
+ parser.add_argument("--persons-prefix", default="", help="Key prefix for the persons dump")
+
+ # Credentials come from the ambient AWS config (AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY env
+ # vars, shared credentials file, or instance profile) so secrets never land in argv or shell
+ # history. Only the non-sensitive region/endpoint are accepted as flags.
+ parser.add_argument("--aws-region", help="AWS region")
+ parser.add_argument("--aws-endpoint-url", help="Custom S3 endpoint (MinIO, SeaweedFS, R2, ...)")
+
+ # Persons may live in a different region/endpoint; these override the shared values for persons.
+ parser.add_argument("--persons-aws-region")
+ parser.add_argument("--persons-aws-endpoint-url")
+
+ parser.add_argument(
+ "--format", default="Parquet", choices=SUPPORTED_FILE_FORMATS, help="Dump file format (default Parquet)"
+ )
+ parser.add_argument("--compression", default="zstd", help="Compression codec, or 'none' (default zstd)")
+ parser.add_argument("--batch-size", type=int, default=10_000, help="Rows per insert batch (default 10000)")
+ parser.add_argument("--yes", "-y", action="store_true", help="Skip the confirmation prompt")
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ help="Import into an existing team instead of creating a new project (skips project/user creation)",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if not settings.DEBUG and not settings.TEST:
+ raise CommandError("bootstrap_local_project is a local-development tool and refuses to run in production")
+
+ team_id = options.get("team_id")
+ self._generated_password: str | None = None
+ if team_id:
+ name = options["name"] or ""
+ email = options["email"] or ""
+ else:
+ name = options["name"] or self._prompt("Project name")
+ email = options["email"] or self._prompt("Owner email")
+ if not options["password"]:
+ # No hardcoded default: mint a high-entropy password and surface it once at the end.
+ self._generated_password = secrets.token_urlsafe(16)
+ options["password"] = self._generated_password
+ compression = None if options["compression"] in ("none", "") else options["compression"]
+
+ config = self._build_config(name, email, compression, options)
+ try:
+ config.validate(require_identity=team_id is None)
+ except BootstrapConfigError as error:
+ raise CommandError(str(error))
+
+ plans = self._discover(config)
+ self._print_plan_report(config, plans)
+
+ if not options["yes"] and not self._confirm("\nProceed with the import?"):
+ self.stdout.write(self.style.WARNING("Aborted."))
+ return
+
+ report = run_bootstrap(config, plans, self._progress(), team_id=options.get("team_id"))
+ self.stdout.write("") # close the progress line
+ self._print_final_report(report)
+
+ def _build_config(self, name: str, email: str, compression: str | None, options: dict[str, Any]) -> BootstrapConfig:
+ shared = {
+ "region": options["aws_region"],
+ "endpoint_url": options["aws_endpoint_url"],
+ }
+ tables: list[TableImportConfig] = []
+
+ if options["events_bucket"]:
+ tables.append(
+ TableImportConfig(
+ table="events",
+ location=S3Location(bucket=options["events_bucket"], prefix=options["events_prefix"], **shared),
+ file_format=options["format"],
+ compression=compression,
+ )
+ )
+
+ if options["persons_bucket"]:
+ tables.append(
+ TableImportConfig(
+ table="persons",
+ location=S3Location(
+ bucket=options["persons_bucket"],
+ prefix=options["persons_prefix"],
+ region=options["persons_aws_region"] or shared["region"],
+ endpoint_url=options["persons_aws_endpoint_url"] or shared["endpoint_url"],
+ ),
+ file_format=options["format"],
+ compression=compression,
+ )
+ )
+
+ if not tables:
+ raise CommandError("Provide at least one of --events-bucket or --persons-bucket")
+
+ return BootstrapConfig(
+ project_name=name,
+ email=email,
+ password=options["password"] or "",
+ tables=tables,
+ batch_size=options["batch_size"],
+ )
+
+ def _discover(self, config: BootstrapConfig) -> list[TablePlan]:
+ plans: list[TablePlan] = []
+ for table_config in config.tables:
+ self.stdout.write(f"Listing {table_config.table} files in s3://{table_config.location.bucket}...")
+ try:
+ files = list_files(table_config)
+ except Exception as error:
+ raise CommandError(f"Failed to list {table_config.table} files: {error}")
+ if not files:
+ self.stdout.write(
+ self.style.WARNING(
+ f" No {table_config.file_format} files found for {table_config.table} "
+ f"under prefix {table_config.location.prefix!r}"
+ )
+ )
+ plans.append(TablePlan(config=table_config, files=files))
+ return plans
+
+ def _print_plan_report(self, config: BootstrapConfig, plans: list[TablePlan]) -> None:
+ self.stdout.write("")
+ self.stdout.write(self.style.MIGRATE_HEADING("Import plan"))
+ self.stdout.write(f" Project: {config.project_name}")
+ self.stdout.write(f" Owner: {config.email}")
+ self.stdout.write("")
+ for plan in plans:
+ location = plan.config.location
+ compression = plan.config.compression or "none"
+ self.stdout.write(self.style.MIGRATE_LABEL(f" {plan.config.table}"))
+ self.stdout.write(f" Source: s3://{location.bucket}/{location.prefix}")
+ self.stdout.write(f" Format: {plan.config.file_format} ({compression})")
+ self.stdout.write(f" Files: {plan.file_count}")
+ self.stdout.write(f" Total size: {_format_bytes(plan.total_size_bytes)}")
+
+ def _progress(self) -> Progress:
+ is_tty = bool(getattr(self.stdout, "isatty", lambda: False)())
+
+ def on_file(table: str, discovered: DiscoveredFile, index: int, total: int) -> None:
+ self.stdout.write(
+ f"\n {table}: reading file {index + 1}/{total} "
+ f"({_format_bytes(discovered.size_bytes)}) {discovered.key}"
+ )
+
+ def on_rows(table: str, total: int) -> None:
+ message = f" {table}: {total:,} rows imported"
+ if is_tty:
+ self.stdout.write(f"\r{message}", ending="")
+ self.stdout.flush()
+ else:
+ self.stdout.write(message)
+
+ return Progress(on_file=on_file, on_rows=on_rows)
+
+ def _print_final_report(self, report) -> None:
+ self.stdout.write("")
+ self.stdout.write(self.style.SUCCESS("Import complete"))
+ self.stdout.write(f" Project: {report.project_name} (team id {report.team_id})")
+ self.stdout.write(
+ f" Owner: {report.email} ({'created' if report.created_user else 'existing user, new project'})"
+ )
+ for result in report.results:
+ line = f" {result.table}: {result.rows_imported:,} rows"
+ if result.table == "persons":
+ line += f", {result.distinct_ids_imported:,} distinct ids"
+ self.stdout.write(self.style.SUCCESS(line))
+ self.stdout.write("")
+ if self._generated_password:
+ self.stdout.write(self.style.WARNING(f" Generated password (shown once): {self._generated_password}"))
+ self.stdout.write(f" Log in at http://localhost:8010 with {report.email} / the password above.")
+ else:
+ self.stdout.write(f" Log in at http://localhost:8010 with {report.email} / the password you set.")
+
+ def _prompt(self, label: str) -> str:
+ value = input(f"{label}: ").strip()
+ if not value:
+ raise CommandError(f"{label} is required")
+ return value
+
+ def _confirm(self, question: str) -> bool:
+ answer = input(f"{question} [y/N]: ").strip().lower()
+ return answer in ("y", "yes")