: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
chore(clickhouse): single manifest.hcl, run hclexp as a CI binary (#70174)
Paweł Szczur368d957d7a1d
diff --git a/.github/workflows/ci-clickhouse-hcl-schema.yml b/.github/workflows/ci-clickhouse-hcl-schema.ymlindex 2a6956a76ce8..dbdebd986242 100644--- a/.github/workflows/ci-clickhouse-hcl-schema.yml+++ b/.github/workflows/ci-clickhouse-hcl-schema.yml@@ -28,8 +28,9 @@ permissions:packages: readenv:- # Pinned chschema build (not :latest) for reproducibility. Override via repo variable.- HCLEXP_IMAGE: ${{ vars.HCLEXP_IMAGE || 'ghcr.io/posthog/chschema:sha-0409212' }}+ # The chschema build is pinned in posthog/clickhouse/hcl/bin/image.txt; the repo+ # variable overrides it when set (empty = use the pin).+ HCLEXP_IMAGE: ${{ vars.HCLEXP_IMAGE }}jobs:hcl-guard:@@ -50,8 +51,8 @@ jobs:username: ${{ github.actor }}password: ${{ secrets.GITHUB_TOKEN }}- - name: Pull hclexp image- run: docker pull "$HCLEXP_IMAGE"+ - name: Install hclexp+ run: bash posthog/clickhouse/hcl/bin/install-hclexp- name: HCL schema guard (validate + drift)run: bash posthog/clickhouse/hcl/check.shdiff --git a/.github/workflows/ci-clickhouse-multinode-migrations.yml b/.github/workflows/ci-clickhouse-multinode-migrations.ymlindex 43e6697239d9..9a5970d50109 100644--- a/.github/workflows/ci-clickhouse-multinode-migrations.yml+++ b/.github/workflows/ci-clickhouse-multinode-migrations.yml@@ -55,9 +55,9 @@ jobs:# of running a full `manage.py migrate`. Cache miss → file absent →# script falls back to migrate automatically.PRIME_POSTGRES_FROM: schema.sql.gz- # Pinned chschema build used by the live-schema convergence gate- # (verify-live.sh). Keep in sync with posthog/clickhouse/hcl/bin/hclexp.- HCLEXP_IMAGE: ${{ vars.HCLEXP_IMAGE || 'ghcr.io/posthog/chschema:sha-0409212' }}+ # The chschema build used by the live-schema convergence gate is pinned in+ # posthog/clickhouse/hcl/bin/image.txt; the repo variable overrides it when set.+ HCLEXP_IMAGE: ${{ vars.HCLEXP_IMAGE }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -140,8 +140,8 @@ jobs:username: ${{ github.actor }}password: ${{ secrets.GITHUB_TOKEN }}- - name: Pull hclexp image- run: docker pull "$HCLEXP_IMAGE"+ - name: Install hclexp+ run: bash posthog/clickhouse/hcl/bin/install-hclexp- name: Run smoke testrun: tools/infra-scripts/clickhouse-multinode/multinode-migration-smokediff --git a/posthog/clickhouse/hcl/.gitignore b/posthog/clickhouse/hcl/.gitignoreindex d57d71faca49..1258c4a062a1 100644--- a/posthog/clickhouse/hcl/.gitignore+++ b/posthog/clickhouse/hcl/.gitignore@@ -1,2 +1,2 @@-# transient manifest render written by check.sh (see render_manifest)-.hcl-manifest.*+# transient empty-schema baseline written by gen-sql.sh+.empty-schema.*diff --git a/posthog/clickhouse/hcl/README.md b/posthog/clickhouse/hcl/README.mdindex 6d0fc2708dff..223ae1a33bee 100644--- a/posthog/clickhouse/hcl/README.md+++ b/posthog/clickhouse/hcl/README.md@@ -16,9 +16,13 @@ declared once in the manifest — there is no object→roles side-table.```texthcl/- bin/hclexp # wrapper: $HCLEXP_BIN local binary, or pinned container image- nodes # composition manifest: (env, role) -> ordered layer list ← placement- clusters # cluster_name -> composing roles; rendered into the manifest check.sh feeds `validate -manifest` to resolve cross-cluster proxies+ bin/hclexp # wrapper: $HCLEXP_BIN, `hclexp` on $PATH, or the pinned container image+ bin/image.txt # the pinned chschema image tag — the one place to bump+ bin/install-hclexp # extract the pinned binary onto $PATH (what CI does)+ manifest.hcl # composition manifest, consumed by hclexp itself ← placement+ # role "<role>" { env "<env>" { layers = [...] } } -> a node's layer stack+ # cluster "<name>" { roles = [...], aliases = [...] } -> cross-cluster proxy resolution+ lib.sh # shared manifest helpers sourced by the scripts belowroles/shared/ # objects on every role (query_log_archive path + custom_metrics_* sub-views + ops_query_log_archive_mv)roles/ops/shared/ # OPS objects on every OPS envroles/ops/prod/ # OPS objects on both prod envs only (the metrics suite)@@ -79,7 +83,7 @@ only in the ops nodes → `[OPS]`; one under `roles/logs/` → `[LOGS]`.Per-node `{shard}` / `{replica}` stay as ClickHouse macros, so replicas collapse to one definition.A cross-cluster Distributed proxy references a table on another cluster's composition; `check.sh`-renders `nodes` + `clusters` into an HCL manifest and runs `validate -manifest -env <env>`, so those+runs `validate -manifest manifest.hcl -env <env>`, so thoseremotes resolve against their target cluster (existence + column agreement) rather than beingskipped. `system.*` remotes are always resolvable. The `posthog` data cluster is `local`-only here(prod goldens live in posthog-cloud-infra), so `check.sh` passes it via `-cluster` flags — composed@@ -97,18 +101,20 @@ HCL=posthog/clickhouse/hcl$HCL/bin/hclexp -help# it is equivalent to:docker run --rm -v "$PWD:/work" -v "${TMPDIR:-/tmp}:${TMPDIR:-/tmp}" -w /work \- ghcr.io/posthog/chschema:sha-0409212 -help+ "$(cat $HCL/bin/image.txt)" -help```-(For faster local iteration you can build the binary — `go build -o hclexp ./cmd/hclexp` in-`../../../../python-clickhouse-schema` — and `export HCLEXP_BIN=…/hclexp`; the wrapper prefers it.)+The image tag is pinned in `bin/image.txt` — the one place to bump when upgrading hclexp.+The wrapper resolves `$HCLEXP_BIN` → `hclexp` on `$PATH` → that image, so a native binary always+wins: run `bash $HCL/bin/install-hclexp` to extract one from the pinned image (what CI does), or+build it yourself with `go build -o hclexp ./cmd/hclexp` in `../../../../python-clickhouse-schema`.1. **Edit the right layer** for what you're changing:- all-role object (the `query_log_archive` path, `custom_metrics_*` sub-views, cross-cluster MVs) → `roles/shared/`- OPS-only → `roles/ops/shared/` (all OPS envs), `roles/ops/prod/` (both prod envs), or `roles/ops/<env>/` (one env)- LOGS → `roles/logs/shared/` (common) or `roles/logs/<env>/` (per-env / differing)- a brand-new object → add it to the layer above **and**, if it's on a new role, add that role's- line to `nodes` (+ a golden for it).+ block to `manifest.hcl` (+ a golden for it).- a long view/MV `query` → keep it in `<layer>/sql/<object>.sql` and reference it as`query = file("sql/<object>.sql")` (resolved relative to the layer file). The loader normalizes`file()`, heredoc, and inline forms to one canonical query, so the form is purely cosmetic — editdiff --git a/posthog/clickhouse/hcl/bin/hclexp b/posthog/clickhouse/hcl/bin/hclexpindex a2c0694e13d4..b42d42a2d4d9 100755--- a/posthog/clickhouse/hcl/bin/hclexp+++ b/posthog/clickhouse/hcl/bin/hclexp@@ -10,9 +10,10 @@# (`go build -o hclexp ./cmd/hclexp` in the sibling repo) for faster iteration.set -euo pipefail-# Pinned to a concrete build (not :latest) for reproducibility.-# Override via $HCLEXP_IMAGE; bump when intentionally upgrading hclexp.-HCLEXP_IMAGE="${HCLEXP_IMAGE:-ghcr.io/posthog/chschema:sha-0409212}"+# Pinned to a concrete build (not :latest) for reproducibility, in bin/image.txt+# — the one place to bump. Override for a single run via $HCLEXP_IMAGE.+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+HCLEXP_IMAGE="${HCLEXP_IMAGE:-$(cat "$HERE/image.txt")}"if [[ -n "${HCLEXP_BIN:-}" ]]; thenexec "$HCLEXP_BIN" "$@"diff --git a/posthog/clickhouse/hcl/bin/image.txt b/posthog/clickhouse/hcl/bin/image.txtnew file mode 100644index 000000000000..8692450ceea2--- /dev/null+++ b/posthog/clickhouse/hcl/bin/image.txt@@ -0,0 +1 @@+ghcr.io/posthog/chschema:sha-2f80e66diff --git a/posthog/clickhouse/hcl/bin/install-hclexp b/posthog/clickhouse/hcl/bin/install-hclexpnew file mode 100755index 000000000000..e6c31ad390ea--- /dev/null+++ b/posthog/clickhouse/hcl/bin/install-hclexp@@ -0,0 +1,34 @@+#!/usr/bin/env bash+# Put the pinned `hclexp` on $PATH as a native binary.+#+# chschema publishes no release asset, but its distroless image carries the+# static binary at /hclexp — so extract it once instead of paying container+# startup on every hclexp call (bin/hclexp prefers a $PATH binary over the image,+# and dump-live.sh then talks to localhost directly, no --network host).+#+# In GitHub Actions the install dir is appended to $GITHUB_PATH for later steps.+set -euo pipefail++HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"+HCLEXP_IMAGE="${HCLEXP_IMAGE:-$(cat "$HERE/image.txt")}"+BIN_DIR="${HCLEXP_INSTALL_DIR:-${RUNNER_TEMP:-/usr/local}/bin}"++mkdir -p "$BIN_DIR"+docker pull "$HCLEXP_IMAGE"+cid="$(docker create "$HCLEXP_IMAGE")"+trap 'docker rm -f "$cid" >/dev/null 2>&1 || true' EXIT+docker cp "$cid:/hclexp" "$BIN_DIR/hclexp"+chmod +x "$BIN_DIR/hclexp"++if [[ -n "${GITHUB_PATH:-}" ]]; then+ echo "$BIN_DIR" >> "$GITHUB_PATH"+fi++# The image ships a Linux binary, so it only runs where the host is Linux (CI).+# On macOS the extraction still succeeds — build hclexp natively instead.+if [[ "$(uname -s)" != "Linux" ]]; then+ echo "installed $BIN_DIR/hclexp (Linux binary — not runnable on $(uname -s))" >&2+ exit 0+fi++"$BIN_DIR/hclexp" -versiondiff --git a/posthog/clickhouse/hcl/check-live.sh b/posthog/clickhouse/hcl/check-live.shindex 6e94a53a913b..d61a97438308 100755--- a/posthog/clickhouse/hcl/check-live.sh+++ b/posthog/clickhouse/hcl/check-live.sh@@ -26,7 +26,13 @@ ENV="${VERIFY_LIVE_ENV:-local}"WARN="${VERIFY_LIVE_WARN:-0}"DUMPDIR="${1:-${LIVE_DUMP_DIR:?dump dir required (pass as arg1 or set LIVE_DUMP_DIR); run dump-live.sh first}}"-ROLES=(data ops logs ai_events aux sessions)+# shellcheck source=posthog/clickhouse/hcl/lib.sh+. "$HCL/lib.sh"++# Hoisted into an assignment (not inline in the herestring) so set -e aborts on a+# failed load instead of silently producing zero roles — see lib.sh.+roles_lines="$(manifest_roles "$ENV")"+read -r -a ROLES <<< "${roles_lines//$'\n'/ }"# Object-name globs the gate ignores, parsed from exclude.hcl (the quoted glob# strings) — the same list dump-live.sh feeds hclexp -exclude, applied here todiff --git a/posthog/clickhouse/hcl/check.sh b/posthog/clickhouse/hcl/check.shindex 75566e4bdab9..1675ffd59135 100755--- a/posthog/clickhouse/hcl/check.sh+++ b/posthog/clickhouse/hcl/check.sh@@ -1,15 +1,15 @@#!/usr/bin/env bash# Fidelity + reference guard for the declarative ClickHouse schema.#-# Reads the node composition manifest (./nodes) and:-# 1. `hclexp validate`s every role, once per env, via an HCL manifest rendered-# from ./nodes + ./clusters (`-manifest`/`-env`). Cross-cluster Distributed-# proxies resolve against their target cluster's composition, so the remote's-# existence AND its columns are checked (not blanket-skipped). `system.*`-# remotes are always resolvable; a short known_drift_skip covers real-# proxy/storage drift pending a fix.+# Reads the node composition manifest (./manifest.hcl) and:+# 1. `hclexp validate -manifest -env`s every role, once per env. Cross-cluster+# Distributed proxies resolve against their target cluster's composition, so+# the remote's existence AND its columns are checked (not blanket-skipped).+# `system.*` remotes are always resolvable; a short known_drift_skip covers+# real proxy/storage drift pending a fix.# 2. `hclexp diff`s each (env, role) stack against golden/<env>-<role>.hcl,# asserting zero drift.+# 3. Regenerates sql/ into a temp dir and asserts it is committed fresh.## Run from the repo root. Uses ./posthog/clickhouse/hcl/bin/hclexp. Exits non-zero# on any drift or unexpected validation error.@@ -18,17 +18,10 @@ set -euo pipefailHCL=posthog/clickhouse/hclHCLEXP="$HCL/bin/hclexp"GOLDEN="$HCL/golden"-MANIFEST="$HCL/nodes"-CLUSTERS="$HCL/clusters"-# Objects cross-cluster validation flags that we intentionally skip — NOT-# resolution gaps (those resolve via ./clusters). Keyed by env (validate runs per-# env). Keep shrinking; each entry needs a note explaining why it's here.-# query_log_archive_old_ops (prod-us): legacy proxy into ops.query_log_archive_old,-# a retired table already gone from the live prod-us cluster (per the-# PostHog/clickhouse-schema dump) and intentionally unmanaged on ops (see-# roles/ops/prod-eu/ops.hcl). The dead proxy still exists on the live node so-# it stays in the golden; skip until ops drops it from the cluster.+# shellcheck source=posthog/clickhouse/hcl/lib.sh+. "$HCL/lib.sh"+known_drift_skip() {case "$1" inprod-us) echo "query_log_archive_old_ops" ;;@@ -36,78 +29,31 @@ known_drift_skip() {esac}-# csv_items CSV -> the comma list as space-separated words (no spaces in values).-csv_items() { printf '%s' "$1" | tr ',' ' '; }--# emit_hcl_list CSV -> the values as an HCL string list body: "a", "b", "c".-emit_hcl_list() {- local first=1 x- for x in $(csv_items "$1"); do- [ "$first" = 1 ] && first=0 || printf ', '- printf '"%s"' "$x"- done-}--# render_manifest FILE -> the HCL manifest `hclexp validate -manifest` consumes:-# a role block per role (env -> layer stack, from ./nodes) plus a cluster block per-# ./clusters cluster (roles it unions + its aliases). Env-independent — `validate-# -env` selects each role's stack, and a cluster whose roles don't compose in the-# selected env resolves @absent on its own (chschema #127). `nodes` stays the-# single source of composition truth; nothing is duplicated in git.-render_manifest() {- local out="$1" cname roles aliases- awk '- !/^#/ && NF>=3 {- role=$2; env=$1; layers="";- for (i=3;i<=NF;i++) layers = layers (layers==""?"":", ") "\"" $i "\"";- body[role] = body[role] " env \"" env "\" { layers = [" layers "] }\n";- if (!(role in seen)) { order[++n]=role; seen[role]=1 }- }- END { for (i=1;i<=n;i++) printf "role \"%s\" {\n%s}\n", order[i], body[order[i]] }- ' "$MANIFEST" > "$out"- while read -r cname roles aliases; do- [ -n "${cname:-}" ] || continue- { printf 'cluster "%s" {\n roles = [' "$cname"; emit_hcl_list "$roles"; printf ']\n'- [ -n "${aliases:-}" ] && { printf ' aliases = ['; emit_hcl_list "$aliases"; printf ']\n'; }- printf '}\n'- } >> "$out"- done < <(grep -vE '^[[:space:]]*#|^[[:space:]]*$' "$CLUSTERS")-}-rc=0-# Write the rendered manifest UNDER the repo dir, not $TMPDIR: bin/hclexp runs-# hclexp in a container that bind-mounts only $PWD (-> /work), so a /tmp path is-# invisible inside it. A repo-relative path resolves under -w /work like the-# golden/layer paths do. chmod it world-readable: the chschema image runs as-# `nonroot`, but mktemp creates 0600, so the container user couldn't read it.-manifest_hcl="$(mktemp "$HCL/.hcl-manifest.XXXXXX")"-trap 'rm -f "$manifest_hcl"' EXIT-render_manifest "$manifest_hcl"-chmod 644 "$manifest_hcl"-# 1. Cross-cluster reference + column validation, once per env (validates every-# role that composes in that env via the manifest). Cross-cluster proxies-# resolve against ./clusters; a cluster not composed in the env resolves @absent.-for env in $(awk '!/^#/ && NF>=3 {print $1}' "$MANIFEST" | awk '!seen[$0]++'); do+# Hoisted into assignments (not `for x in $(...)`) so set -e aborts on a failed+# load instead of silently iterating zero times — see lib.sh.+envs="$(manifest_envs)"++for env in $envs; doecho "== $env: validate (all roles) =="- if ! "$HCLEXP" validate -manifest "$manifest_hcl" -env "$env" -layer-root "$HCL" \+ if ! "$HCLEXP" validate -manifest "$MANIFEST" -env "$env" -layer-root "$HCL" \-skip-validation "$(known_drift_skip "$env")" >/dev/null; thenecho "FAIL: validate $env"; rc=1fidone-# 2. Golden drift, per (env, role): the committed golden is the resolved-# composition; this catches a layer edited without regenerating.-while read -r env role layers; do- [ -z "${env:-}" ] && continue- case "$env" in \#*) continue ;; esac-- stack=""- for l in $layers; do stack="${stack:+$stack,}$HCL/$l"; done+for env in $envs; do+ roles="$(manifest_roles "$env")"+ for role in $roles; do+ golden="$GOLDEN/$env-$role.hcl"+ if [ ! -f "$golden" ]; then+ echo "== $env/$role: no golden (validate only) =="+ continue+ fi- golden="$GOLDEN/$env-$role.hcl"- if [ -f "$golden" ]; thenecho "== $env/$role: diff vs golden =="+ stack="$(manifest_stack "$env" "$role")"err="$(mktemp)"out="$("$HCLEXP" diff -left "$stack" -right "$golden" 2>"$err")"if [ "$out" != "no differences" ]; then@@ -116,12 +62,9 @@ while read -r env role layers; doecho "no differences"firm -f "$err"- else- echo "== $env/$role: no golden (validate only) =="- fi-done < "$MANIFEST"+ done+done-# The committed build-from-scratch SQL (sql/<env>-<role>.sql) must match the HCL.echo "== sql: freshness =="tmp_sql="$(mktemp -d)"bash "$HCL/gen-sql.sh" "$tmp_sql" >/dev/nulldiff --git a/posthog/clickhouse/hcl/clusters b/posthog/clickhouse/hcl/clustersdeleted file mode 100644index 023b2ea18fb6..000000000000--- a/posthog/clickhouse/hcl/clusters+++ /dev/null@@ -1,26 +0,0 @@-# Stable cluster mapping — rendered into the HCL manifest check.sh feeds-# `hclexp validate -manifest`, so cross-cluster Distributed proxies resolve-# against their target cluster's composition (remote existence + column-# agreement) instead of -skip-validation.-#-# Format: <cluster_name> <roles> [<aliases>]-# <roles> comma-separated node roles whose compositions union into the-# cluster's schema (resolved per -env from ./nodes). Each must be a-# role in ./nodes.-# <aliases> optional comma-separated remote_servers aliases sharing the-# cluster's schema.-#-# Env-independent: `hclexp validate -env <env>` selects each role's stack, and a-# cluster whose roles aren't composed in that env resolves @absent on its own-# (chschema #127). So the `posthog` data cluster — modeled here only for `local`,-# prod goldens in posthog-cloud-infra — is validated for `local` and absent for the-# cloud envs, from this one declaration, no per-env handling.-#-# `system.*` remotes are always resolvable and need no entry.--ops ops-logs logs-aux aux-ai_events ai_events-batch_exports batch_exports-posthog data posthog_writable,posthog_primary_replica,posthog_single_sharddiff --git a/posthog/clickhouse/hcl/codegen/README.md b/posthog/clickhouse/hcl/codegen/README.mdindex c499a3d0c822..a038efaecaa0 100644--- a/posthog/clickhouse/hcl/codegen/README.md+++ b/posthog/clickhouse/hcl/codegen/README.md@@ -9,7 +9,7 @@ side-table.## How it works```text-edit OPS HCL ─▶ for each env in ../nodes: hclexp plan (committed goldens ─▶ working composition)+edit OPS HCL ─▶ for each env in ../manifest.hcl: hclexp plan (committed goldens ─▶ working composition)─▶ gen_migration.py: merge across envs, derive targeting─▶ operations = [run_sql_with_exceptions(...), ...]```@@ -19,7 +19,7 @@ composition for every role of an env at once. Goldens hold only the managed set,`DROP` is a real removal — nothing unmanaged to prune — and `plan` unions roles andorders statements by cross-role dependency, so each operation arrives with its `roles`,engine, and order already resolved (no text parsing). A node's schema =-`compose(its layers)` (see `../nodes`); placement falls out of it:+`compose(its layers)` (see `../manifest.hcl`); placement falls out of it:- **`node_roles`** = the roles whose composition surfaced a statement. A change to a`roles/shared/` object appears in every managed role's node → `node_roles` = those roles@@ -30,7 +30,7 @@ engine, and order already resolved (no text parsing). A node's schema =- **Env-specific** statements (only some envs) are flagged for `settings.CLOUD_DEPLOYMENT`gating.-There is no object→roles map — `../nodes` (the composition manifest) is the single+There is no object→roles map — `../manifest.hcl` (the composition manifest) is the singlesource of truth for placement.## Usage@@ -56,7 +56,7 @@ and bump `max_migration.txt`.comment; the human writes the `CLOUD_DEPLOYMENT` branch (auto-gating is a follow-up).- `--auto` writes the next numbered `migrations/NNNN_<name>.py` and bumps `max_migration.txt`;without it the body goes to stdout (or `--out`) for manual placement.-- Scoped to OPS + LOGS (see `../nodes`). Other roles that also host the shared+- Scoped to OPS + LOGS (see `../manifest.hcl`). Other roles that also host the shared`query_log_archive` path are commented out, so shared-object changes target onlyOPS + LOGS; `events_recent` derives as OPS-only until the DATA node is modeled.@@ -64,4 +64,4 @@ and bump `max_migration.txt`.Placement is the manifest + which layer a file lives in. Put cross-role objects in`roles/shared/`, OPS-only in `roles/ops/<shared|prod|env>/`, and add the (env, role) line-to `../nodes`. `check.sh` verifies every composition against its golden.+to `../manifest.hcl`. `check.sh` verifies every composition against its golden.diff --git a/posthog/clickhouse/hcl/codegen/gen_migration.py b/posthog/clickhouse/hcl/codegen/gen_migration.pyindex 7c9f57798919..766963d11184 100644--- a/posthog/clickhouse/hcl/codegen/gen_migration.py+++ b/posthog/clickhouse/hcl/codegen/gen_migration.py@@ -45,7 +45,8 @@ HERE = os.path.dirname(os.path.abspath(__file__)) # .../posthog/clickhouse/hcl/HCL_DIR = os.path.dirname(HERE) # .../posthog/clickhouse/hclREPO_ROOT = os.path.abspath(os.path.join(HERE, "..", "..", "..", ".."))HCL_REL = os.path.relpath(HCL_DIR, REPO_ROOT) # posthog/clickhouse/hcl (relative: resolves inside the wrapper)-MANIFEST = os.path.join(HCL_DIR, "nodes")+MANIFEST = os.path.join(HCL_DIR, "manifest.hcl")+MANIFEST_REL = os.path.relpath(MANIFEST, REPO_ROOT) # relative: resolves inside the wrapper's container# absolute path to the wrapper (lives at hcl/bin/hclexp); subprocess won't resolve a relative exec via cwdHCLEXP = os.path.join(HCL_DIR, "bin", "hclexp")@@ -55,34 +56,30 @@ HCLEXP = os.path.join(HCL_DIR, "bin", "hclexp")ROLE_ORDER = ["data", "endpoints", "aux", "ai_events", "sessions", "logs", "ops"]-def read_manifest() -> list[tuple[str, str, list[str]]]:- out = []- for line in open(MANIFEST):- s = line.strip()- if not s or s.startswith("#"):- continue- parts = s.split()- out.append((parts[0], parts[1], parts[2:]))- return out--def run(cmd: list[str]) -> str:return subprocess.run(cmd, cwd=REPO_ROOT, capture_output=True, text=True, check=True).stdout-def write_manifest_hcl(manifest: list[tuple[str, str, list[str]]], path: str) -> None:- """Render the `nodes` text manifest as the HCL manifest `plan` expects (role-first)."""- roles: OrderedDict[str, list[tuple[str, list[str]]]] = OrderedDict()- for env, role, layers in manifest:- roles.setdefault(role, []).append((env, layers))- lines = []- for role, envs in roles.items():- lines.append(f'role "{role}" {{')- for env, layers in envs:- lst = ", ".join(f'"{layer}"' for layer in layers)- lines.append(f' env "{env}" {{ layers = [{lst}] }}')- lines.append("}")- open(path, "w").write("\n".join(lines) + "\n")+def manifest_envs() -> list[str]:+ """Envs declared in manifest.hcl, first-seen order.++ hclexp wants -env up front on every subcommand, so it cannot enumerate them for us+ (tracked upstream). Extracting the single-line block labels is safe; comments are skipped.+ """+ envs: list[str] = []+ for line in open(MANIFEST):+ if line.lstrip().startswith("#"):+ continue+ for env in re.findall(r'^\s*env "([^"]+)"', line):+ if env not in envs:+ envs.append(env)+ return envs+++def manifest_roles(env: str) -> list[str]:+ """Roles the manifest deploys in `env`, in manifest order (resolved by hclexp)."""+ out = run([HCLEXP, "load", "-manifest", MANIFEST_REL, "-env", env, "-layer-root", HCL_REL, "-format", "json"])+ return [r["role"] for r in json.loads(out)["roles"]]def write_dump(env: str, roles: list[str], ref: str, dump_dir: str) -> None:@@ -107,14 +104,12 @@ def main() -> None:)args = ap.parse_args()- manifest = read_manifest()envs_for_role: dict[str, set[str]] = {}env_roles: OrderedDict[str, list[str]] = OrderedDict() # env -> roles, in manifest order- for env, role, _ in manifest:- envs_for_role.setdefault(role, set()).add(env)- env_roles.setdefault(env, [])- if role not in env_roles[env]:- env_roles[env].append(role)+ for env in manifest_envs():+ env_roles[env] = manifest_roles(env)+ for role in env_roles[env]:+ envs_for_role.setdefault(role, set()).add(env)# stmt -> {op, roles, envs}; identical SQL across envs/roles dedupes to one op.merged: dict[str, dict] = {}@@ -124,8 +119,6 @@ def main() -> None:unsafe_notes: dict[str, str] = {} # object -> reason (recreate-only changes)with tempfile.TemporaryDirectory() as tmp:- manifest_hcl = os.path.join(tmp, "manifest.hcl")- write_manifest_hcl(manifest, manifest_hcl)for env_idx, (env, roles_in_env) in enumerate(env_roles.items()):dump_dir = os.path.join(tmp, f"dump-{env}")write_dump(env, roles_in_env, args.ref, dump_dir)@@ -135,7 +128,7 @@ def main() -> None:HCLEXP,"plan","-manifest",- manifest_hcl,+ MANIFEST_REL,"-env",env,"-dump",diff --git a/posthog/clickhouse/hcl/diff.sh b/posthog/clickhouse/hcl/diff.shindex f62f6fe2e373..0c3d042c3f6a 100755--- a/posthog/clickhouse/hcl/diff.sh+++ b/posthog/clickhouse/hcl/diff.sh@@ -1,8 +1,8 @@#!/usr/bin/env bash# Preview the migration DDL your uncommitted HCL edits would produce, per node.#-# For each (env, role) in the composition manifest (./nodes) it resolves the layer-# stack twice — committed (left = reference) and working tree (right = desired) —+# For each (env, role) in the composition manifest (./manifest.hcl) it resolves the+# layer stack twice — committed (left = reference) and working tree (right = desired) —# and runs `hclexp diff -left <committed> -right <working> -sql`, so the emitted# statements are the migration to go committed -> changed.#@@ -17,15 +17,16 @@ set -euo pipefailHCL=posthog/clickhouse/hclHCLEXP="$HCL/bin/hclexp"-MANIFEST="$HCL/nodes"++# shellcheck source=posthog/clickhouse/hcl/lib.sh+. "$HCL/lib.sh"++ALL_ROLES="$(grep -oE '^role "[^"]+"' "$MANIFEST" | sed -E 's/.*"(.*)"/\1/')"REF="HEAD"ROLE_FILTER=""for arg in "$@"; do- case "$arg" in- ops|data|endpoints|aux|ai_events|sessions) ROLE_FILTER="$arg" ;;- *) REF="$arg" ;;- esac+ if printf '%s\n' "$ALL_ROLES" | grep -qx "$arg"; then ROLE_FILTER="$arg"; else REF="$arg"; fidoneif git diff --quiet "$REF" -- "$HCL" 2>/dev/null; then@@ -37,26 +38,42 @@ TMP="$(mktemp -d)"trap 'rm -rf "$TMP"' EXITgit archive "$REF" "$HCL" | tar -x -C "$TMP"+REF_MANIFEST="$TMP/$HCL/manifest.hcl"+if [ ! -f "$REF_MANIFEST" ]; then+ echo "FAIL: $REF has no $HCL/manifest.hcl — it predates the manifest; diff against a newer ref" >&2+ exit 1+fi+rc=0-while read -r env role layers; do- [ -z "${env:-}" ] && continue- case "$env" in \#*) continue ;; esac- [ -n "$ROLE_FILTER" ] && [ "$role" != "$ROLE_FILTER" ] && continue-- working=""; committed=""- for l in $layers; do- working="${working:+$working,}$HCL/$l"- committed="${committed:+$committed,}$TMP/$HCL/$l"- done+# Hoisted into assignments (not `for x in $(...)`) so set -e aborts on a failed+# load instead of silently iterating zero times — see lib.sh.+envs="$(manifest_envs)"+for env in $envs; do+ roles="$(manifest_roles "$env")"+ for role in $roles; do+ [ -n "$ROLE_FILTER" ] && [ "$role" != "$ROLE_FILTER" ] && continue++ # The ref's own manifest resolves the committed stack: a layer added or removed+ # by this change must not be attributed to the reference side.+ committed="$(manifest_stack "$env" "$role" "$TMP/$HCL" "$REF_MANIFEST")"+ working="$(manifest_stack "$env" "$role")"+ if [ -z "$committed" ]; then+ echo "=============================================================="+ echo "# $env/$role (new node at $REF -> working tree; see gen-sql.sh for its full schema)"+ echo "=============================================================="+ echo+ continue+ fi- echo "=============================================================="- echo "# $env/$role (committed@$REF -> working tree)"- echo "=============================================================="- if ! "$HCLEXP" diff -left "$committed" -right "$working" -sql; then- echo "WARN: hclexp diff failed for $env/$role" >&2- rc=1- fi- echo-done < "$MANIFEST"+ echo "=============================================================="+ echo "# $env/$role (committed@$REF -> working tree)"+ echo "=============================================================="+ if ! "$HCLEXP" diff -left "$committed" -right "$working" -sql; then+ echo "WARN: hclexp diff failed for $env/$role" >&2+ rc=1+ fi+ echo+ done+doneexit $rcdiff --git a/posthog/clickhouse/hcl/dump-live.sh b/posthog/clickhouse/hcl/dump-live.shindex b213642c7b0c..155ff164611a 100755--- a/posthog/clickhouse/hcl/dump-live.sh+++ b/posthog/clickhouse/hcl/dump-live.sh@@ -43,18 +43,22 @@ ROLES=("sessions localhost 9400 posthog")-# Pin to the same chschema build as bin/hclexp; override via repo variable.-HCLEXP_IMAGE="${HCLEXP_IMAGE:-ghcr.io/posthog/chschema:sha-0409212}"+# Same pin as bin/hclexp; override for a single run via $HCLEXP_IMAGE.+HCLEXP_IMAGE="${HCLEXP_IMAGE:-$(cat "$HCL/bin/image.txt")}"-# hclexp that can reach ClickHouse on the host's published ports. Prefer a local-# binary; otherwise a container sharing the host network namespace so localhost-# resolves to the published compose ports (works on Linux CI; on macOS set-# HCLEXP_BIN to a locally built binary).+# hclexp that can reach ClickHouse on the host's published ports. Prefer a native+# binary (bin/install-hclexp puts one on $PATH); otherwise a container sharing the+# host network namespace so localhost resolves to the published compose ports+# (works on Linux CI; on macOS install the binary or set HCLEXP_BIN).run_hclexp() {if [[ -n "${HCLEXP_BIN:-}" ]]; then"$HCLEXP_BIN" "$@"returnfi+ if command -v hclexp >/dev/null 2>&1; then+ hclexp "$@"+ return+ filocal tmp="${TMPDIR:-/tmp}"; tmp="${tmp%/}"docker run --rm --network host -v "$PWD:/work" -v "$tmp:$tmp" -w /work "$HCLEXP_IMAGE" "$@"}diff --git a/posthog/clickhouse/hcl/gen-golden.sh b/posthog/clickhouse/hcl/gen-golden.shindex b7ea61f98412..5fe9fcb7f74f 100644--- a/posthog/clickhouse/hcl/gen-golden.sh+++ b/posthog/clickhouse/hcl/gen-golden.sh@@ -2,31 +2,40 @@# Refresh the golden for every node in the composition manifest.## Golden = the resolved composition (the desired/predicted schema for that node).-# For each (env, role) it runs `hclexp load -out golden/<env>-<role>.hcl`. check.sh-# then diffs the live composition against the golden, so a stale golden (you edited a-# layer but didn't refresh) is caught. The dump pipeline introspects the real cluster-# after deploy to confirm it converged to the golden.+# For each env it runs `hclexp load -manifest -env -out golden/`, which writes one+# golden/<env>-<role>.hcl per role deployed there. check.sh then diffs the live+# composition against the golden, so a stale golden (you edited a layer but didn't+# refresh) is caught. The dump pipeline introspects the real cluster after deploy to+# confirm it converged to the golden.## Run from the repo root. Uses ./posthog/clickhouse/hcl/bin/hclexp.set -euo pipefailHCL=posthog/clickhouse/hclHCLEXP="$HCL/bin/hclexp"-MANIFEST="$HCL/nodes"GOLDEN="$HCL/golden"+# shellcheck source=posthog/clickhouse/hcl/lib.sh+. "$HCL/lib.sh"+# Optional filters: gen-golden.sh [env] [role] — regenerate a subset.ENV_FILTER="${1:-}"; ROLE_FILTER="${2:-}"-while read -r env role layers; do- [ -z "${env:-}" ] && continue- case "$env" in \#*) continue ;; esac+# Hoisted into an assignment (not `for x in $(...)`) so set -e aborts on a failed+# load instead of silently iterating zero times — see lib.sh.+envs="$(manifest_envs)"+for env in $envs; do[ -n "$ENV_FILTER" ] && [ "$env" != "$ENV_FILTER" ] && continue- [ -n "$ROLE_FILTER" ] && [ "$role" != "$ROLE_FILTER" ] && continue- stack=""- for l in $layers; do stack="${stack:+$stack,}$HCL/$l"; done+ roles="$(manifest_roles "$env")"+ if [ -n "$ROLE_FILTER" ]; then+ printf '%s\n' "$roles" | grep -qx "$ROLE_FILTER" || continue # not deployed in this env+ roles="$ROLE_FILTER"+ set -- -role "$ROLE_FILTER"+ else+ set --+ fi- "$HCLEXP" load -layer "$stack" -out "$GOLDEN/$env-$role.hcl" >/dev/null 2>&1- echo "wrote $GOLDEN/$env-$role.hcl"-done < "$MANIFEST"+ "$HCLEXP" load -manifest "$MANIFEST" -env "$env" -layer-root "$HCL" "$@" -out "$GOLDEN" >/dev/null+ for role in $roles; do echo "wrote $GOLDEN/$env-$role.hcl"; done+donediff --git a/posthog/clickhouse/hcl/gen-sql.sh b/posthog/clickhouse/hcl/gen-sql.shindex 81e32df8592c..2c9d3574f2c4 100644--- a/posthog/clickhouse/hcl/gen-sql.sh+++ b/posthog/clickhouse/hcl/gen-sql.sh@@ -11,9 +11,11 @@ set -euo pipefailHCL=posthog/clickhouse/hclHCLEXP="$HCL/bin/hclexp"-MANIFEST="$HCL/nodes"SQL_DIR="${1:-$HCL/sql}" # optional override (check.sh writes to a temp dir to verify freshness)+# shellcheck source=posthog/clickhouse/hcl/lib.sh+. "$HCL/lib.sh"+mkdir -p "$SQL_DIR"# Empty schema for the diff baseline. It must live under the repo (which bin/hclexp# bind-mounts into the container) and be referenced by a repo-relative path — an@@ -21,19 +23,20 @@ mkdir -p "$SQL_DIR"EMPTY="$HCL/.empty-schema.$$.hcl"; printf 'database "posthog" {\n}\n' > "$EMPTY"trap 'rm -f "$EMPTY"' EXIT-while read -r env role layers; do- [ -z "${env:-}" ] && continue- case "$env" in \#*) continue ;; esac-- stack=""- for l in $layers; do stack="${stack:+$stack,}$HCL/$l"; done-- out="$SQL_DIR/$env-$role.sql"- {- echo "-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit."- echo "-- Full CREATE schema for the $env/$role node. Apply to a fresh ClickHouse to build it."- echo- "$HCLEXP" diff -left "$EMPTY" -right "$stack" -sql- } > "$out"- echo "wrote $out ($(grep -cE '^CREATE' "$out") objects)"-done < "$MANIFEST"+# Hoisted into assignments (not `for x in $(...)`) so set -e aborts on a failed+# load instead of silently iterating zero times — see lib.sh.+envs="$(manifest_envs)"+for env in $envs; do+ roles="$(manifest_roles "$env")"+ for role in $roles; do+ out="$SQL_DIR/$env-$role.sql"+ stack="$(manifest_stack "$env" "$role")"+ {+ echo "-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit."+ echo "-- Full CREATE schema for the $env/$role node. Apply to a fresh ClickHouse to build it."+ echo+ "$HCLEXP" diff -left "$EMPTY" -right "$stack" -sql+ } > "$out"+ echo "wrote $out ($(grep -cE '^CREATE' "$out") objects)"+ done+donediff --git a/posthog/clickhouse/hcl/golden/local-aux.hcl b/posthog/clickhouse/hcl/golden/local-aux.hclindex 9deb863759cc..f3511ae5cb77 100644--- a/posthog/clickhouse/hcl/golden/local-aux.hcl+++ b/posthog/clickhouse/hcl/golden/local-aux.hcl@@ -369,32 +369,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"@@ -428,32 +428,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"diff --git a/posthog/clickhouse/hcl/golden/local-data.hcl b/posthog/clickhouse/hcl/golden/local-data.hclindex a421d9aca14a..3542ffb396b9 100644--- a/posthog/clickhouse/hcl/golden/local-data.hcl+++ b/posthog/clickhouse/hcl/golden/local-data.hcl@@ -773,6 +773,9 @@ database "posthog" {column "client_name" {type = "String"}+ column "client_agent" {+ type = "LowCardinality(String)"+ }column "client_revision" {type = "UInt64"}@@ -1764,32 +1767,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"diff --git a/posthog/clickhouse/hcl/golden/prod-eu-aux.hcl b/posthog/clickhouse/hcl/golden/prod-eu-aux.hclindex da291c2d2f81..dceb64b1639a 100644--- a/posthog/clickhouse/hcl/golden/prod-eu-aux.hcl+++ b/posthog/clickhouse/hcl/golden/prod-eu-aux.hcl@@ -370,32 +370,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"@@ -429,32 +429,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"diff --git a/posthog/clickhouse/hcl/golden/prod-us-aux.hcl b/posthog/clickhouse/hcl/golden/prod-us-aux.hclindex 4dda85b1494a..8a14fc08af08 100644--- a/posthog/clickhouse/hcl/golden/prod-us-aux.hcl+++ b/posthog/clickhouse/hcl/golden/prod-us-aux.hcl@@ -404,32 +404,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"@@ -463,32 +463,32 @@ database "posthog" {type = "DateTime64(6, 'UTC')"}column "category" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'category'), ''), 'unknown')"}column "severity" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'severity'), ''), 'warning')"}column "pipeline_step" {- type = "LowCardinality(String)"- default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"+ type = "LowCardinality(String)"+ default = "coalesce(nullIf(JSONExtractString(details, 'pipelineStep'), ''), 'unknown')"}column "event_uuid" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'eventUuid'))"}column "distinct_id" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'distinctId'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'distinctId'), '')"}column "group_key" {- type = "Nullable(String)"- default = "nullIf(JSONExtractString(details, 'groupKey'), '')"+ type = "Nullable(String)"+ default = "nullIf(JSONExtractString(details, 'groupKey'), '')"}column "person_id" {- type = "Nullable(UUID)"- default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"+ type = "Nullable(UUID)"+ default = "toUUIDOrNull(JSONExtractString(details, 'personId'))"}column "_timestamp" {type = "DateTime"diff --git a/posthog/clickhouse/hcl/lib.sh b/posthog/clickhouse/hcl/lib.shnew file mode 100644index 000000000000..68bcd7bf6286--- /dev/null+++ b/posthog/clickhouse/hcl/lib.sh@@ -0,0 +1,49 @@+# shellcheck shell=bash+# Shared manifest helpers, sourced by the hcl/*.sh scripts.+#+# manifest.hcl is the single source of truth for composition, and `hclexp` parses it —+# so the shell never rebuilds a layer stack by hand. The one thing the tool cannot+# answer is "which envs does this manifest declare" (every subcommand wants -env+# up front), so manifest_envs extracts the block labels. That is label extraction,+# not HCL parsing: `env "<name>" {` labels are single-line by construction.+# Tracked upstream as a chschema issue.+#+# Callers set $HCL (the hcl/ dir, relative to the repo root) before sourcing.++MANIFEST="${MANIFEST:-$HCL/manifest.hcl}"++# These helpers run inside $(...) — a plain `exit` there only kills the subshell,+# and a substitution failing in a `for` word is ignored even under set -e. Callers+# must hoist into an assignment (`roles="$(manifest_roles ...)"`) so set -e catches+# a failed load; the helpers guarantee a load failure is non-zero and on stderr,+# never an empty-but-successful result that makes the guards pass vacuously.++# Envs declared anywhere in the manifest, in first-seen order, comments ignored.+manifest_envs() {+ local envs+ envs="$(grep -vE '^[[:space:]]*#' "$MANIFEST" \+ | grep -oE '^[[:space:]]*env "[^"]+"' \+ | sed -E 's/.*"(.*)"/\1/' \+ | awk '!seen[$0]++')" || true+ [ -n "$envs" ] || { echo "ERROR: no envs declared in $MANIFEST" >&2; return 1; }+ printf '%s\n' "$envs"+}++# Roles the manifest deploys in $1, in manifest order.+manifest_roles() {+ local roles+ roles="$("$HCLEXP" load -manifest "$MANIFEST" -env "$1" -layer-root "$HCL" -format json \+ | jq -r '.roles[].role')" || true+ [ -n "$roles" ] || { echo "ERROR: no roles resolved for env $1 in $MANIFEST" >&2; return 1; }+ printf '%s\n' "$roles"+}++# The resolved layer dirs for env $1 / role $2, comma-joined for `-layer`.+# -layer-root defaults to $HCL; pass $3 to resolve against another tree (diff.sh+# resolves the committed tree unpacked under a temp dir). Empty output is legal:+# diff.sh probes a ref's manifest for roles that may not exist there yet.+manifest_stack() {+ local env="$1" role="$2" root="${3:-$HCL}" manifest="${4:-$MANIFEST}"+ "$HCLEXP" load -manifest "$manifest" -env "$env" -layer-root "$root" -format json \+ | jq -r --arg r "$role" '.roles[] | select(.role == $r) | .resolved_layers | join(",")'+}diff --git a/posthog/clickhouse/hcl/manifest.hcl b/posthog/clickhouse/hcl/manifest.hclnew file mode 100644index 000000000000..b0c108a66596--- /dev/null+++ b/posthog/clickhouse/hcl/manifest.hcl@@ -0,0 +1,143 @@+# Node composition manifest — the source of truth for object placement, and the file+# `hclexp` itself consumes (`validate -manifest`, `plan -manifest`, `load -manifest`).+#+# A node's schema = compose(its layers, in order). Each role block declares, per env,+# the ordered layer dirs (relative to this file) whose composition is that node's+# desired schema.+#+# node_roles for an object is DERIVED, not declared: it is the set of roles whose+# composition includes the layer that defines the object. check.sh, diff.sh, and the+# migration generator all read this file. Cross-role objects (in roles/shared/) appear+# in every role's composition -> node_roles = every role here; OPS-only objects (under+# roles/ops/) appear only in the ops compositions -> node_roles = [OPS].+#+# Layout: roles/shared/ (objects on every role) + roles/<role>/<env-or-shared>/ where+# `shared` = all envs of that role and `prod` = both prod envs (e.g. the OPS metrics+# suite is prod-only but env-identical).+#+# Both managed roles (OPS, LOGS) are modeled for all three cloud envs (dev, prod-us,+# prod-eu); OPS additionally has `local`. OPS carries the env differences; LOGS carries+# the shared managed subset (env-identical, but verified per env for fidelity).+#+# SCOPE: the pilot is OPS + LOGS. The other roles (data/endpoints/aux/ai_events/sessions)+# also host the shared query_log_archive path + custom_metrics, but are intentionally+# left out for now, so node_roles for shared objects derives to [OPS, LOGS] rather than+# every role. To bring a role under management, add its env block and regenerate the+# golden from a host of that role (codegen/README has the extraction).++role "ops" {+ env "local" { layers = ["roles/shared", "roles/ops/shared", "roles/ops/local"] }+ env "dev" { layers = ["roles/shared", "roles/ops/shared", "roles/ops/dev"] }+ env "prod-us" { layers = ["roles/shared", "roles/ops/shared", "roles/ops/prod", "roles/ops/prod-us"] }+ env "prod-eu" { layers = ["roles/shared", "roles/ops/shared", "roles/ops/prod", "roles/ops/prod-eu"] }+}++# The local LOGS node runs a partial/newer schema than the cloud logs nodes, so it+# composes a self-contained roles/logs/local (extracted from the live node) rather+# than the shared cloud layers.+role "logs" {+ env "local" { layers = ["roles/logs/local"] }+ env "dev" { layers = ["roles/shared", "roles/logs/shared", "roles/logs/dev"] }+ env "prod-us" { layers = ["roles/shared", "roles/logs/shared", "roles/logs/prod", "roles/logs/prod-us"] }+ env "prod-eu" { layers = ["roles/shared", "roles/logs/shared", "roles/logs/prod", "roles/logs/prod-eu"] }+}++# AI_EVENTS satellite (LLM analytics). local/hobby run the MSK variant+# (kafka_ai_events_json + ai_events_json_mv) with a sharded_ai_events data table+# + distributed ai_events reader; US/EU run the WarpStream variant+# (kafka_ai_events_json_ws + ai_events_json_ws_mv, MSK dropped by migration 0248)+# writing into a single ai_events data table. roles/ai_events/shared holds the+# env-uniform person / person_distinct_id2 Distributed shims (0240). dev currently+# has only the top-level shared objects (per the latest dump).+role "ai_events" {+ env "local" { layers = ["roles/shared", "roles/ai_events/shared", "roles/ai_events/local"] }+ env "dev" { layers = ["roles/shared"] }+ env "prod-us" { layers = ["roles/shared", "roles/ai_events/shared", "roles/ai_events/prod"] }+ env "prod-eu" { layers = ["roles/shared", "roles/ai_events/shared", "roles/ai_events/prod"] }+}++# AUX satellite: auxiliary tables (error tracking, hog invocations, message assets,+# property values, web/marketing preaggregated). roles/auxiliary/shared holds the env-uniform+# objects; local carries the MSK ingest variant (kafka_error_tracking + its MV, MSK+# kafka_hog_invocation_results); prod carries the WarpStream variant. prod-us adds the+# ingestion_warnings tables. prod goldens are dump-baselined (not live-verifiable here).+role "aux" {+ env "local" { layers = ["roles/shared", "roles/auxiliary/shared", "roles/auxiliary/local"] }+ env "prod-us" { layers = ["roles/shared", "roles/auxiliary/shared", "roles/auxiliary/prod", "roles/auxiliary/prod-us"] }+ env "prod-eu" { layers = ["roles/shared", "roles/auxiliary/shared", "roles/auxiliary/prod", "roles/auxiliary/prod-eu"] }+}++# SESSIONS satellite: the local node runs only the shared query_log_archive path+# (session tables are prod-only), so it composes roles/shared alone. prod nodes host+# the session tables (sessions, raw_sessions, raw_sessions_v3), the events replica,+# channel_definition + web_pre_aggregated_teams (+ their dictionaries), and person+# join tables. roles/sessions/shared holds the env-uniform objects; prod-us/prod-eu+# carry the env-specific channel_definition / events / raw_sessions_v3 (prod-us also+# has writable_events_recent). prod goldens are dump-baselined (not live-verifiable here).+role "sessions" {+ env "local" { layers = ["roles/shared"] }+ env "prod-us" { layers = ["roles/shared", "roles/sessions/shared", "roles/sessions/prod-us"] }+ env "prod-eu" { layers = ["roles/shared", "roles/sessions/shared", "roles/sessions/prod-eu"] }+}++# SESSIONSV3 satellite: US-only node hosting the v3 session tables (events replica,+# raw_sessions_v3) plus the query_log_archive path. Dump-baselined.+role "sessionsv3" {+ env "prod-us" { layers = ["roles/shared", "roles/sessionsv3/prod-us"] }+}++# BATCH_EXPORTS satellite: hosts the sharded_events_recent data table (the recent-events+# store the export workers read; data/ops reach it via Distributed proxies) plus the+# query_log_archive path. Env-specific — prod-eu carries an extra historical_migration+# column. Dump-baselined (no local batch-exports node).+role "batch_exports" {+ env "prod-us" { layers = ["roles/shared", "roles/batch_exports/prod-us"] }+ env "prod-eu" { layers = ["roles/shared", "roles/batch_exports/prod-eu"] }+}++# DATA cluster: the main sharded cluster (events family, persons/groups, sessions,+# preaggregated + analytics tables). Only the local node is modeled here — it runs the+# base schema migrations produce (MSK events_json_mv, ~135 objects, no per-env mat_+# columns). The prod data clusters carry 200-300 env-specific materialized (mat_)+# columns per env that are added out-of-band and churn constantly, so their goldens+# live in PostHog/posthog-cloud-infra (clickhouse/hcl/), not the OSS gate.+role "data" {+ env "local" { layers = ["roles/shared", "roles/data/local"] }+}++# role "endpoints" {+# env "prod-us" { layers = ["roles/shared"] }+# }++# ---------------------------------------------------------------------------+# Cluster mapping — cross-cluster Distributed proxies resolve against their+# target cluster's composition (remote existence + column agreement) instead of+# -skip-validation.+#+# roles node roles whose compositions union into the cluster's schema+# (resolved per -env). Each must be a role block above.+# aliases optional remote_servers aliases sharing the cluster's schema.+#+# Env-independent: `hclexp validate -env <env>` selects each role's stack, and a+# cluster whose roles aren't composed in that env resolves @absent on its own+# (chschema #127). So the `posthog` data cluster — modeled here only for `local`,+# prod goldens in posthog-cloud-infra — is validated for `local` and absent for the+# cloud envs, from this one declaration, no per-env handling.+#+# `system.*` remotes are always resolvable and need no entry.+# ---------------------------------------------------------------------------++cluster "ops" { roles = ["ops"] }++cluster "logs" { roles = ["logs"] }++cluster "aux" { roles = ["aux"] }++cluster "ai_events" { roles = ["ai_events"] }++cluster "batch_exports" { roles = ["batch_exports"] }++cluster "posthog" {+ roles = ["data"]+ aliases = ["posthog_writable", "posthog_primary_replica", "posthog_single_shard"]+}diff --git a/posthog/clickhouse/hcl/nodes b/posthog/clickhouse/hcl/nodesdeleted file mode 100644index d182689a1c80..000000000000--- a/posthog/clickhouse/hcl/nodes+++ /dev/null@@ -1,88 +0,0 @@-# Node composition manifest — the source of truth for object placement (replaces codegen/topology.py).-#-# A node's schema = compose(its layers, in order). Each line is:-# <env> <role> <layer> [<layer> ...]-# layers are directories relative to this file (posthog/clickhouse/hcl/).-#-# node_roles for an object is DERIVED, not declared: it is the set of roles whose-# composition includes the layer that defines the object. check.sh, diff.sh, and the-# migration generator all read this file. Cross-role objects (in roles/shared/) appear-# in every role's composition -> node_roles = every role here; OPS-only objects (under-# roles/ops/) appear only in the ops compositions -> node_roles = [OPS].-#-# Layout: roles/shared/ (objects on every role) + roles/<role>/<env-or-shared>/ where-# `shared` = all envs of that role and `prod` = both prod envs (e.g. the OPS metrics-# suite is prod-only but env-identical).-#-# Both managed roles (OPS, LOGS) are modeled for all three cloud envs (dev, prod-us,-# prod-eu); OPS additionally has `local`. OPS carries the env differences; LOGS carries-# the shared managed subset (env-identical, but verified per env for fidelity).-#-# SCOPE: the pilot is OPS + LOGS. The other roles (data/endpoints/aux/ai_events/sessions)-# also host the shared query_log_archive path + custom_metrics, but are intentionally-# left out for now, so node_roles for shared objects derives to [OPS, LOGS] rather than-# every role. To bring a role under management, uncomment its line and regenerate the-# golden from a host of that role (codegen/README has the extraction).--local ops roles/shared roles/ops/shared roles/ops/local-dev ops roles/shared roles/ops/shared roles/ops/dev-prod-us ops roles/shared roles/ops/shared roles/ops/prod roles/ops/prod-us-prod-eu ops roles/shared roles/ops/shared roles/ops/prod roles/ops/prod-eu--local logs roles/logs/local-dev logs roles/shared roles/logs/shared roles/logs/dev-prod-us logs roles/shared roles/logs/shared roles/logs/prod roles/logs/prod-us-prod-eu logs roles/shared roles/logs/shared roles/logs/prod roles/logs/prod-eu--# AI_EVENTS satellite (LLM analytics). local/hobby run the MSK variant-# (kafka_ai_events_json + ai_events_json_mv) with a sharded_ai_events data table-# + distributed ai_events reader; US/EU run the WarpStream variant-# (kafka_ai_events_json_ws + ai_events_json_ws_mv, MSK dropped by migration 0248)-# writing into a single ai_events data table. roles/ai_events/shared holds the-# env-uniform person / person_distinct_id2 Distributed shims (0240). dev currently-# has only the top-level shared objects (per the latest dump).-local ai_events roles/shared roles/ai_events/shared roles/ai_events/local-dev ai_events roles/shared-prod-us ai_events roles/shared roles/ai_events/shared roles/ai_events/prod-prod-eu ai_events roles/shared roles/ai_events/shared roles/ai_events/prod--# AUX satellite: auxiliary tables (error tracking, hog invocations, message assets,-# property values, web/marketing preaggregated). roles/auxiliary/shared holds the env-uniform-# objects; local carries the MSK ingest variant (kafka_error_tracking + its MV, MSK-# kafka_hog_invocation_results); prod carries the WarpStream variant. prod-us adds the-# ingestion_warnings tables. prod goldens are dump-baselined (not live-verifiable here).-local aux roles/shared roles/auxiliary/shared roles/auxiliary/local-prod-us aux roles/shared roles/auxiliary/shared roles/auxiliary/prod roles/auxiliary/prod-us-prod-eu aux roles/shared roles/auxiliary/shared roles/auxiliary/prod roles/auxiliary/prod-eu--# SESSIONS satellite: the local node runs only the shared query_log_archive path-# (session tables are prod-only), so it composes roles/shared alone. prod nodes host-# the session tables (sessions, raw_sessions, raw_sessions_v3), the events replica,-# channel_definition + web_pre_aggregated_teams (+ their dictionaries), and person-# join tables. roles/sessions/shared holds the env-uniform objects; prod-us/prod-eu-# carry the env-specific channel_definition / events / raw_sessions_v3 (prod-us also-# has writable_events_recent). prod goldens are dump-baselined (not live-verifiable here).-local sessions roles/shared-prod-us sessions roles/shared roles/sessions/shared roles/sessions/prod-us-prod-eu sessions roles/shared roles/sessions/shared roles/sessions/prod-eu--# SESSIONSV3 satellite: US-only node hosting the v3 session tables (events replica,-# raw_sessions_v3) plus the query_log_archive path. Dump-baselined.-prod-us sessionsv3 roles/shared roles/sessionsv3/prod-us--# BATCH_EXPORTS satellite: hosts the sharded_events_recent data table (the recent-events-# store the export workers read; data/ops reach it via Distributed proxies) plus the-# query_log_archive path. Env-specific — prod-eu carries an extra historical_migration-# column. Dump-baselined (no local batch-exports node).-prod-us batch_exports roles/shared roles/batch_exports/prod-us-prod-eu batch_exports roles/shared roles/batch_exports/prod-eu--# DATA cluster: the main sharded cluster (events family, persons/groups, sessions,-# preaggregated + analytics tables). Only the local node is modeled here — it runs the-# base schema migrations produce (MSK events_json_mv, ~135 objects, no per-env mat_-# columns). The prod data clusters carry 200-300 env-specific materialized (mat_)-# columns per env that are added out-of-band and churn constantly, so their goldens-# live in PostHog/posthog-cloud-infra (clickhouse/hcl/), not the OSS gate.-local data roles/shared roles/data/local--# prod-us endpoints roles/shareddiff --git a/posthog/clickhouse/hcl/roles/data/local/tables.hcl b/posthog/clickhouse/hcl/roles/data/local/tables.hclindex d9610b69aa9f..2cd6bc4887c2 100644--- a/posthog/clickhouse/hcl/roles/data/local/tables.hcl+++ b/posthog/clickhouse/hcl/roles/data/local/tables.hcl@@ -760,6 +760,9 @@ database "posthog" {column "client_name" {type = "String"}+ column "client_agent" {+ type = "LowCardinality(String)"+ }column "client_revision" {type = "UInt64"}diff --git a/posthog/clickhouse/hcl/sql/local-data.sql b/posthog/clickhouse/hcl/sql/local-data.sqlindex 7b75d9b79a0f..dba720ecbdb3 100644--- a/posthog/clickhouse/hcl/sql/local-data.sql+++ b/posthog/clickhouse/hcl/sql/local-data.sql@@ -125,6 +125,7 @@ CREATE TABLE posthog.distributed_system_processes (os_user String,client_hostname String,client_name String,+ client_agent LowCardinality(String),client_revision UInt64,client_version_major UInt64,client_version_minor UInt64,