:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(clickhouse): declarative HCL schema + codegen for OPS/LOGS (#65969)
Paweł Szczur6e9b7041d402
diff --git a/.github/workflows/ci-clickhouse-hcl-schema.yml b/.github/workflows/ci-clickhouse-hcl-schema.ymlindex 3191c0410553..cefa39b1c379 100644--- a/.github/workflows/ci-clickhouse-hcl-schema.yml+++ b/.github/workflows/ci-clickhouse-hcl-schema.yml@@ -28,16 +28,21 @@ permissions:packages: readenv:- # Pin to a concrete chschema build (not :latest) for reproducibility. sha-f9490b7- # has the modifier-aware diff (chschema #59) so the guard compares ALIAS/- # MATERIALIZED/DEFAULT columns. Override via repo variable.- HCLEXP_IMAGE: ${{ vars.HCLEXP_IMAGE || 'ghcr.io/posthog/chschema:sha-f9490b7' }}+ # Pin to a concrete chschema build (not :latest) for reproducibility. sha-1871283+ # adds file()/heredoc query refs with beautify-canonical normalization on the+ # layer loader (#68/#69) so a query authored as file("sql/x.sql") compares equal+ # to its golden; it retains the modifier-aware diff (#59). Override via repo variable.+ HCLEXP_IMAGE: ${{ vars.HCLEXP_IMAGE || 'ghcr.io/posthog/chschema:sha-1871283' }}jobs:ops-hcl-guard:name: Validate + diff OPS HCL against golden dumpsruns-on: ubuntu-24.04timeout-minutes: 10+ # Informational only while the declarative-HCL pilot stabilizes: the guard+ # runs and reports drift, but a failure must not block PRs. Remove once the+ # OPS/LOGS managed set is trusted and we want it enforced.+ continue-on-error: truesteps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2@@ -51,5 +56,5 @@ jobs:- name: Pull hclexp imagerun: docker pull "$HCLEXP_IMAGE"- - name: OPS schema guard (validate + drift)- run: bash posthog/clickhouse/hcl/ops/check.sh+ - name: HCL schema guard (validate + drift)+ run: bash posthog/clickhouse/hcl/check.shdiff --git a/posthog/clickhouse/hcl/README.md b/posthog/clickhouse/hcl/README.mdindex f66ce6735083..1a4864fb0153 100644--- a/posthog/clickhouse/hcl/README.md+++ b/posthog/clickhouse/hcl/README.md@@ -1,121 +1,115 @@# Declarative ClickHouse schema (HCL)Source of truth for satellite ClickHouse clusters, managed declaratively with-[`hclexp`](../../../../python-clickhouse-schema) instead of sequential Python-migrations. Schemas are written in HCL, layered for multi-environment setups,-resolved into a flat desired state, and diffed against live clusters (or-captured dumps) to produce migration DDL.+[`hclexp`](../../../../python-clickhouse-schema) instead of hand-written migrations.+Schemas are written in HCL, **composed per node** `(env, role)`, verified against+captured cluster dumps, and used to generate the migration that applies a change.-Currently covers the **OPS** cluster. LOGS is next.+Currently covers the **OPS** and **LOGS** roles across the three cloud envs+(dev, prod-us, prod-eu); OPS also has `local`.-## Layout+## Model: per-node composition++A node's schema = `compose(its layers)`. The two axes are **env** (dev/prod-us/prod-eu)+and **node role** (ops/logs/…). Placement is expressed by _which layers a node composes_,+declared once in the manifest — there is no object→roles side-table.```texthcl/- bin/hclexp # wrapper: local binary or pinned container image- ops/- base/ops.hcl # query_log_archive data path + ops tables/views (all envs)- base/custom_metrics.hcl # custom_metrics Prometheus-style views (all envs)- prod/ops.hcl # metrics suite — prod-us + prod-eu only- env/- local/ops.hcl # local dev — composes base as-is (no local-only objects yet)- dev/ops.hcl # prom_metrics experiment (cloud dev only)- prod-us/ops.hcl # events distributed proxies, sharded_tophog (tophog_new)- prod-eu/ops.hcl # sharded_tophog (tophog) — query_log_archive_old intentionally unmanaged- golden/ # vendored per-env cluster dumps — the drift baseline- check.sh # validate + diff layers vs golden for every env- diff.sh # preview DDL your uncommitted edits produce, per env+ bin/hclexp # wrapper: $HCLEXP_BIN local binary, or pinned container image+ nodes # composition manifest: (env, role) -> ordered layer list ← placement+ roles/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 env+ roles/ops/prod/ # OPS objects on both prod envs only (the metrics suite)+ roles/ops/<env>/ # per-env OPS overlay (sharded_tophog zoo_path, prod-us ProfileEvents2, dev prom_metrics); env ∈ local/dev/prod-us/prod-eu+ roles/logs/shared/ # LOGS objects on every LOGS env+ roles/logs/<env>/ # per-env LOGS overlay (kafka/zoo_path/distributed variants; traces on prod only); env ∈ dev/prod-us/prod-eu+ <layer>/sql/<object>.sql # view/MV query bodies extracted from a layer, referenced as query = file("sql/<object>.sql")+ golden/<env>-<role>.hcl # resolved composition per node (the desired schema); check.sh diffs against it+ sql/<env>-<role>.sql # generated build-from-scratch CREATE schema per node (apply to a fresh ClickHouse)+ check.sh # CI guard: validate + diff every node vs golden + verify golden/ & sql/ are fresh+ diff.sh # preview the DDL your uncommitted edits produce, per node+ gen-golden.sh # (re)generate golden/ — hclexp load per node+ gen-sql.sh # (re)generate sql/+ codegen/gen_migration.py # turn an edit into run_sql_with_exceptions(...) operations```-`base/` is a single layer directory; `hclexp` loads every `*.hcl` in it, so-`base/ops.hcl` and `base/custom_metrics.hcl` are always composed together.--Each environment is the ordered composition of layers:--| Environment | Layer stack | Golden |-| ----------- | ------------------------------- | ------------------------------- |-| local | `base` + `env/local` | — (created from HCL; see below) |-| dev | `base` + `env/dev` | `golden/dev-ops.hcl` |-| prod-us | `base` + `prod` + `env/prod-us` | `golden/prod-us-ops.hcl` |-| prod-eu | `base` + `prod` + `env/prod-eu` | `golden/prod-eu-ops.hcl` |--`local` composes the same shared `base` as cloud (so `custom_metrics` and the-`query_log_archive` data path exist locally too); it just has none of the cloud-env extras. It has no external cluster dump, so `check.sh` validates it but does-not diff it against a golden — the live round-trip is exercised by the-local-apply tooling instead.+`node_roles` is **derived**: an object in `roles/shared/` appears in every node's composition →+`node_roles` = every managed role (currently `[LOGS, OPS]`); an object under `roles/ops/` appears+only in the ops nodes → `[OPS]`; one under `roles/logs/` → `[LOGS]`.-Per-node `{shard}` / `{replica}` stay as ClickHouse macros, so the 1a/1b (1c/1d)-replicas of a cluster collapse to a single definition.+Per-node `{shard}` / `{replica}` stay as ClickHouse macros, so replicas collapse to one definition.+Some objects reference tables outside the composed set by design (custom_metrics → `system`, the+qla MV → `system.query_log`, distributed proxies → other clusters) and are listed in `SKIP` in+`check.sh` so `validate` doesn't flag them.-## The OPS cluster, in brief+## Making a change (edit HCL → migration)-Only `sharded_query_log_archive` (ReplicatedMergeTree, single shard) physically-lives on OPS. Every node role across the fleet also gets three companion objects-that reference it — modeled in `base/ops.hcl`:+Run from the repo root. All the scripts below call `hclexp` through `bin/hclexp`,+which runs the pinned container image — **no install needed, just have Docker running**:-- `query_log_archive` — Distributed **read** → `ops.sharded_query_log_archive`-- `writable_query_log_archive` — Distributed **write** → `ops.sharded_query_log_archive`-- `ops_query_log_archive_mv` — MV reading each node's `system.query_log` and- writing through `writable_query_log_archive`.+```bash+HCL=posthog/clickhouse/hcl+# the wrapper used by every script (for running hclexp directly), e.g.:+$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-1871283 -help+```-Some objects reference tables **outside** the OPS schema by design and are-excluded from `validate` (see `SKIP` in `check.sh`): the `custom_metrics*` views-read the `system` database, the MV reads `system.query_log`, and-`events_main` / `events_recent` are Distributed proxies to the main events-cluster.+(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.)-## Local apply notes+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).+ - 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 — edit+ the `.sql`. `gen-sql.sh`/`gen-golden.sh` emit the beautified form.-The `custom_metrics*` views read system tables (`system.part_log`,-`system.parts`, `system.backup_log`, `system.crash_log`, …). On a fresh local-ClickHouse some of these are created lazily (e.g. `system.part_log` appears only-after merge activity), so applying the views may fail with `UNKNOWN_TABLE` until-those system tables exist. This is an environment dependency, not a schema-issue; on the real clusters the system tables are always present.+2. **Preview the DDL** the change produces, per node:-(The earlier `CREATE VIEW` regeneration bug for views with a column list +-`SELECT *` — [PostHog/chschema#41](https://github.com/PostHog/chschema/issues/41)-— is fixed in `hclexp`; rebuild or pull the latest before running the tooling.)+ ```bash+ bash $HCL/diff.sh # committed HEAD -> working tree, per (env, role); flags UNSAFE+ ```-## Common commands+3. **Generate the migration** — `--auto` writes the next numbered migration and bumps `max_migration.txt`:-Run from the repo root. Point `HCLEXP_BIN` at a built binary for fast local-iteration; CI uses the container image via the same wrapper.+ ```bash+ python $HCL/codegen/gen_migration.py --name <slug> --auto+ ```-```bash-HCLEXP=posthog/clickhouse/hcl/bin/hclexp+ It derives `node_roles` from composition and `sharded`/`is_alter_on_replicated_table` from the engine.+ Review the generated `posthog/clickhouse/migrations/NNNN_<slug>.py`: add `settings.CLOUD_DEPLOYMENT`+ gating where a statement is flagged env-specific, and recheck any `UNSAFE` (recreate) statements by hand.+ (Drop `--auto` to print to stdout instead.)-# Fidelity + reference guard for every OPS environment (CI entry point)-bash posthog/clickhouse/hcl/ops/check.sh+4. **Refresh the generated artifacts** so the guard passes:-# Preview the migration DDL your uncommitted edits would produce, per env-# (committed = reference, working tree = desired). Optional ref / env args.-bash posthog/clickhouse/hcl/ops/diff.sh+ ```bash+ bash $HCL/gen-golden.sh # rebuild golden/ (resolved compositions); optional [env] [role] filter+ bash $HCL/gen-sql.sh # rebuild sql/+ ```-# Resolve a layer stack to canonical HCL-$HCLEXP load -layer posthog/clickhouse/hcl/ops/base,posthog/clickhouse/hcl/ops/env/dev -out /tmp/ops-dev.hcl+ (Golden = the desired post-apply schema; the dump pipeline re-introspects after deploy to confirm+ the real cluster converged to it.)-# Migration DDL to bring a live cluster up to the HCL source of truth-$HCLEXP diff \- -left posthog/clickhouse/hcl/ops/base,posthog/clickhouse/hcl/ops/prod,posthog/clickhouse/hcl/ops/env/prod-us \- -right 'clickhouse://user:pass@host:9440/posthog?secure=true' \- -sql-```+5. **Verify**:-`diff -sql` may flag in-place-impossible changes `-- UNSAFE`. Those are review-gated-and must never be auto-applied to production — `query_log_archive` is a-fleet-wide, sensitive table.+ ```bash+ bash $HCL/check.sh # validate + diff every node vs golden + sql freshness; must exit 0+ ```-## Updating the schema+The committed migration is the apply + history record; the HCL/golden/sql are the source of truth and+the offline guard. `diff -sql` UNSAFE statements (engine/zoo_path/order_by recreations) are review-gated+and must never be auto-applied to production.-1. Edit the relevant layer file(s).-2. When prod changes upstream, re-dump the cluster (see the- `../../../../python-clickhouse-schema` `dump-cluster` command) and refresh the- matching `ops/golden/*-ops.hcl` baseline in the same change.-3. Run `check.sh` — it must report `no differences` for every environment.-4. Generate the migration DDL with `diff -sql` and apply it through the normal- operational path.+## Build a node from scratch-The `golden/*-ops.hcl` files are captured cluster dumps, kept in lockstep with-the layered source so `check.sh` is a deterministic, offline CI guard.+`sql/<env>-<role>.sql` is the full, dependency-ordered CREATE schema for that node — e.g. apply+`sql/local-ops.sql` to a local ClickHouse to create the OPS schema. (It is faithful to the HCL, so it+references the real clusters / `{shard}` macros / Kafka; apply it to an env that has those configured.)diff --git a/posthog/clickhouse/hcl/bin/hclexp b/posthog/clickhouse/hcl/bin/hclexpindex aafd503f3baa..9a7b1457854f 100755--- a/posthog/clickhouse/hcl/bin/hclexp+++ b/posthog/clickhouse/hcl/bin/hclexp@@ -10,11 +10,12 @@# (`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. sha-f9490b7-# includes the modifier-aware diff fix (chschema #59), required so check.sh-# compares ALIAS/MATERIALIZED/DEFAULT columns. Override via $HCLEXP_IMAGE; bump-# when intentionally upgrading hclexp.-HCLEXP_IMAGE="${HCLEXP_IMAGE:-ghcr.io/posthog/chschema:sha-f9490b7}"+# Pinned to a concrete build (not :latest) for reproducibility. sha-1871283 adds+# file()/heredoc query refs with beautify-canonical normalization on the layer+# loader (chschema #68/#69) and beautified dump-sql (#70); it retains structured+# JSON diff (#66), the plan command (#67), and the modifier-aware diff (#59).+# Override via $HCLEXP_IMAGE; bump when intentionally upgrading hclexp.+HCLEXP_IMAGE="${HCLEXP_IMAGE:-ghcr.io/posthog/chschema:sha-1871283}"if [[ -n "${HCLEXP_BIN:-}" ]]; thenexec "$HCLEXP_BIN" "$@"@@ -24,5 +25,8 @@ if command -v hclexp >/dev/null 2>&1; thenexec hclexp "$@"fi-# Mount the repo so layer-dir and dump-file paths resolve inside the container.-exec docker run --rm -v "$PWD:/work" -w /work "$HCLEXP_IMAGE" "$@"+# Mount the repo (relative layer/golden paths resolve under -w /work) and the temp+# dir (diff.sh/gen-sql.sh/the generator pass absolute committed-tree and scratch paths+# under $TMPDIR) so both resolve inside the container.+TMP="${TMPDIR:-/tmp}"; TMP="${TMP%/}"+exec docker run --rm -v "$PWD:/work" -v "$TMP:$TMP" -w /work "$HCLEXP_IMAGE" "$@"diff --git a/posthog/clickhouse/hcl/check.sh b/posthog/clickhouse/hcl/check.shnew file mode 100755index 000000000000..1833ee219c1b--- /dev/null+++ b/posthog/clickhouse/hcl/check.sh@@ -0,0 +1,72 @@+#!/usr/bin/env bash+# Fidelity + reference guard for the declarative OPS ClickHouse schema.+#+# Reads the node composition manifest (./nodes) and, for each (env, role):+# 1. `hclexp validate`s the composed layer stack (cross-object refs resolve),+# skipping refs that intentionally point outside the composed set (the+# `system` database, the main events cluster, and the OPS-only data table+# that the shared distributed tables read from).+# 2. `hclexp diff`s the stack against golden/<env>-<role>.hcl, asserting zero drift.+# The golden is the resolved composition (run ops/gen-golden.sh to refresh it), so+# this catches a stale golden — a layer edited without regenerating. Reality-fidelity+# (HCL vs the real cluster) is the post-deploy introspection's job, not this guard.+#+# Run from the repo root. Uses ./posthog/clickhouse/hcl/bin/hclexp. Exits non-zero+# on any drift or unexpected validation error.+set -euo pipefail++HCL=posthog/clickhouse/hcl+HCLEXP="$HCL/bin/hclexp"+GOLDEN="$HCL/golden"+MANIFEST="$HCL/nodes"++# Objects whose source/target lives outside a composed set by design:+# - custom_metrics* read the `system` database+# - ops_query_log_archive_mv reads system.query_log+# - events_main / events_recent are Distributed proxies to the main events cluster+# - query_log_archive / writable_query_log_archive are Distributed over the OPS-only+# sharded_query_log_archive, which is absent from non-OPS (shared-only) compositions+SKIP='custom_metrics,custom_metrics_backups,custom_metrics_dictionaries,custom_metrics_part_counts,custom_metrics_replication_queue,custom_metrics_server_crash,custom_metrics_table_sizes,custom_metrics_test,ops_query_log_archive_mv,events_main,events_recent,query_log_archive,writable_query_log_archive'++rc=0+while read -r env role layers; do+ [ -z "${env:-}" ] && continue+ case "$env" in \#*) continue ;; esac++ # Build comma-separated layer dirs rooted at the ops dir.+ stack=""+ for l in $layers; do stack="${stack:+$stack,}$HCL/$l"; done++ echo "== $env/$role: validate =="+ if ! "$HCLEXP" validate -layer "$stack" -skip-validation "$SKIP" >/dev/null; then+ echo "FAIL: validate $env/$role"; rc=1+ fi++ golden="$GOLDEN/$env-$role.hcl"+ if [ -f "$golden" ]; then+ echo "== $env/$role: diff vs golden =="+ err="$(mktemp)"+ out="$("$HCLEXP" diff -left "$stack" -right "$golden" 2>"$err")"+ if [ "$out" != "no differences" ]; then+ echo "FAIL: drift in $env/$role"; echo "$out"; cat "$err"; rc=1+ else+ echo "no differences"+ fi+ rm -f "$err"+ else+ echo "== $env/$role: no golden (validate only) =="+ fi+done < "$MANIFEST"++# 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/null+if ! diff -r "$HCL/sql" "$tmp_sql" >/dev/null 2>&1; then+ echo "FAIL: sql/ is stale — run ops/gen-sql.sh and commit"; diff -r "$HCL/sql" "$tmp_sql" | head; rc=1+else+ echo "sql up to date"+fi+rm -rf "$tmp_sql"++exit $rcdiff --git a/posthog/clickhouse/hcl/codegen/README.md b/posthog/clickhouse/hcl/codegen/README.mdnew file mode 100644index 000000000000..c499a3d0c822--- /dev/null+++ b/posthog/clickhouse/hcl/codegen/README.md@@ -0,0 +1,67 @@+# OPS HCL → migration codegen++Turns a declarative-HCL change into a ClickHouse migration the existing+`infi.clickhouse_orm` runner executes. The HCL is the source of truth for _what_+the schema is; this produces the `run_sql_with_exceptions(...)` operations for+_applying_ it — with the cluster targeting derived from **composition**, not a+side-table.++## How it works++```text+edit OPS HCL ─▶ for each env in ../nodes: hclexp plan (committed goldens ─▶ working composition)+ ─▶ gen_migration.py: merge across envs, derive targeting+ ─▶ operations = [run_sql_with_exceptions(...), ...]+```++`plan` diffs the **committed goldens** (current managed state) against the working-tree+composition for every role of an env at once. Goldens hold only the managed set, so a+`DROP` is a real removal — nothing unmanaged to prune — and `plan` unions roles and+orders 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:++- **`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+ (the pilot manages OPS + LOGS, so `[LOGS, OPS]`); a change to an OPS-only object+ (under `roles/ops/`) appears only in the ops nodes → `node_roles = [OPS]`.+- **`is_alter_on_replicated_table`** = ALTER on a `Replicated*` MergeTree (engine).+- **`sharded`** = replicated _and_ on the multi-shard DATA cluster.+- **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+source of truth for placement.++## Usage++Runs `hclexp` via `bin/hclexp` (the pinned ghcr.io image) — just have Docker running:++```bash+python posthog/clickhouse/hcl/codegen/gen_migration.py --name add_foo_column --auto+# --auto write the next posthog/clickhouse/migrations/NNNN_<name>.py and bump max_migration.txt+# --ref <git-ref> the golden baseline to diff the working tree against (default HEAD)+# --out <path|-> without --auto: write here, or stdout (default)+# (optional: export HCLEXP_BIN=…/hclexp to use a local binary instead of Docker)+```++Then: review the output, save it as the next `posthog/clickhouse/migrations/NNNN_<name>.py`,+and bump `max_migration.txt`.++## Guardrails / limitations++- **UNSAFE changes are flagged** (`# UNSAFE (review/recreate by hand)`); never emitted+ silently as a plain ALTER.+- Env-specific statements get a `# NOTE: only [...] — gate with settings.CLOUD_DEPLOYMENT`+ 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+ `query_log_archive` path are commented out, so shared-object changes target only+ OPS + LOGS; `events_recent` derives as OPS-only until the DATA node is modeled.++## Adding/moving objects++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.diff --git a/posthog/clickhouse/hcl/codegen/gen_migration.py b/posthog/clickhouse/hcl/codegen/gen_migration.pynew file mode 100644index 000000000000..7c9f57798919--- /dev/null+++ b/posthog/clickhouse/hcl/codegen/gen_migration.py@@ -0,0 +1,219 @@+#!/usr/bin/env python3+"""Generate a ClickHouse migration from a declarative-HCL change.++Uses `hclexp plan` to diff the **committed goldens** (current managed state) against+the **working-tree composition** (desired) for every role at once, per env. Because+goldens hold only the managed set, a DROP here is a real removal — there is no live+cluster and nothing unmanaged to prune. `plan` unions roles and orders statements by+cross-role dependency, so each operation already carries everything we need — no text+parsing:++ sql / kind / object the DDL statement and what it does+ roles which node roles surfaced it (union across the env)+ engine / replicated used to derive the targeting below+ order hclexp's cross-role dependency order+ unsafe / unsafe_reason recreate-only changes, surfaced as review notes++For each env in the manifest we feed plan a -dump built from that env's committed+goldens (tagged with hostClusterRole) and resolve the desired side from the working+layers. Results are merged across envs to derive:++ node_roles = roles, ordered by ROLE_ORDER+ is_alter_on_replicated_table = ALTER on a Replicated* MergeTree (from `replicated`)+ sharded = replicated AND on the multi-shard DATA cluster+ env-specific statements = present in only some envs -> CLOUD_DEPLOYMENT gating++Output is the `operations = [...]` body for a numbered migration.++Usage (from the repo root):+ python posthog/clickhouse/hcl/codegen/gen_migration.py --name add_foo+ # --ref <git-ref> (default HEAD, the golden baseline), --out <path|->, --auto+"""++from __future__ import annotations++import os+import re+import sys+import json+import argparse+import tempfile+import subprocess+from collections import OrderedDict++HERE = os.path.dirname(os.path.abspath(__file__)) # .../posthog/clickhouse/hcl/codegen+HCL_DIR = os.path.dirname(HERE) # .../posthog/clickhouse/hcl+REPO_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")+# absolute path to the wrapper (lives at hcl/bin/hclexp); subprocess won't resolve a relative exec via cwd+HCLEXP = os.path.join(HCL_DIR, "bin", "hclexp")++# Canonical role order for emitted node_roles (mirrors ALL_ROLES in migration 0273).+# Only roles present in the manifest appear; the rest are listed for stable ordering+# if/when they are uncommented there.+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 write_dump(env: str, roles: list[str], ref: str, dump_dir: str) -> None:+ """Build plan's -dump for one env from the committed goldens, tagged by role."""+ os.makedirs(dump_dir)+ for role in roles:+ golden = run(["git", "show", f"{ref}:{HCL_REL}/golden/{env}-{role}.hcl"])+ with open(os.path.join(dump_dir, f"{role}.hcl"), "w") as f:+ f.write(f'node "{role}" {{\n macros = {{ hostClusterRole = "{role}" }}\n}}\n')+ f.write(golden)+++def main() -> None:+ ap = argparse.ArgumentParser()+ ap.add_argument("--name", required=True)+ ap.add_argument("--ref", default="HEAD")+ ap.add_argument("--out", default="-")+ ap.add_argument(+ "--auto",+ action="store_true",+ help="write the next numbered migration into posthog/clickhouse/migrations/ and bump max_migration.txt",+ )+ 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)++ # stmt -> {op, roles, envs}; identical SQL across envs/roles dedupes to one op.+ merged: dict[str, dict] = {}+ # stmt -> (env_index, plan order): first-seen global order. plan orders across roles+ # by dependency within an env; across envs we keep manifest order.+ order_key: dict[str, tuple[int, int]] = {}+ 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)+ data = json.loads(+ run(+ [+ HCLEXP,+ "plan",+ "-manifest",+ manifest_hcl,+ "-env",+ env,+ "-dump",+ dump_dir,+ "-layer-root",+ HCL_REL,+ "-format",+ "json",+ ]+ )+ )+ for op in data.get("operations") or []:+ sql = op["sql"]+ entry = merged.setdefault(sql, {"op": op, "roles": set(), "envs": set()})+ entry["roles"].update(op.get("roles") or [])+ entry["envs"].add(env)+ order_key.setdefault(sql, (env_idx, op["order"]))+ if op.get("unsafe"):+ unsafe_notes.setdefault(op["object"], op.get("unsafe_reason") or "recreate required")++ if not merged:+ raise SystemExit("No DDL generated — the HCL has no changes vs the goldens.")++ notes = [f"# UNSAFE (review/recreate by hand): {obj} — {reason}" for obj, reason in sorted(unsafe_notes.items())]+ operations = []+ for sql in sorted(merged, key=lambda s: order_key[s]):+ entry = merged[sql]+ op, roles, envs = entry["op"], entry["roles"], entry["envs"]+ node_roles = [r for r in ROLE_ORDER if r in roles]+ replicated = op["replicated"]+ is_alter_repl = op["kind"] == "ALTER" and replicated+ sharded = replicated and "data" in roles+ # Env-specific if the statement is absent from some env that hosts these roles.+ full_envs = set().union(*(envs_for_role[r] for r in roles))+ gate = "" if envs >= full_envs else f" # NOTE: only {sorted(envs)} — gate with settings.CLOUD_DEPLOYMENT"+ roles_src = "[" + ", ".join(f"NodeRole.{r.upper()}" for r in node_roles) + "]"+ operations.append(+ " run_sql_with_exceptions(\n"+ f" {sql!r},\n"+ f" node_roles={roles_src},{gate}\n"+ f" sharded={sharded},\n"+ f" is_alter_on_replicated_table={is_alter_repl},\n"+ " ),"+ )++ body = (+ '"""AUTO-GENERATED from the declarative HCL by '+ "posthog/clickhouse/hcl/codegen/gen_migration.py.\n"+ "Placement (node_roles) is derived from the node composition manifest; review before committing.\n"+ '"""\n'+ "from posthog.clickhouse.client.connection import NodeRole\n"+ "from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions\n\n"+ )+ if notes:+ body += "\n".join(notes) + "\n\n"+ body += "operations = [\n" + "\n".join(operations) + "\n]\n"++ if args.auto:+ mig_dir = os.path.join(REPO_ROOT, "posthog", "clickhouse", "migrations")+ max_file = os.path.join(mig_dir, "max_migration.txt")+ last = open(max_file).read().strip()+ m = re.match(r"(\d+)", last)+ if not m:+ raise SystemExit(f"ERROR: can't parse a migration number from max_migration.txt: {last!r}")+ num = int(m.group(1)) + 1+ name = f"{num:04d}_{args.name}"+ path = os.path.join(mig_dir, f"{name}.py")+ if os.path.exists(path):+ raise SystemExit(f"ERROR: {path} already exists")+ open(path, "w").write(body)+ open(max_file, "w").write(name + "\n")+ sys.stderr.write(f"wrote {os.path.relpath(path, REPO_ROOT)}\nbumped max_migration.txt -> {name}\n")+ elif args.out == "-":+ sys.stdout.write(body)+ else:+ open(args.out, "w").write(body)+ sys.stderr.write(f"wrote {args.out}\n")+++if __name__ == "__main__":+ main()diff --git a/posthog/clickhouse/hcl/diff.sh b/posthog/clickhouse/hcl/diff.shnew file mode 100755index 000000000000..f62f6fe2e373--- /dev/null+++ b/posthog/clickhouse/hcl/diff.sh@@ -0,0 +1,62 @@+#!/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) —+# and runs `hclexp diff -left <committed> -right <working> -sql`, so the emitted+# statements are the migration to go committed -> changed.+#+# Companion to check.sh (which guards composition vs golden); this asks "what does+# my change actually do?". Read-only. UNSAFE (recreate) changes are flagged by hclexp.+#+# Usage (from repo root):+# posthog/clickhouse/hcl/diff.sh # working tree vs HEAD, all nodes+# posthog/clickhouse/hcl/diff.sh <ref> # working tree vs an arbitrary ref+# posthog/clickhouse/hcl/diff.sh <ref> ops # filter to one role+set -euo pipefail++HCL=posthog/clickhouse/hcl+HCLEXP="$HCL/bin/hclexp"+MANIFEST="$HCL/nodes"++REF="HEAD"+ROLE_FILTER=""+for arg in "$@"; do+ case "$arg" in+ ops|data|endpoints|aux|ai_events|sessions) ROLE_FILTER="$arg" ;;+ *) REF="$arg" ;;+ esac+done++if git diff --quiet "$REF" -- "$HCL" 2>/dev/null; then+ echo "no HCL changes under $HCL (vs $REF)"+ exit 0+fi++TMP="$(mktemp -d)"+trap 'rm -rf "$TMP"' EXIT+git archive "$REF" "$HCL" | tar -x -C "$TMP"++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++ 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"++exit $rcdiff --git a/posthog/clickhouse/hcl/gen-golden.sh b/posthog/clickhouse/hcl/gen-golden.shnew file mode 100644index 000000000000..b7ea61f98412--- /dev/null+++ b/posthog/clickhouse/hcl/gen-golden.sh@@ -0,0 +1,32 @@+#!/usr/bin/env bash+# 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.+#+# Run from the repo root. Uses ./posthog/clickhouse/hcl/bin/hclexp.+set -euo pipefail++HCL=posthog/clickhouse/hcl+HCLEXP="$HCL/bin/hclexp"+MANIFEST="$HCL/nodes"+GOLDEN="$HCL/golden"++# 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+ [ -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++ "$HCLEXP" load -layer "$stack" -out "$GOLDEN/$env-$role.hcl" >/dev/null 2>&1+ echo "wrote $GOLDEN/$env-$role.hcl"+done < "$MANIFEST"diff --git a/posthog/clickhouse/hcl/gen-sql.sh b/posthog/clickhouse/hcl/gen-sql.shnew file mode 100644index 000000000000..81e32df8592c--- /dev/null+++ b/posthog/clickhouse/hcl/gen-sql.sh@@ -0,0 +1,39 @@+#!/usr/bin/env bash+# Generate the "build-from-scratch" SQL for every node in the composition manifest.+#+# For each (env, role) it diffs the composed layer stack against an empty schema, so+# `hclexp` emits the full set of CREATE statements (dependency-ordered) that build that+# node's schema. Output: sql/<env>-<role>.sql — e.g. apply sql/local-ops.sql to a local+# ClickHouse to create the OPS schema.+#+# Run from the repo root. Uses ./posthog/clickhouse/hcl/bin/hclexp.+set -euo pipefail++HCL=posthog/clickhouse/hcl+HCLEXP="$HCL/bin/hclexp"+MANIFEST="$HCL/nodes"+SQL_DIR="${1:-$HCL/sql}" # optional override (check.sh writes to a temp dir to verify freshness)++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+# absolute $TMPDIR path is not visible inside the container in CI.+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"diff --git a/posthog/clickhouse/hcl/golden/dev-logs.hcl b/posthog/clickhouse/hcl/golden/dev-logs.hclnew file mode 100644index 000000000000..b3c12b9865d6--- /dev/null+++ b/posthog/clickhouse/hcl/golden/dev-logs.hcl@@ -0,0 +1,2286 @@+database "posthog" {+ table "kafka_logs_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ engine "kafka" {+ broker_list = "warpstream_logs"+ topic_list = "kafka_topic_list = 'clickhouse_logs'"+ group_name = "kafka_group_name = 'clickhouse-logs-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "kafka_metrics_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Nullable(Int32)"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "Nullable(String)"+ }+ column "metric_name" {+ type = "Nullable(String)"+ }+ column "metric_type" {+ type = "Nullable(String)"+ }+ column "value" {+ type = "Nullable(Float64)"+ }+ column "count" {+ type = "Nullable(Int64)"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(Int64)"+ }+ column "unit" {+ type = "Nullable(String)"+ }+ column "aggregation_temporality" {+ type = "Nullable(String)"+ }+ column "is_monotonic" {+ type = "Nullable(UInt8)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "Nullable(String)"+ }+ column "attributes" {+ type = "Map(String, String)"+ }+ engine "kafka" {+ broker_list = "warpstream_metrics"+ topic_list = "kafka_topic_list = 'clickhouse_metrics'"+ group_name = "kafka_group_name = 'clickhouse-metrics-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "log_attributes2" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ ttl = "time_bucket + toIntervalDay(15)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/log_attributes34"+ replica_name = "{replica}"+ }+ }++ table "log_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "log_attributes2"+ }+ }++ table "logs34" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "severity_text", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ add_minmax_index_for_numeric_columns = "1"+ allow_experimental_reverse_key = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_severity_text_set" {+ expr = "severity_text"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_mat_body_ipv4_matches" {+ expr = "mat_body_ipv4_matches"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_body_ngram3" {+ expr = "lower(body)"+ type = "ngrambf_v1(3, 25000, 2, 0)"+ granularity = 1+ }+ index "idx_uuid_bloom" {+ expr = "uuid"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.logs34"+ replica_name = "{replica}"+ }+ }++ table "logs_billing_metrics" {+ order_by = ["team_id", "time_bucket", "service_name"]+ partition_by = "toYYYYMM(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_billing_metrics"+ replica_name = "{replica}"+ }+ }++ table "logs_billing_metrics_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_billing_metrics"+ }+ }++ table "logs_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs34"+ }+ }++ table "logs_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "logs_kafka_metrics_distributed" {+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_kafka_metrics"+ }+ }++ table "metric_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metric_attributes"+ replica_name = "{replica}"+ }+ }++ table "metrics" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "metrics1"+ }+ }++ table "metrics1" {+ order_by = ["team_id", "time_bucket", "service_name", "metric_name", "resource_fingerprint", "timestamp"]+ partition_by = "toDate(timestamp)"+ settings = {+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ index "idx_metric_name_set" {+ expr = "metric_name"+ type = "set(100)"+ granularity = 1+ }+ index "idx_metric_type_set" {+ expr = "metric_type"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics1"+ replica_name = "{replica}"+ }+ }++ table "metrics_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ column "exception_name" {+ type = "String"+ alias = "errorCodeToName(exception_code)"+ }+ column "ProfileEvents_RealTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['RealTimeMicroseconds']"+ }+ column "ProfileEvents_OSCPUVirtualTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['OSCPUVirtualTimeMicroseconds']"+ }+ column "ProfileEvents_S3Clients" {+ type = "Int64"+ alias = "ProfileEvents['S3Clients']"+ }+ column "ProfileEvents_S3DeleteObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3DeleteObjects']"+ }+ column "ProfileEvents_S3CopyObject" {+ type = "Int64"+ alias = "ProfileEvents['S3CopyObject']"+ }+ column "ProfileEvents_S3ListObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3ListObjects']"+ }+ column "ProfileEvents_S3HeadObject" {+ type = "Int64"+ alias = "ProfileEvents['S3HeadObject']"+ }+ column "ProfileEvents_S3GetObjectAttributes" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObjectAttributes']"+ }+ column "ProfileEvents_S3CreateMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CreateMultipartUpload']"+ }+ column "ProfileEvents_S3UploadPartCopy" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPartCopy']"+ }+ column "ProfileEvents_S3UploadPart" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPart']"+ }+ column "ProfileEvents_S3AbortMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3AbortMultipartUpload']"+ }+ column "ProfileEvents_S3CompleteMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CompleteMultipartUpload']"+ }+ column "ProfileEvents_S3PutObject" {+ type = "Int64"+ alias = "ProfileEvents['S3PutObject']"+ }+ column "ProfileEvents_S3GetObject" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObject']"+ }+ column "ProfileEvents_ReadBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['ReadBufferFromS3Bytes']"+ }+ column "ProfileEvents_WriteBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['WriteBufferFromS3Bytes']"+ }+ column "lc_workflow" {+ type = "LowCardinality(String)"+ alias = "log_comment.workflow"+ }+ column "lc_kind" {+ type = "LowCardinality(String)"+ alias = "log_comment.kind"+ }+ column "lc_id" {+ type = "String"+ alias = "CAST(log_comment.id, 'String')"+ }+ column "lc_route_id" {+ type = "String"+ alias = "CAST(log_comment.route_id, 'String')"+ }+ column "lc_access_method" {+ type = "LowCardinality(String)"+ alias = "log_comment.access_method"+ }+ column "lc_api_key_label" {+ type = "String"+ alias = "CAST(log_comment.api_key_label, 'String')"+ }+ column "lc_api_key_mask" {+ type = "String"+ alias = "CAST(log_comment.api_key_mask, 'String')"+ }+ column "lc_query_type" {+ type = "LowCardinality(String)"+ alias = "log_comment.query_type"+ }+ column "lc_product" {+ type = "LowCardinality(String)"+ alias = "log_comment.product"+ }+ column "lc_chargeable" {+ type = "Bool"+ alias = "log_comment.chargeable"+ }+ column "lc_name" {+ type = "String"+ alias = "CAST(log_comment.name, 'String')"+ }+ column "lc_request_name" {+ type = "String"+ alias = "CAST(log_comment.request_name, 'String')"+ }+ column "lc_client_query_id" {+ type = "String"+ alias = "CAST(log_comment.client_query_id, 'String')"+ }+ column "lc_org_id" {+ type = "String"+ alias = "CAST(log_comment.org_id, 'String')"+ }+ column "lc_user_id" {+ type = "Int64"+ alias = "log_comment.user_id"+ }+ column "lc_is_impersonated" {+ type = "Bool"+ alias = "log_comment.is_impersonated"+ }+ column "lc_session_id" {+ type = "String"+ alias = "CAST(log_comment.session_id, 'String')"+ }+ column "lc_dashboard_id" {+ type = "Int64"+ alias = "log_comment.dashboard_id"+ }+ column "lc_insight_id" {+ type = "Int64"+ alias = "log_comment.insight_id"+ }+ column "lc_cohort_id" {+ type = "Int64"+ alias = "log_comment.cohort_id"+ }+ column "lc_batch_export_id" {+ type = "String"+ alias = "CAST(log_comment.batch_export_id, 'String')"+ }+ column "lc_experiment_id" {+ type = "Int64"+ alias = "log_comment.experiment_id"+ }+ column "lc_experiment_feature_flag_key" {+ type = "String"+ alias = "CAST(log_comment.experiment_feature_flag_key, 'String')"+ }+ column "lc_alert_config_id" {+ type = "String"+ alias = "CAST(log_comment.alert_config_id, 'String')"+ }+ column "lc_feature" {+ type = "LowCardinality(String)"+ alias = "log_comment.feature"+ }+ column "lc_table_id" {+ type = "String"+ alias = "CAST(log_comment.table_id, 'String')"+ }+ column "lc_warehouse_query" {+ type = "Bool"+ alias = "log_comment.warehouse_query"+ }+ column "lc_person_on_events_mode" {+ type = "LowCardinality(String)"+ alias = "log_comment.person_on_events_mode"+ }+ column "lc_service_name" {+ type = "String"+ alias = "CAST(log_comment.service_name, 'String')"+ }+ column "lc_workload" {+ type = "LowCardinality(String)"+ alias = "log_comment.workload"+ }+ column "lc_query__kind" {+ type = "LowCardinality(String)"+ alias = "if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind'))"+ }+ column "lc_query__query" {+ type = "String"+ alias = "multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query'))"+ }+ column "lc_query" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), '')"+ }+ column "lc_temporal__workflow_namespace" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_namespace`, 'String')"+ }+ column "lc_temporal__workflow_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_type`, 'String')"+ }+ column "lc_temporal__workflow_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_id`, 'String')"+ }+ column "lc_temporal__workflow_run_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_run_id`, 'String')"+ }+ column "lc_temporal__activity_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_type`, 'String')"+ }+ column "lc_temporal__activity_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_id`, 'String')"+ }+ column "lc_temporal__attempt" {+ type = "Int64"+ alias = "log_comment.`temporal.attempt`"+ }+ column "lc_dagster__job_name" {+ type = "String"+ alias = "CAST(log_comment.`dagster.job_name`, 'String')"+ }+ column "lc_dagster__run_id" {+ type = "String"+ alias = "CAST(log_comment.`dagster.run_id`, 'String')"+ }+ column "lc_dagster__owner" {+ type = "String"+ alias = "CAST(log_comment.`dagster.tags.owner`, 'String')"+ }+ column "lc_modifiers" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "sharded_query_log_archive"+ }+ }++ table "writable_query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "query_log_archive_buffer"+ }+ }++ materialized_view "kafka_logs34_avro_mv" {+ to_table = "posthog.logs34"+ query = <<SQL+SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avro+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "Int64"+ }+ column "_bytes_uncompressed" {+ type = "Nullable(Int64)"+ }+ column "_bytes_compressed" {+ type = "Nullable(Int64)"+ }+ }++ materialized_view "kafka_logs_avro_billing_metrics_mv" {+ to_table = "posthog.logs_billing_metrics"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(floor(_bytes_uncompressed / _record_count)) AS bytes_uncompressed,+ sumSimpleState(floor(_bytes_compressed / _record_count)) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_name+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "kafka_logs_avro_kafka_metrics_mv" {+ to_table = "posthog.logs_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ materialized_view "kafka_metrics_avro_kafka_metrics_mv" {+ to_table = "posthog.metrics_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ materialized_view "kafka_metrics_avro_mv" {+ to_table = "posthog.metrics1"+ query = <<SQL+SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "metric_name" {+ type = "String"+ }+ column "metric_type" {+ type = "String"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "String"+ }+ column "aggregation_temporality" {+ type = "String"+ }+ column "is_monotonic" {+ type = "UInt8"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "attributes_map_float" {+ type = "Map(String, Nullable(Float64))"+ }+ column "team_id" {+ type = "Int32"+ }+ }++ materialized_view "logs34_to_log_attributes" {+ to_table = "posthog.log_attributes2"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "logs34_to_resource_attributes" {+ to_table = "posthog.log_attributes2"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "metrics1_to_metric_attributes" {+ to_table = "posthog.metric_attributes"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "metrics1_to_resource_attributes" {+ to_table = "posthog.metric_attributes"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "ops_query_log_archive_mv" {+ to_table = "posthog.writable_query_log_archive"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL++ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "String"+ }+ column "ProfileEvents" {+ type = "Map(LowCardinality(String), UInt64)"+ }+ }++ view "custom_metrics" {+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL++ }++ view "custom_metrics_backups" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL++ }++ view "custom_metrics_dictionaries" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL++ }++ view "custom_metrics_part_counts" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL++ }++ view "custom_metrics_replication_queue" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL++ }++ view "custom_metrics_server_crash" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL++ }++ view "custom_metrics_table_sizes" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL++ }++ view "custom_metrics_test" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL++ }+}diff --git a/posthog/clickhouse/hcl/ops/golden/dev-ops.hcl b/posthog/clickhouse/hcl/golden/dev-ops.hclsimilarity index 83%rename from posthog/clickhouse/hcl/ops/golden/dev-ops.hclrename to posthog/clickhouse/hcl/golden/dev-ops.hclindex e7e5ff528a7a..2c579b165ce4 100644--- a/posthog/clickhouse/hcl/ops/golden/dev-ops.hcl+++ b/posthog/clickhouse/hcl/golden/dev-ops.hcl@@ -1,13 +1,3 @@-node "dev-us-iad-ch-1a-ops" {- macros = {- cluster = "ops"- hostClusterRole = "ops"- hostClusterType = "offline"- replica = "a"- shard = "1"- }-}-database "posthog" {table "events_team_daily_stats" {order_by = ["analysis_date", "team_id", "event"]@@ -1234,7 +1224,43 @@ database "posthog" {materialized_view "ops_query_log_archive_mv" {to_table = "posthog.writable_query_log_archive"- query = "SELECT hostname, user, query_id, initial_query_id, is_initial_query, type, event_date, event_time, event_time_microseconds, query_start_time, query_start_time_microseconds, query_duration_ms, read_rows, read_bytes, written_rows, written_bytes, result_rows, result_bytes, memory_usage, peak_threads_usage, current_database, query, formatted_query, normalized_query_hash, query_kind, exception_code, exception, stack_trace, JSONExtractInt(log_comment, 'team_id') AS team_id, if(isValidJSON(log_comment), log_comment, '{}') AS log_comment, ProfileEvents FROM system.query_log WHERE type != 'QueryStart'"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL+column "hostname" {type = "LowCardinality(String)"}@@ -1331,38 +1357,256 @@ database "posthog" {}view "custom_metrics" {- query = "SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_test UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_replication_queue UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_server_crash UNION ALL SELECT * FROM posthog.custom_metrics_table_sizes UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_part_counts UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_dictionaries UNION ALL SELECT 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name, map('instance', hostname(), 'disk', disk_name) AS labels, toFloat64(sum(bytes_on_disk)) AS value, 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help, 'gauge' AS type FROM system.parts WHERE disk_name IN ('s3disk', 'cache') GROUP BY disk_name UNION ALL SELECT 'ClickHouseCustomMetric_MergeFailures15m' AS name, map('instance', hostname()) AS labels, toFloat64(count()) AS value, 'Number of failed merge operations in the last 15 minutes' AS help, 'gauge' AS type FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) UNION ALL SELECT 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name, map('instance', hostname()) AS labels, toFloat64(max(cnt)) AS value, 'Max failed merge retries for any single table in the last 15 minutes' AS help, 'gauge' AS type FROM (SELECT count() AS cnt FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) GROUP BY database, `table`, partition_id)"+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL+}view "custom_metrics_backups" {- query = "WITH ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names, [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values, ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions, ['gauge', 'gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.backup_log WHERE event_date = today() GROUP BY event_date"+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL+}view "custom_metrics_dictionaries" {- query = "SELECT 'ClickHouseCustomMetric_DictionariesFailed' AS name, map('instance', hostname(), 'database', d.database, 'dictionary', d.dict_name, 'uuid', toString(d.uuid), 'status', toString(d.status)) AS labels, toUInt64(1) AS value, 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help, 'gauge' AS type FROM (SELECT name AS dict_name, database, uuid, status FROM system.dictionaries WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')) AS d"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL+}view "custom_metrics_part_counts" {- query = "SELECT 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name, map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels, part_count AS value, 'Maximum number of active parts for any partition in a PostHog table' AS help, 'gauge' AS type FROM (SELECT database, `table`, partition, count() AS part_count FROM system.parts WHERE active AND (database = 'posthog') GROUP BY database, `table`, partition ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC LIMIT 1 BY database, `table`)"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL+}view "custom_metrics_replication_queue" {- query = "WITH ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names, [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values, ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions, ['gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('table', `table`, 'instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.replication_queue GROUP BY `table` HAVING value > 0"+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL+}view "custom_metrics_server_crash" {- query = "SELECT 'ClickHouseCustomMetric_ServerCrash' AS name, map('instance', hostname()) AS labels, count() AS value, 'Number of server crashes for current date' AS help, 'gauge' AS type FROM system.crash_log WHERE event_date = today() GROUP BY hostname()"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL+}view "custom_metrics_table_sizes" {- query = "SELECT 'ClickHouseCustomMetric_TableTotalBytes' AS name, map('instance', hostname(), 'database', database, 'table', `table`) AS labels, CAST(total_bytes, 'Float64') AS value, 'Size of a database table on a given node (need a sum for sharded)' AS help, 'gauge' AS type FROM system.tables WHERE (database NOT IN ('INFORMATION_SCHEMA', 'information_schema')) AND (total_bytes IS NOT NULL)"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL+}view "custom_metrics_test" {- query = "SELECT 'ClickHouseCustomMetric_Test' AS name, map('instance', hostname()) AS labels, 1 AS value, 'Test to check that the metric endpoint is working' AS help, 'gauge' AS type"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL+}view "daily_aggregated_query_log_archive" {- query = "SELECT event_date AS day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label, count() AS query_count, sum(read_bytes) AS read_bytes, sum(read_rows) AS read_rows, sum(query_duration_ms) AS query_duration_ms, sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds, countIf(exception_code != 0) AS error_count, countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count FROM posthog.sharded_query_log_archive WHERE is_initial_query AND (event_date < today()) GROUP BY day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label"+ query = <<SQL+SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label+SQL+}}diff --git a/posthog/clickhouse/hcl/ops/base/ops.hcl b/posthog/clickhouse/hcl/golden/local-ops.hclsimilarity index 80%rename from posthog/clickhouse/hcl/ops/base/ops.hclrename to posthog/clickhouse/hcl/golden/local-ops.hclindex 27ca3ef84248..fa45b275627d 100644--- a/posthog/clickhouse/hcl/ops/base/ops.hcl+++ b/posthog/clickhouse/hcl/golden/local-ops.hcl@@ -1,6 +1,3 @@-# OPS base layer — query_log_archive data path + ops-owned tables/views (all envs)-#-# Declarative source of truth for the OPS ClickHouse cluster.database "posthog" {table "events_team_daily_stats" {order_by = ["analysis_date", "team_id", "event"]@@ -54,6 +51,7 @@ database "posthog" {replica_name = "{replica}"}}+table "query_log_archive" {column "hostname" {type = "LowCardinality(String)"@@ -402,6 +400,7 @@ database "posthog" {remote_table = "sharded_query_log_archive"}}+table "query_log_archive_buffer" {column "hostname" {type = "LowCardinality(String)"@@ -508,6 +507,7 @@ database "posthog" {max_bytes = 100000000}}+table "sharded_query_log_archive" {order_by = ["team_id", "event_date", "event_time", "query_id"]partition_by = "toYYYYMM(event_date)"@@ -862,6 +862,7 @@ database "posthog" {replica_name = "{replica}-{shard}"}}+table "writable_query_log_archive" {column "hostname" {type = "LowCardinality(String)"@@ -962,9 +963,46 @@ database "posthog" {remote_table = "query_log_archive_buffer"}}+materialized_view "ops_query_log_archive_mv" {to_table = "posthog.writable_query_log_archive"- query = "SELECT hostname, user, query_id, initial_query_id, is_initial_query, type, event_date, event_time, event_time_microseconds, query_start_time, query_start_time_microseconds, query_duration_ms, read_rows, read_bytes, written_rows, written_bytes, result_rows, result_bytes, memory_usage, peak_threads_usage, current_database, query, formatted_query, normalized_query_hash, query_kind, exception_code, exception, stack_trace, JSONExtractInt(log_comment, 'team_id') AS team_id, if(isValidJSON(log_comment), log_comment, '{}') AS log_comment, ProfileEvents FROM system.query_log WHERE type != 'QueryStart'"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL+column "hostname" {type = "LowCardinality(String)"}@@ -1059,7 +1097,258 @@ database "posthog" {type = "Map(LowCardinality(String), UInt64)"}}++ view "custom_metrics" {+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL++ }++ view "custom_metrics_backups" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL++ }++ view "custom_metrics_dictionaries" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL++ }++ view "custom_metrics_part_counts" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL++ }++ view "custom_metrics_replication_queue" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL++ }++ view "custom_metrics_server_crash" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL++ }++ view "custom_metrics_table_sizes" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL++ }++ view "custom_metrics_test" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL++ }+view "daily_aggregated_query_log_archive" {- query = "SELECT event_date AS day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label, count() AS query_count, sum(read_bytes) AS read_bytes, sum(read_rows) AS read_rows, sum(query_duration_ms) AS query_duration_ms, sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds, countIf(exception_code != 0) AS error_count, countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count FROM posthog.sharded_query_log_archive WHERE is_initial_query AND (event_date < today()) GROUP BY day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label"+ query = <<SQL+SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label+SQL+}}diff --git a/posthog/clickhouse/hcl/golden/prod-eu-logs.hcl b/posthog/clickhouse/hcl/golden/prod-eu-logs.hclnew file mode 100644index 000000000000..d1fad006a2ec--- /dev/null+++ b/posthog/clickhouse/hcl/golden/prod-eu-logs.hcl@@ -0,0 +1,3049 @@+database "posthog" {+ table "kafka_logs_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "bytes_uncompressed" {+ type = "Int64"+ }+ engine "kafka" {+ broker_list = "warpstream_logs"+ topic_list = "kafka_topic_list = 'clickhouse_logs'"+ group_name = "kafka_group_name = 'clickhouse-logs-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "kafka_metrics_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Nullable(Int32)"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "Nullable(String)"+ }+ column "metric_name" {+ type = "Nullable(String)"+ }+ column "metric_type" {+ type = "Nullable(String)"+ }+ column "value" {+ type = "Nullable(Float64)"+ }+ column "count" {+ type = "Nullable(Int64)"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(Int64)"+ }+ column "unit" {+ type = "Nullable(String)"+ }+ column "aggregation_temporality" {+ type = "Nullable(String)"+ }+ column "is_monotonic" {+ type = "Nullable(UInt8)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "Nullable(String)"+ }+ column "attributes" {+ type = "Map(String, String)"+ }+ engine "kafka" {+ broker_list = "warpstream_metrics"+ topic_list = "kafka_topic_list = 'clickhouse_metrics'"+ group_name = "kafka_group_name = 'clickhouse-metrics-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "kafka_trace_spans_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int32"+ }+ column "flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "Int32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "Int32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "Int32"+ }+ column "status_code" {+ type = "Int32"+ }+ engine "kafka" {+ broker_list = "warpstream_traces"+ topic_list = "kafka_topic_list = 'clickhouse_traces'"+ group_name = "kafka_group_name = 'clickhouse-traces-avro'"+ format = "kafka_format = 'Avro'"+ num_consumers = 2+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "log_attributes2" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ ttl = "time_bucket + toIntervalDay(15)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/log_attributes34"+ replica_name = "{replica}"+ }+ }++ table "log_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "log_attributes2"+ }+ }++ table "logs34" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "severity_text", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ add_minmax_index_for_numeric_columns = "1"+ allow_experimental_reverse_key = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ storage_policy = "s3_tiered"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_severity_text_set" {+ expr = "severity_text"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_mat_body_ipv4_matches" {+ expr = "mat_body_ipv4_matches"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_body_ngram3" {+ expr = "lower(body)"+ type = "ngrambf_v1(3, 25000, 2, 0)"+ granularity = 1+ }+ index "idx_uuid_bloom" {+ expr = "uuid"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.logs34"+ replica_name = "{replica}"+ }+ }++ table "logs_billing_metrics" {+ order_by = ["team_id", "time_bucket", "service_name"]+ partition_by = "toYYYYMM(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_billing_metrics"+ replica_name = "{replica}"+ }+ }++ table "logs_billing_metrics_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_billing_metrics"+ }+ }++ table "logs_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs34"+ }+ }++ table "logs_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "logs_kafka_metrics_distributed" {+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_kafka_metrics"+ }+ }++ table "metric_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metric_attributes"+ replica_name = "{replica}"+ }+ }++ table "metrics" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "metrics1"+ }+ }++ table "metrics1" {+ order_by = ["team_id", "time_bucket", "service_name", "metric_name", "resource_fingerprint", "timestamp"]+ partition_by = "toDate(timestamp)"+ settings = {+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ index "idx_metric_name_set" {+ expr = "metric_name"+ type = "set(100)"+ granularity = 1+ }+ index "idx_metric_type_set" {+ expr = "metric_type"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics1"+ replica_name = "{replica}"+ }+ }++ table "metrics_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ column "exception_name" {+ type = "String"+ alias = "errorCodeToName(exception_code)"+ }+ column "ProfileEvents_RealTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['RealTimeMicroseconds']"+ }+ column "ProfileEvents_OSCPUVirtualTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['OSCPUVirtualTimeMicroseconds']"+ }+ column "ProfileEvents_S3Clients" {+ type = "Int64"+ alias = "ProfileEvents['S3Clients']"+ }+ column "ProfileEvents_S3DeleteObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3DeleteObjects']"+ }+ column "ProfileEvents_S3CopyObject" {+ type = "Int64"+ alias = "ProfileEvents['S3CopyObject']"+ }+ column "ProfileEvents_S3ListObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3ListObjects']"+ }+ column "ProfileEvents_S3HeadObject" {+ type = "Int64"+ alias = "ProfileEvents['S3HeadObject']"+ }+ column "ProfileEvents_S3GetObjectAttributes" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObjectAttributes']"+ }+ column "ProfileEvents_S3CreateMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CreateMultipartUpload']"+ }+ column "ProfileEvents_S3UploadPartCopy" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPartCopy']"+ }+ column "ProfileEvents_S3UploadPart" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPart']"+ }+ column "ProfileEvents_S3AbortMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3AbortMultipartUpload']"+ }+ column "ProfileEvents_S3CompleteMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CompleteMultipartUpload']"+ }+ column "ProfileEvents_S3PutObject" {+ type = "Int64"+ alias = "ProfileEvents['S3PutObject']"+ }+ column "ProfileEvents_S3GetObject" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObject']"+ }+ column "ProfileEvents_ReadBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['ReadBufferFromS3Bytes']"+ }+ column "ProfileEvents_WriteBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['WriteBufferFromS3Bytes']"+ }+ column "lc_workflow" {+ type = "LowCardinality(String)"+ alias = "log_comment.workflow"+ }+ column "lc_kind" {+ type = "LowCardinality(String)"+ alias = "log_comment.kind"+ }+ column "lc_id" {+ type = "String"+ alias = "CAST(log_comment.id, 'String')"+ }+ column "lc_route_id" {+ type = "String"+ alias = "CAST(log_comment.route_id, 'String')"+ }+ column "lc_access_method" {+ type = "LowCardinality(String)"+ alias = "log_comment.access_method"+ }+ column "lc_api_key_label" {+ type = "String"+ alias = "CAST(log_comment.api_key_label, 'String')"+ }+ column "lc_api_key_mask" {+ type = "String"+ alias = "CAST(log_comment.api_key_mask, 'String')"+ }+ column "lc_query_type" {+ type = "LowCardinality(String)"+ alias = "log_comment.query_type"+ }+ column "lc_product" {+ type = "LowCardinality(String)"+ alias = "log_comment.product"+ }+ column "lc_chargeable" {+ type = "Bool"+ alias = "log_comment.chargeable"+ }+ column "lc_name" {+ type = "String"+ alias = "CAST(log_comment.name, 'String')"+ }+ column "lc_request_name" {+ type = "String"+ alias = "CAST(log_comment.request_name, 'String')"+ }+ column "lc_client_query_id" {+ type = "String"+ alias = "CAST(log_comment.client_query_id, 'String')"+ }+ column "lc_org_id" {+ type = "String"+ alias = "CAST(log_comment.org_id, 'String')"+ }+ column "lc_user_id" {+ type = "Int64"+ alias = "log_comment.user_id"+ }+ column "lc_is_impersonated" {+ type = "Bool"+ alias = "log_comment.is_impersonated"+ }+ column "lc_session_id" {+ type = "String"+ alias = "CAST(log_comment.session_id, 'String')"+ }+ column "lc_dashboard_id" {+ type = "Int64"+ alias = "log_comment.dashboard_id"+ }+ column "lc_insight_id" {+ type = "Int64"+ alias = "log_comment.insight_id"+ }+ column "lc_cohort_id" {+ type = "Int64"+ alias = "log_comment.cohort_id"+ }+ column "lc_batch_export_id" {+ type = "String"+ alias = "CAST(log_comment.batch_export_id, 'String')"+ }+ column "lc_experiment_id" {+ type = "Int64"+ alias = "log_comment.experiment_id"+ }+ column "lc_experiment_feature_flag_key" {+ type = "String"+ alias = "CAST(log_comment.experiment_feature_flag_key, 'String')"+ }+ column "lc_alert_config_id" {+ type = "String"+ alias = "CAST(log_comment.alert_config_id, 'String')"+ }+ column "lc_feature" {+ type = "LowCardinality(String)"+ alias = "log_comment.feature"+ }+ column "lc_table_id" {+ type = "String"+ alias = "CAST(log_comment.table_id, 'String')"+ }+ column "lc_warehouse_query" {+ type = "Bool"+ alias = "log_comment.warehouse_query"+ }+ column "lc_person_on_events_mode" {+ type = "LowCardinality(String)"+ alias = "log_comment.person_on_events_mode"+ }+ column "lc_service_name" {+ type = "String"+ alias = "CAST(log_comment.service_name, 'String')"+ }+ column "lc_workload" {+ type = "LowCardinality(String)"+ alias = "log_comment.workload"+ }+ column "lc_query__kind" {+ type = "LowCardinality(String)"+ alias = "if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind'))"+ }+ column "lc_query__query" {+ type = "String"+ alias = "multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query'))"+ }+ column "lc_query" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), '')"+ }+ column "lc_temporal__workflow_namespace" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_namespace`, 'String')"+ }+ column "lc_temporal__workflow_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_type`, 'String')"+ }+ column "lc_temporal__workflow_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_id`, 'String')"+ }+ column "lc_temporal__workflow_run_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_run_id`, 'String')"+ }+ column "lc_temporal__activity_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_type`, 'String')"+ }+ column "lc_temporal__activity_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_id`, 'String')"+ }+ column "lc_temporal__attempt" {+ type = "Int64"+ alias = "log_comment.`temporal.attempt`"+ }+ column "lc_dagster__job_name" {+ type = "String"+ alias = "CAST(log_comment.`dagster.job_name`, 'String')"+ }+ column "lc_dagster__run_id" {+ type = "String"+ alias = "CAST(log_comment.`dagster.run_id`, 'String')"+ }+ column "lc_dagster__owner" {+ type = "String"+ alias = "CAST(log_comment.`dagster.tags.owner`, 'String')"+ }+ column "lc_modifiers" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "sharded_query_log_archive"+ }+ }++ table "trace_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(original_expiry_time_bucket)"+ ttl = "original_expiry_time_bucket"+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_attributes"+ replica_name = "{replica}"+ }+ }++ table "trace_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_attributes"+ }+ }++ table "trace_spans" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "status_code", "name", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ allow_part_offset_column_in_projections = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_name" {+ expr = "name"+ type = "ngrambf_v1(4, 5000, 2, 0)"+ granularity = 16+ }+ index "idx_kind" {+ expr = "kind"+ type = "minmax"+ granularity = 4+ }+ index "idx_duration" {+ expr = "duration_nano"+ type = "minmax"+ granularity = 1+ }+ index "idx_status_code" {+ expr = "status_code"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 16+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 16+ }+ index "idx_trace_bloom_part" {+ expr = "trace_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ index "idx_span_id_bloom_part" {+ expr = "span_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_spans"+ replica_name = "{replica}"+ }+ }++ table "trace_spans_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_spans"+ }+ }++ table "writable_query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "query_log_archive_buffer"+ }+ }++ materialized_view "kafka_logs34_avro_mv" {+ to_table = "posthog.logs34"+ query = <<SQL+SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes, bytes_uncompressed),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avro+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "Int64"+ }+ column "_bytes_uncompressed" {+ type = "Nullable(Int64)"+ }+ column "_bytes_compressed" {+ type = "Nullable(Int64)"+ }+ }++ materialized_view "kafka_logs_avro_billing_metrics_mv" {+ to_table = "posthog.logs_billing_metrics"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(_bytes_uncompressed) AS bytes_uncompressed,+ sumSimpleState(_bytes_compressed) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_name+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "kafka_logs_avro_kafka_metrics_mv" {+ to_table = "posthog.logs_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ materialized_view "kafka_metrics_avro_kafka_metrics_mv" {+ to_table = "posthog.metrics_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ materialized_view "kafka_metrics_avro_mv" {+ to_table = "posthog.metrics1"+ query = <<SQL+SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "metric_name" {+ type = "String"+ }+ column "metric_type" {+ type = "String"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "String"+ }+ column "aggregation_temporality" {+ type = "String"+ }+ column "is_monotonic" {+ type = "UInt8"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "attributes_map_float" {+ type = "Map(String, Nullable(Float64))"+ }+ column "team_id" {+ type = "Int32"+ }+ }++ materialized_view "kafka_trace_spans_avro_mv" {+ to_table = "posthog.trace_spans"+ query = <<SQL+SELECT+ * EXCEPT(attributes, resource_attributes, kind, flags, dropped_attributes_count, dropped_events_count, dropped_links_count, status_code),+ toInt8(kind) AS kind,+ toUInt32(flags) AS flags,+ toUInt32(dropped_attributes_count) AS dropped_attributes_count,+ toUInt32(dropped_events_count) AS dropped_events_count,+ toUInt32(dropped_links_count) AS dropped_links_count,+ toInt16(status_code) AS status_code,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) AS _bytes_compressed+FROM posthog.kafka_trace_spans_avro+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "status_code" {+ type = "Int16"+ }+ column "team_id" {+ type = "Int32"+ }+ }++ materialized_view "logs34_to_log_attributes" {+ to_table = "posthog.log_attributes2"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "logs34_to_resource_attributes" {+ to_table = "posthog.log_attributes2"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "metrics1_to_metric_attributes" {+ to_table = "posthog.metric_attributes"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "metrics1_to_resource_attributes" {+ to_table = "posthog.metric_attributes"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "ops_query_log_archive_mv" {+ to_table = "posthog.writable_query_log_archive"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL++ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "String"+ }+ column "ProfileEvents" {+ type = "Map(LowCardinality(String), UInt64)"+ }+ }++ materialized_view "trace_span_to_attributes" {+ to_table = "posthog.trace_attributes"+ query = <<SQL+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "trace_span_to_resource_attributes" {+ to_table = "posthog.trace_attributes"+ query = <<SQL+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_resource_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "trace_span_to_span_attributes" {+ to_table = "posthog.trace_attributes"+ query = <<SQL+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ 'name' AS attribute_key,+ name AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, name+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ view "custom_metrics" {+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL++ }++ view "custom_metrics_backups" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL++ }++ view "custom_metrics_dictionaries" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL++ }++ view "custom_metrics_part_counts" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL++ }++ view "custom_metrics_replication_queue" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL++ }++ view "custom_metrics_server_crash" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL++ }++ view "custom_metrics_table_sizes" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL++ }++ view "custom_metrics_test" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL++ }+}diff --git a/posthog/clickhouse/hcl/ops/golden/prod-eu-ops.hcl b/posthog/clickhouse/hcl/golden/prod-eu-ops.hclsimilarity index 84%rename from posthog/clickhouse/hcl/ops/golden/prod-eu-ops.hclrename to posthog/clickhouse/hcl/golden/prod-eu-ops.hclindex 0310b5587ea5..1e577ffc538f 100644--- a/posthog/clickhouse/hcl/ops/golden/prod-eu-ops.hcl+++ b/posthog/clickhouse/hcl/golden/prod-eu-ops.hcl@@ -1,13 +1,3 @@-node "prod-eu-fra-ch-1a-ops" {- macros = {- cluster = "ops"- hostClusterRole = "ops"- hostClusterType = "offline"- replica = "a"- shard = "1"- }-}-database "posthog" {table "events_main" {column "uuid" {@@ -1274,7 +1264,17 @@ database "posthog" {materialized_view "metrics_label_index_from_series_mv" {to_table = "posthog.metrics_label_index"- query = "SELECT team_id, metric_name, tupleElement(label_pair, 1) AS label_name, tupleElement(label_pair, 2) AS label_value, id FROM posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair"+ query = <<SQL+SELECT+ team_id,+ metric_name,+ tupleElement(label_pair, 1) AS label_name,+ tupleElement(label_pair, 2) AS label_value,+ id+FROM+ posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair+SQL+column "team_id" {type = "UInt64"}@@ -1294,7 +1294,43 @@ database "posthog" {materialized_view "ops_query_log_archive_mv" {to_table = "posthog.writable_query_log_archive"- query = "SELECT hostname, user, query_id, initial_query_id, is_initial_query, type, event_date, event_time, event_time_microseconds, query_start_time, query_start_time_microseconds, query_duration_ms, read_rows, read_bytes, written_rows, written_bytes, result_rows, result_bytes, memory_usage, peak_threads_usage, current_database, query, formatted_query, normalized_query_hash, query_kind, exception_code, exception, stack_trace, JSONExtractInt(log_comment, 'team_id') AS team_id, if(isValidJSON(log_comment), log_comment, '{}') AS log_comment, ProfileEvents FROM system.query_log WHERE type != 'QueryStart'"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL+column "hostname" {type = "LowCardinality(String)"}@@ -1391,38 +1427,256 @@ database "posthog" {}view "custom_metrics" {- query = "SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_test UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_replication_queue UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_server_crash UNION ALL SELECT * FROM posthog.custom_metrics_table_sizes UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_part_counts UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_dictionaries UNION ALL SELECT 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name, map('instance', hostname(), 'disk', disk_name) AS labels, toFloat64(sum(bytes_on_disk)) AS value, 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help, 'gauge' AS type FROM system.parts WHERE disk_name IN ('s3disk', 'cache') GROUP BY disk_name UNION ALL SELECT 'ClickHouseCustomMetric_MergeFailures15m' AS name, map('instance', hostname()) AS labels, toFloat64(count()) AS value, 'Number of failed merge operations in the last 15 minutes' AS help, 'gauge' AS type FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) UNION ALL SELECT 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name, map('instance', hostname()) AS labels, toFloat64(max(cnt)) AS value, 'Max failed merge retries for any single table in the last 15 minutes' AS help, 'gauge' AS type FROM (SELECT count() AS cnt FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) GROUP BY database, `table`, partition_id)"+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL+}view "custom_metrics_backups" {- query = "WITH ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names, [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values, ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions, ['gauge', 'gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.backup_log WHERE event_date = today() GROUP BY event_date"+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL+}view "custom_metrics_dictionaries" {- query = "SELECT 'ClickHouseCustomMetric_DictionariesFailed' AS name, map('instance', hostname(), 'database', d.database, 'dictionary', d.dict_name, 'uuid', toString(d.uuid), 'status', toString(d.status)) AS labels, toUInt64(1) AS value, 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help, 'gauge' AS type FROM (SELECT name AS dict_name, database, uuid, status FROM system.dictionaries WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')) AS d"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL+}view "custom_metrics_part_counts" {- query = "SELECT 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name, map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels, part_count AS value, 'Maximum number of active parts for any partition in a PostHog table' AS help, 'gauge' AS type FROM (SELECT database, `table`, partition, count() AS part_count FROM system.parts WHERE active AND (database = 'posthog') GROUP BY database, `table`, partition ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC LIMIT 1 BY database, `table`)"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL+}view "custom_metrics_replication_queue" {- query = "WITH ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names, [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values, ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions, ['gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('table', `table`, 'instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.replication_queue GROUP BY `table` HAVING value > 0"+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL+}view "custom_metrics_server_crash" {- query = "SELECT 'ClickHouseCustomMetric_ServerCrash' AS name, map('instance', hostname()) AS labels, count() AS value, 'Number of server crashes for current date' AS help, 'gauge' AS type FROM system.crash_log WHERE event_date = today() GROUP BY hostname()"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL+}view "custom_metrics_table_sizes" {- query = "SELECT 'ClickHouseCustomMetric_TableTotalBytes' AS name, map('instance', hostname(), 'database', database, 'table', `table`) AS labels, CAST(total_bytes, 'Float64') AS value, 'Size of a database table on a given node (need a sum for sharded)' AS help, 'gauge' AS type FROM system.tables WHERE (database NOT IN ('INFORMATION_SCHEMA', 'information_schema')) AND (total_bytes IS NOT NULL)"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL+}view "custom_metrics_test" {- query = "SELECT 'ClickHouseCustomMetric_Test' AS name, map('instance', hostname()) AS labels, 1 AS value, 'Test to check that the metric endpoint is working' AS help, 'gauge' AS type"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL+}view "daily_aggregated_query_log_archive" {- query = "SELECT event_date AS day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label, count() AS query_count, sum(read_bytes) AS read_bytes, sum(read_rows) AS read_rows, sum(query_duration_ms) AS query_duration_ms, sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds, countIf(exception_code != 0) AS error_count, countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count FROM posthog.sharded_query_log_archive WHERE is_initial_query AND (event_date < today()) GROUP BY day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label"+ query = <<SQL+SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label+SQL+}}diff --git a/posthog/clickhouse/hcl/golden/prod-us-logs.hcl b/posthog/clickhouse/hcl/golden/prod-us-logs.hclnew file mode 100644index 000000000000..f3a9566fc448--- /dev/null+++ b/posthog/clickhouse/hcl/golden/prod-us-logs.hcl@@ -0,0 +1,3103 @@+database "posthog" {+ table "kafka_logs_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ engine "kafka" {+ broker_list = "warpstream_logs"+ topic_list = "kafka_topic_list = 'clickhouse_logs'"+ group_name = "kafka_group_name = 'clickhouse-logs-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 32+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "kafka_metrics_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Nullable(Int32)"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "Nullable(String)"+ }+ column "metric_name" {+ type = "Nullable(String)"+ }+ column "metric_type" {+ type = "Nullable(String)"+ }+ column "value" {+ type = "Nullable(Float64)"+ }+ column "count" {+ type = "Nullable(Int64)"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(Int64)"+ }+ column "unit" {+ type = "Nullable(String)"+ }+ column "aggregation_temporality" {+ type = "Nullable(String)"+ }+ column "is_monotonic" {+ type = "Nullable(UInt8)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "Nullable(String)"+ }+ column "attributes" {+ type = "Map(String, String)"+ }+ engine "kafka" {+ broker_list = "warpstream_metrics"+ topic_list = "kafka_topic_list = 'clickhouse_metrics'"+ group_name = "kafka_group_name = 'clickhouse-metrics-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "kafka_trace_spans_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int32"+ }+ column "flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "Int32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "Int32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "Int32"+ }+ column "status_code" {+ type = "Int32"+ }+ engine "kafka" {+ broker_list = "warpstream_traces"+ topic_list = "kafka_topic_list = 'clickhouse_traces'"+ group_name = "kafka_group_name = 'clickhouse-traces-avro'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }++ table "log_attributes2" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ ttl = "time_bucket + toIntervalDay(15)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/log_attributes34"+ replica_name = "{replica}"+ }+ }++ table "log_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "log_attributes2"+ }+ }++ table "logs34" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "severity_text", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ add_minmax_index_for_numeric_columns = "1"+ allow_experimental_reverse_key = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_buckets_strategy = "constant"+ map_serialization_version = "with_buckets"+ max_buckets_in_map = "32"+ storage_policy = "s3_tiered"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_severity_text_set" {+ expr = "severity_text"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_mat_body_ipv4_matches" {+ expr = "mat_body_ipv4_matches"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_body_ngram3" {+ expr = "lower(body)"+ type = "ngrambf_v1(3, 25000, 2, 0)"+ granularity = 1+ }+ index "idx_uuid_bloom" {+ expr = "uuid"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.logs34"+ replica_name = "{replica}"+ }+ }++ table "logs_billing_metrics" {+ order_by = ["team_id", "time_bucket", "service_name"]+ partition_by = "toYYYYMM(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_billing_metrics"+ replica_name = "{replica}"+ }+ }++ table "logs_billing_metrics_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_billing_metrics"+ }+ }++ table "logs_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs34"+ }+ }++ table "logs_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "logs_kafka_metrics_distributed" {+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_kafka_metrics"+ }+ }++ table "metric_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metric_attributes"+ replica_name = "{replica}"+ }+ }++ table "metrics" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "metrics1"+ }+ }++ table "metrics1" {+ order_by = ["team_id", "time_bucket", "service_name", "metric_name", "resource_fingerprint", "timestamp"]+ partition_by = "toDate(timestamp)"+ settings = {+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ index "idx_metric_name_set" {+ expr = "metric_name"+ type = "set(100)"+ granularity = 1+ }+ index "idx_metric_type_set" {+ expr = "metric_type"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics1"+ replica_name = "{replica}"+ }+ }++ table "metrics_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ column "exception_name" {+ type = "String"+ alias = "errorCodeToName(exception_code)"+ }+ column "ProfileEvents_RealTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['RealTimeMicroseconds']"+ }+ column "ProfileEvents_OSCPUVirtualTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['OSCPUVirtualTimeMicroseconds']"+ }+ column "ProfileEvents_S3Clients" {+ type = "Int64"+ alias = "ProfileEvents['S3Clients']"+ }+ column "ProfileEvents_S3DeleteObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3DeleteObjects']"+ }+ column "ProfileEvents_S3CopyObject" {+ type = "Int64"+ alias = "ProfileEvents['S3CopyObject']"+ }+ column "ProfileEvents_S3ListObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3ListObjects']"+ }+ column "ProfileEvents_S3HeadObject" {+ type = "Int64"+ alias = "ProfileEvents['S3HeadObject']"+ }+ column "ProfileEvents_S3GetObjectAttributes" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObjectAttributes']"+ }+ column "ProfileEvents_S3CreateMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CreateMultipartUpload']"+ }+ column "ProfileEvents_S3UploadPartCopy" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPartCopy']"+ }+ column "ProfileEvents_S3UploadPart" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPart']"+ }+ column "ProfileEvents_S3AbortMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3AbortMultipartUpload']"+ }+ column "ProfileEvents_S3CompleteMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CompleteMultipartUpload']"+ }+ column "ProfileEvents_S3PutObject" {+ type = "Int64"+ alias = "ProfileEvents['S3PutObject']"+ }+ column "ProfileEvents_S3GetObject" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObject']"+ }+ column "ProfileEvents_ReadBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['ReadBufferFromS3Bytes']"+ }+ column "ProfileEvents_WriteBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['WriteBufferFromS3Bytes']"+ }+ column "lc_workflow" {+ type = "LowCardinality(String)"+ alias = "log_comment.workflow"+ }+ column "lc_kind" {+ type = "LowCardinality(String)"+ alias = "log_comment.kind"+ }+ column "lc_id" {+ type = "String"+ alias = "CAST(log_comment.id, 'String')"+ }+ column "lc_route_id" {+ type = "String"+ alias = "CAST(log_comment.route_id, 'String')"+ }+ column "lc_access_method" {+ type = "LowCardinality(String)"+ alias = "log_comment.access_method"+ }+ column "lc_api_key_label" {+ type = "String"+ alias = "CAST(log_comment.api_key_label, 'String')"+ }+ column "lc_api_key_mask" {+ type = "String"+ alias = "CAST(log_comment.api_key_mask, 'String')"+ }+ column "lc_query_type" {+ type = "LowCardinality(String)"+ alias = "log_comment.query_type"+ }+ column "lc_product" {+ type = "LowCardinality(String)"+ alias = "log_comment.product"+ }+ column "lc_chargeable" {+ type = "Bool"+ alias = "log_comment.chargeable"+ }+ column "lc_name" {+ type = "String"+ alias = "CAST(log_comment.name, 'String')"+ }+ column "lc_request_name" {+ type = "String"+ alias = "CAST(log_comment.request_name, 'String')"+ }+ column "lc_client_query_id" {+ type = "String"+ alias = "CAST(log_comment.client_query_id, 'String')"+ }+ column "lc_org_id" {+ type = "String"+ alias = "CAST(log_comment.org_id, 'String')"+ }+ column "lc_user_id" {+ type = "Int64"+ alias = "log_comment.user_id"+ }+ column "lc_is_impersonated" {+ type = "Bool"+ alias = "log_comment.is_impersonated"+ }+ column "lc_session_id" {+ type = "String"+ alias = "CAST(log_comment.session_id, 'String')"+ }+ column "lc_dashboard_id" {+ type = "Int64"+ alias = "log_comment.dashboard_id"+ }+ column "lc_insight_id" {+ type = "Int64"+ alias = "log_comment.insight_id"+ }+ column "lc_cohort_id" {+ type = "Int64"+ alias = "log_comment.cohort_id"+ }+ column "lc_batch_export_id" {+ type = "String"+ alias = "CAST(log_comment.batch_export_id, 'String')"+ }+ column "lc_experiment_id" {+ type = "Int64"+ alias = "log_comment.experiment_id"+ }+ column "lc_experiment_feature_flag_key" {+ type = "String"+ alias = "CAST(log_comment.experiment_feature_flag_key, 'String')"+ }+ column "lc_alert_config_id" {+ type = "String"+ alias = "CAST(log_comment.alert_config_id, 'String')"+ }+ column "lc_feature" {+ type = "LowCardinality(String)"+ alias = "log_comment.feature"+ }+ column "lc_table_id" {+ type = "String"+ alias = "CAST(log_comment.table_id, 'String')"+ }+ column "lc_warehouse_query" {+ type = "Bool"+ alias = "log_comment.warehouse_query"+ }+ column "lc_person_on_events_mode" {+ type = "LowCardinality(String)"+ alias = "log_comment.person_on_events_mode"+ }+ column "lc_service_name" {+ type = "String"+ alias = "CAST(log_comment.service_name, 'String')"+ }+ column "lc_workload" {+ type = "LowCardinality(String)"+ alias = "log_comment.workload"+ }+ column "lc_query__kind" {+ type = "LowCardinality(String)"+ alias = "if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind'))"+ }+ column "lc_query__query" {+ type = "String"+ alias = "multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query'))"+ }+ column "lc_query" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), '')"+ }+ column "lc_temporal__workflow_namespace" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_namespace`, 'String')"+ }+ column "lc_temporal__workflow_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_type`, 'String')"+ }+ column "lc_temporal__workflow_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_id`, 'String')"+ }+ column "lc_temporal__workflow_run_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_run_id`, 'String')"+ }+ column "lc_temporal__activity_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_type`, 'String')"+ }+ column "lc_temporal__activity_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_id`, 'String')"+ }+ column "lc_temporal__attempt" {+ type = "Int64"+ alias = "log_comment.`temporal.attempt`"+ }+ column "lc_dagster__job_name" {+ type = "String"+ alias = "CAST(log_comment.`dagster.job_name`, 'String')"+ }+ column "lc_dagster__run_id" {+ type = "String"+ alias = "CAST(log_comment.`dagster.run_id`, 'String')"+ }+ column "lc_dagster__owner" {+ type = "String"+ alias = "CAST(log_comment.`dagster.tags.owner`, 'String')"+ }+ column "lc_modifiers" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "sharded_query_log_archive"+ }+ }++ table "trace_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(original_expiry_time_bucket)"+ ttl = "original_expiry_time_bucket"+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_attributes"+ replica_name = "{replica}"+ }+ }++ table "trace_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_attributes"+ }+ }++ table "trace_spans" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "status_code", "name", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ allow_part_offset_column_in_projections = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_name" {+ expr = "name"+ type = "ngrambf_v1(4, 5000, 2, 0)"+ granularity = 16+ }+ index "idx_kind" {+ expr = "kind"+ type = "minmax"+ granularity = 4+ }+ index "idx_duration" {+ expr = "duration_nano"+ type = "minmax"+ granularity = 1+ }+ index "idx_status_code" {+ expr = "status_code"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 16+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 16+ }+ index "idx_trace_bloom_part" {+ expr = "trace_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ index "idx_span_id_bloom_part" {+ expr = "span_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_spans"+ replica_name = "{replica}"+ }+ }++ table "trace_spans_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_spans"+ }+ }++ table "trace_spans_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_spans_kafka_metrics"+ replica_name = "{replica}"+ }+ }++ table "writable_query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "query_log_archive_buffer"+ }+ }++ materialized_view "kafka_logs34_avro_mv" {+ to_table = "posthog.logs34"+ query = <<SQL+SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avro+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "Int64"+ }+ column "_bytes_uncompressed" {+ type = "Nullable(Int64)"+ }+ column "_bytes_compressed" {+ type = "Nullable(Int64)"+ }+ }++ materialized_view "kafka_logs_avro_billing_metrics_mv" {+ to_table = "posthog.logs_billing_metrics"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(floor(_bytes_uncompressed / _record_count)) AS bytes_uncompressed,+ sumSimpleState(floor(_bytes_compressed / _record_count)) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_name+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "kafka_logs_avro_kafka_metrics_mv" {+ to_table = "posthog.logs_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ materialized_view "kafka_metrics_avro_kafka_metrics_mv" {+ to_table = "posthog.metrics_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ materialized_view "kafka_metrics_avro_mv" {+ to_table = "posthog.metrics1"+ query = <<SQL+SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "metric_name" {+ type = "String"+ }+ column "metric_type" {+ type = "String"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "String"+ }+ column "aggregation_temporality" {+ type = "String"+ }+ column "is_monotonic" {+ type = "UInt8"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "attributes_map_float" {+ type = "Map(String, Nullable(Float64))"+ }+ column "team_id" {+ type = "Int32"+ }+ }++ materialized_view "kafka_trace_spans_avro_mv" {+ to_table = "posthog.trace_spans"+ query = <<SQL+SELECT+ * EXCEPT(attributes, resource_attributes, kind, flags, dropped_attributes_count, dropped_events_count, dropped_links_count, status_code),+ toInt8(kind) AS kind,+ toUInt32(flags) AS flags,+ toUInt32(dropped_attributes_count) AS dropped_attributes_count,+ toUInt32(dropped_events_count) AS dropped_events_count,+ toUInt32(dropped_links_count) AS dropped_links_count,+ toInt16(status_code) AS status_code,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) AS _bytes_compressed+FROM posthog.kafka_trace_spans_avro+SQL++ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "status_code" {+ type = "Int16"+ }+ column "team_id" {+ type = "Int32"+ }+ }++ materialized_view "logs34_to_log_attributes" {+ to_table = "posthog.log_attributes2"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "logs34_to_resource_attributes" {+ to_table = "posthog.log_attributes2"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "metrics1_to_metric_attributes" {+ to_table = "posthog.metric_attributes"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "metrics1_to_resource_attributes" {+ to_table = "posthog.metric_attributes"+ query = <<SQL+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "ops_query_log_archive_mv" {+ to_table = "posthog.writable_query_log_archive"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL++ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "String"+ }+ column "ProfileEvents" {+ type = "Map(LowCardinality(String), UInt64)"+ }+ }++ materialized_view "trace_span_to_attributes" {+ to_table = "posthog.trace_attributes"+ query = <<SQL+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "trace_span_to_resource_attributes" {+ to_table = "posthog.trace_attributes"+ query = <<SQL+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_resource_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "trace_span_to_span_attributes" {+ to_table = "posthog.trace_attributes"+ query = <<SQL+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ 'name' AS attribute_key,+ name AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, name+ )+SQL++ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }++ materialized_view "trace_spans_to_kafka_metrics_mv" {+ to_table = "posthog.trace_spans_kafka_metrics"+ query = <<SQL+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.trace_spans+GROUP BY+ _partition, _topic+SQL++ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }++ view "custom_metrics" {+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL++ }++ view "custom_metrics_backups" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL++ }++ view "custom_metrics_dictionaries" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL++ }++ view "custom_metrics_part_counts" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL++ }++ view "custom_metrics_replication_queue" {+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL++ }++ view "custom_metrics_server_crash" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL++ }++ view "custom_metrics_table_sizes" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL++ }++ view "custom_metrics_test" {+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL++ }+}diff --git a/posthog/clickhouse/hcl/ops/golden/prod-us-ops.hcl b/posthog/clickhouse/hcl/golden/prod-us-ops.hclsimilarity index 84%rename from posthog/clickhouse/hcl/ops/golden/prod-us-ops.hclrename to posthog/clickhouse/hcl/golden/prod-us-ops.hclindex 234bd36f791b..b8f5e47ccb42 100644--- a/posthog/clickhouse/hcl/ops/golden/prod-us-ops.hcl+++ b/posthog/clickhouse/hcl/golden/prod-us-ops.hcl@@ -1,13 +1,3 @@-node "prod-us-iad-ch-1c-ops" {- macros = {- cluster = "ops"- hostClusterRole = "ops"- hostClusterType = "offline"- replica = "c"- shard = "1"- }-}-database "posthog" {table "events_main" {column "uuid" {@@ -1361,7 +1351,17 @@ database "posthog" {materialized_view "metrics_label_index_from_series_mv" {to_table = "posthog.metrics_label_index"- query = "SELECT team_id, metric_name, tupleElement(label_pair, 1) AS label_name, tupleElement(label_pair, 2) AS label_value, id FROM posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair"+ query = <<SQL+SELECT+ team_id,+ metric_name,+ tupleElement(label_pair, 1) AS label_name,+ tupleElement(label_pair, 2) AS label_value,+ id+FROM+ posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair+SQL+column "team_id" {type = "UInt64"}@@ -1381,7 +1381,43 @@ database "posthog" {materialized_view "ops_query_log_archive_mv" {to_table = "posthog.writable_query_log_archive"- query = "SELECT hostname, user, query_id, initial_query_id, is_initial_query, type, event_date, event_time, event_time_microseconds, query_start_time, query_start_time_microseconds, query_duration_ms, read_rows, read_bytes, written_rows, written_bytes, result_rows, result_bytes, memory_usage, peak_threads_usage, current_database, query, formatted_query, normalized_query_hash, query_kind, exception_code, exception, stack_trace, JSONExtractInt(log_comment, 'team_id') AS team_id, if(isValidJSON(log_comment), log_comment, '{}') AS log_comment, ProfileEvents FROM system.query_log WHERE type != 'QueryStart'"+ query = <<SQL+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'+SQL+column "hostname" {type = "LowCardinality(String)"}@@ -1478,38 +1514,256 @@ database "posthog" {}view "custom_metrics" {- query = "SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_test UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_replication_queue UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_server_crash UNION ALL SELECT * FROM posthog.custom_metrics_table_sizes UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_part_counts UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_dictionaries UNION ALL SELECT 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name, map('instance', hostname(), 'disk', disk_name) AS labels, toFloat64(sum(bytes_on_disk)) AS value, 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help, 'gauge' AS type FROM system.parts WHERE disk_name IN ('s3disk', 'cache') GROUP BY disk_name UNION ALL SELECT 'ClickHouseCustomMetric_MergeFailures15m' AS name, map('instance', hostname()) AS labels, toFloat64(count()) AS value, 'Number of failed merge operations in the last 15 minutes' AS help, 'gauge' AS type FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) UNION ALL SELECT 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name, map('instance', hostname()) AS labels, toFloat64(max(cnt)) AS value, 'Max failed merge retries for any single table in the last 15 minutes' AS help, 'gauge' AS type FROM (SELECT count() AS cnt FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) GROUP BY database, `table`, partition_id)"+ query = <<SQL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )+SQL+}view "custom_metrics_backups" {- query = "WITH ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names, [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values, ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions, ['gauge', 'gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.backup_log WHERE event_date = today() GROUP BY event_date"+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date+SQL+}view "custom_metrics_dictionaries" {- query = "SELECT 'ClickHouseCustomMetric_DictionariesFailed' AS name, map('instance', hostname(), 'database', d.database, 'dictionary', d.dict_name, 'uuid', toString(d.uuid), 'status', toString(d.status)) AS labels, toUInt64(1) AS value, 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help, 'gauge' AS type FROM (SELECT name AS dict_name, database, uuid, status FROM system.dictionaries WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')) AS d"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d+SQL+}view "custom_metrics_part_counts" {- query = "SELECT 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name, map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels, part_count AS value, 'Maximum number of active parts for any partition in a PostHog table' AS help, 'gauge' AS type FROM (SELECT database, `table`, partition, count() AS part_count FROM system.parts WHERE active AND (database = 'posthog') GROUP BY database, `table`, partition ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC LIMIT 1 BY database, `table`)"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )+SQL+}view "custom_metrics_replication_queue" {- query = "WITH ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names, [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values, ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions, ['gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('table', `table`, 'instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.replication_queue GROUP BY `table` HAVING value > 0"+ query = <<SQL+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0+SQL+}view "custom_metrics_server_crash" {- query = "SELECT 'ClickHouseCustomMetric_ServerCrash' AS name, map('instance', hostname()) AS labels, count() AS value, 'Number of server crashes for current date' AS help, 'gauge' AS type FROM system.crash_log WHERE event_date = today() GROUP BY hostname()"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()+SQL+}view "custom_metrics_table_sizes" {- query = "SELECT 'ClickHouseCustomMetric_TableTotalBytes' AS name, map('instance', hostname(), 'database', database, 'table', `table`) AS labels, CAST(total_bytes, 'Float64') AS value, 'Size of a database table on a given node (need a sum for sharded)' AS help, 'gauge' AS type FROM system.tables WHERE (database NOT IN ('INFORMATION_SCHEMA', 'information_schema')) AND (total_bytes IS NOT NULL)"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)+SQL+}view "custom_metrics_test" {- query = "SELECT 'ClickHouseCustomMetric_Test' AS name, map('instance', hostname()) AS labels, 1 AS value, 'Test to check that the metric endpoint is working' AS help, 'gauge' AS type"+ query = <<SQL+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type+SQL+}view "daily_aggregated_query_log_archive" {- query = "SELECT event_date AS day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label, count() AS query_count, sum(read_bytes) AS read_bytes, sum(read_rows) AS read_rows, sum(query_duration_ms) AS query_duration_ms, sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds, countIf(exception_code != 0) AS error_count, countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count FROM posthog.sharded_query_log_archive WHERE is_initial_query AND (event_date < today()) GROUP BY day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label"+ query = <<SQL+SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label+SQL+}}diff --git a/posthog/clickhouse/hcl/nodes b/posthog/clickhouse/hcl/nodesnew file mode 100644index 000000000000..34f8d41571bc--- /dev/null+++ b/posthog/clickhouse/hcl/nodes@@ -0,0 +1,40 @@+# 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++dev logs roles/shared roles/logs/shared roles/logs/dev+prod-us logs roles/shared roles/logs/shared roles/logs/prod-us+prod-eu logs roles/shared roles/logs/shared roles/logs/prod-eu++# prod-us data roles/shared roles/data/shared roles/data/prod-us+# prod-us endpoints roles/shared+# prod-us aux roles/shared+# prod-us ai_events roles/shared+# prod-us sessions roles/shareddiff --git a/posthog/clickhouse/hcl/ops/base/custom_metrics.hcl b/posthog/clickhouse/hcl/ops/base/custom_metrics.hcldeleted file mode 100644index a128274903f2..000000000000--- a/posthog/clickhouse/hcl/ops/base/custom_metrics.hcl+++ /dev/null@@ -1,29 +0,0 @@-# OPS custom_metrics views — Prometheus-style metric views over system.* (all envs)-#-# Declarative source of truth for the OPS ClickHouse cluster.-database "posthog" {- view "custom_metrics" {- query = "SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_test UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_replication_queue UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_server_crash UNION ALL SELECT * FROM posthog.custom_metrics_table_sizes UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_part_counts UNION ALL SELECT * REPLACE(toFloat64(value) AS value) FROM posthog.custom_metrics_dictionaries UNION ALL SELECT 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name, map('instance', hostname(), 'disk', disk_name) AS labels, toFloat64(sum(bytes_on_disk)) AS value, 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help, 'gauge' AS type FROM system.parts WHERE disk_name IN ('s3disk', 'cache') GROUP BY disk_name UNION ALL SELECT 'ClickHouseCustomMetric_MergeFailures15m' AS name, map('instance', hostname()) AS labels, toFloat64(count()) AS value, 'Number of failed merge operations in the last 15 minutes' AS help, 'gauge' AS type FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) UNION ALL SELECT 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name, map('instance', hostname()) AS labels, toFloat64(max(cnt)) AS value, 'Max failed merge retries for any single table in the last 15 minutes' AS help, 'gauge' AS type FROM (SELECT count() AS cnt FROM system.part_log WHERE (event_time >= (now() - toIntervalMinute(15))) AND (event_type = 'MergeParts') AND (error > 0) AND (merge_reason != 'NotAMerge') AND (error != 40) GROUP BY database, `table`, partition_id)"- }- view "custom_metrics_backups" {- query = "WITH ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names, [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values, ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions, ['gauge', 'gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.backup_log WHERE event_date = today() GROUP BY event_date"- }- view "custom_metrics_dictionaries" {- query = "SELECT 'ClickHouseCustomMetric_DictionariesFailed' AS name, map('instance', hostname(), 'database', d.database, 'dictionary', d.dict_name, 'uuid', toString(d.uuid), 'status', toString(d.status)) AS labels, toUInt64(1) AS value, 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help, 'gauge' AS type FROM (SELECT name AS dict_name, database, uuid, status FROM system.dictionaries WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')) AS d"- }- view "custom_metrics_part_counts" {- query = "SELECT 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name, map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels, part_count AS value, 'Maximum number of active parts for any partition in a PostHog table' AS help, 'gauge' AS type FROM (SELECT database, `table`, partition, count() AS part_count FROM system.parts WHERE active AND (database = 'posthog') GROUP BY database, `table`, partition ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC LIMIT 1 BY database, `table`)"- }- view "custom_metrics_replication_queue" {- query = "WITH ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names, [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values, ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions, ['gauge', 'gauge', 'gauge'] AS types, arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl SELECT tpl.1 AS name, map('table', `table`, 'instance', hostname()) AS labels, tpl.2 AS value, tpl.3 AS help, tpl.4 AS type FROM system.replication_queue GROUP BY `table` HAVING value > 0"- }- view "custom_metrics_server_crash" {- query = "SELECT 'ClickHouseCustomMetric_ServerCrash' AS name, map('instance', hostname()) AS labels, count() AS value, 'Number of server crashes for current date' AS help, 'gauge' AS type FROM system.crash_log WHERE event_date = today() GROUP BY hostname()"- }- view "custom_metrics_table_sizes" {- query = "SELECT 'ClickHouseCustomMetric_TableTotalBytes' AS name, map('instance', hostname(), 'database', database, 'table', `table`) AS labels, CAST(total_bytes, 'Float64') AS value, 'Size of a database table on a given node (need a sum for sharded)' AS help, 'gauge' AS type FROM system.tables WHERE (database NOT IN ('INFORMATION_SCHEMA', 'information_schema')) AND (total_bytes IS NOT NULL)"- }- view "custom_metrics_test" {- query = "SELECT 'ClickHouseCustomMetric_Test' AS name, map('instance', hostname()) AS labels, 1 AS value, 'Test to check that the metric endpoint is working' AS help, 'gauge' AS type"- }-}diff --git a/posthog/clickhouse/hcl/ops/check.sh b/posthog/clickhouse/hcl/ops/check.shdeleted file mode 100755index eeea04682eba..000000000000--- a/posthog/clickhouse/hcl/ops/check.sh+++ /dev/null@@ -1,71 +0,0 @@-#!/usr/bin/env bash-# Fidelity + reference guard for the declarative OPS ClickHouse schema.-#-# For each environment it:-# 1. `hclexp validate`s the resolved layer stack (cross-object references resolve),-# skipping references that intentionally point outside the OPS schema-# (the `system` database and the main events cluster).-# 2. `hclexp diff`s the resolved layer stack against the vendored golden dump,-# asserting zero drift — i.e. the layered source still reproduces the-# last captured cluster state exactly.-#-# Run from the repo root. Uses ./posthog/clickhouse/hcl/bin/hclexp (container or-# local binary). Exits non-zero on any drift or unexpected validation error.-set -euo pipefail--HCL=posthog/clickhouse/hcl-HCLEXP="$HCL/bin/hclexp"-BASE="$HCL/ops/base"-PROD="$HCL/ops/prod"-GOLDEN="$HCL/ops/golden"--# Objects whose source/target tables live outside the OPS schema by design:-# - custom_metrics* views read from the `system` database-# - ops_query_log_archive_mv reads from system.query_log-# - events_main / events_recent are Distributed proxies to the main events cluster-SKIP='custom_metrics,custom_metrics_backups,custom_metrics_dictionaries,custom_metrics_part_counts,custom_metrics_replication_queue,custom_metrics_server_crash,custom_metrics_table_sizes,ops_query_log_archive_mv,events_main,events_recent'--# env -> layer stack (kept portable for bash 3.2; no associative arrays)-# Every environment composes the shared base layer (query_log_archive data path-# + custom_metrics views). `local` adds nothing on top; cloud envs add the-# metrics suite (prod) and per-env objects.-stack_for() {- case "$1" in- local) echo "$BASE,$HCL/ops/env/local" ;;- dev) echo "$BASE,$HCL/ops/env/dev" ;;- prod-us) echo "$BASE,$PROD,$HCL/ops/env/prod-us" ;;- prod-eu) echo "$BASE,$PROD,$HCL/ops/env/prod-eu" ;;- esac-}--# Cloud envs are diffed against a vendored golden dump captured from the live-# cluster. `local` has no external cluster dump (it is created from this HCL),-# so it is validated only — the live round-trip is exercised by the local-apply-# tooling, not this offline guard.-has_golden() { [[ "$1" != "local" ]]; }--rc=0-for env in local dev prod-us prod-eu; do- layers="$(stack_for "$env")"-- echo "== $env: validate =="- if ! "$HCLEXP" validate -layer "$layers" -skip-validation "$SKIP" >/dev/null; then- echo "FAIL: validate $env"; rc=1- fi-- if has_golden "$env"; then- echo "== $env: diff vs golden =="- err="$(mktemp)"- out="$("$HCLEXP" diff -left "$layers" -right "$GOLDEN/$env-ops.hcl" 2>"$err")"- if [[ "$out" != "no differences" ]]; then- # On a tool failure (image not pulled, missing golden, bad arg) $out is- # empty — surface stderr so "FAIL: drift" is never an empty mystery.- echo "FAIL: drift in $env"; echo "$out"; cat "$err"; rc=1- else- echo "no differences"- fi- rm -f "$err"- fi-done--exit $rcdiff --git a/posthog/clickhouse/hcl/ops/diff.sh b/posthog/clickhouse/hcl/ops/diff.shdeleted file mode 100755index be4ec1fffa94..000000000000--- a/posthog/clickhouse/hcl/ops/diff.sh+++ /dev/null@@ -1,72 +0,0 @@-#!/usr/bin/env bash-# Preview the migration DDL your uncommitted HCL edits would produce, per env.-#-# For each OPS environment it resolves the layer stack twice — at the committed-# state (left = reference) and at your working tree (right = desired) — and runs-# hclexp diff -left <committed> -right <working> -sql-# so the emitted statements are the migration to go committed -> changed.-#-# This is review-time companion to check.sh (which guards layers vs golden):-# check.sh asks "does the source still reproduce the captured cluster?"; this-# asks "what does my change actually do?". Read-only — never touches a cluster,-# never applies. UNSAFE (recreate) changes are flagged by hclexp.-#-# Usage (from repo root):-# posthog/clickhouse/hcl/ops/diff.sh # working tree vs HEAD, all envs-# posthog/clickhouse/hcl/ops/diff.sh prod-us # one env-# posthog/clickhouse/hcl/ops/diff.sh <ref> # working tree vs an arbitrary ref-# posthog/clickhouse/hcl/ops/diff.sh <ref> prod-eu # both-set -euo pipefail--HCL=posthog/clickhouse/hcl-HCLEXP="$HCL/bin/hclexp"-BASE="$HCL/ops/base"-PROD="$HCL/ops/prod"--# env -> layer stack (kept in sync with check.sh; portable for bash 3.2).-stack_for() {- case "$1" in- local) echo "$BASE,$HCL/ops/env/local" ;;- dev) echo "$BASE,$HCL/ops/env/dev" ;;- prod-us) echo "$BASE,$PROD,$HCL/ops/env/prod-us" ;;- prod-eu) echo "$BASE,$PROD,$HCL/ops/env/prod-eu" ;;- esac-}--REF="HEAD"-ENVS="local dev prod-us prod-eu"-for arg in "$@"; do- case "$arg" in- local|dev|prod-us|prod-eu) ENVS="$arg" ;;- *) REF="$arg" ;;- esac-done--# Short-circuit when nothing under the OPS HCL changed vs the reference.-if git diff --quiet "$REF" -- "$HCL/ops" 2>/dev/null; then- echo "no HCL changes under $HCL/ops (vs $REF)"- exit 0-fi--# Materialize the committed tree so the left side resolves the *reference* layers.-TMP="$(mktemp -d)"-trap 'rm -rf "$TMP"' EXIT-git archive "$REF" "$HCL/ops" | tar -x -C "$TMP"--rc=0-for env in $ENVS; do- working="$(stack_for "$env")"- # Same stack, rooted in the committed snapshot.- committed="$(stack_for "$env" | sed "s#$HCL/ops#$TMP/$HCL/ops#g")"-- echo "=============================================================="- echo "# $env (committed@$REF -> working tree)"- echo "=============================================================="- if ! "$HCLEXP" diff -left "$committed" -right "$working" -sql; then- echo "WARN: hclexp diff failed for $env" >&2- rc=1- fi- echo-done--exit $rcdiff --git a/posthog/clickhouse/hcl/roles/logs/dev/sql/kafka_logs34_avro_mv.sql b/posthog/clickhouse/hcl/roles/logs/dev/sql/kafka_logs34_avro_mv.sqlnew file mode 100644index 000000000000..a1132b907b05--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/dev/sql/kafka_logs34_avro_mv.sql@@ -0,0 +1,16 @@+SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avrodiff --git a/posthog/clickhouse/hcl/roles/logs/dev/sql/kafka_logs_avro_billing_metrics_mv.sql b/posthog/clickhouse/hcl/roles/logs/dev/sql/kafka_logs_avro_billing_metrics_mv.sqlnew file mode 100644index 000000000000..2dce06860d5e--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/dev/sql/kafka_logs_avro_billing_metrics_mv.sql@@ -0,0 +1,20 @@+SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(floor(_bytes_uncompressed / _record_count)) AS bytes_uncompressed,+ sumSimpleState(floor(_bytes_compressed / _record_count)) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_namediff --git a/posthog/clickhouse/hcl/roles/logs/dev/tables.hcl b/posthog/clickhouse/hcl/roles/logs/dev/tables.hclnew file mode 100644index 000000000000..2f6156bb1030--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/dev/tables.hcl@@ -0,0 +1,673 @@+# LOGS dev overlay — env-specific / differing logs objects.+database "posthog" {+ materialized_view "kafka_logs34_avro_mv" {+ to_table = "posthog.logs34"+ query = file("sql/kafka_logs34_avro_mv.sql")+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "Int64"+ }+ column "_bytes_uncompressed" {+ type = "Nullable(Int64)"+ }+ column "_bytes_compressed" {+ type = "Nullable(Int64)"+ }+ }+ table "kafka_logs_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ engine "kafka" {+ broker_list = "warpstream_logs"+ topic_list = "kafka_topic_list = 'clickhouse_logs'"+ group_name = "kafka_group_name = 'clickhouse-logs-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }+ materialized_view "kafka_logs_avro_billing_metrics_mv" {+ to_table = "posthog.logs_billing_metrics"+ query = file("sql/kafka_logs_avro_billing_metrics_mv.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "log_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "log_attributes2"+ }+ }+ table "logs34" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "severity_text", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ add_minmax_index_for_numeric_columns = "1"+ allow_experimental_reverse_key = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_severity_text_set" {+ expr = "severity_text"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_mat_body_ipv4_matches" {+ expr = "mat_body_ipv4_matches"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_body_ngram3" {+ expr = "lower(body)"+ type = "ngrambf_v1(3, 25000, 2, 0)"+ granularity = 1+ }+ index "idx_uuid_bloom" {+ expr = "uuid"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.logs34"+ replica_name = "{replica}"+ }+ }+ table "logs_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs34"+ }+ }+ table "metrics" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "metrics1"+ }+ }+ table "metrics1" {+ order_by = ["team_id", "time_bucket", "service_name", "metric_name", "resource_fingerprint", "timestamp"]+ partition_by = "toDate(timestamp)"+ settings = {+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ index "idx_metric_name_set" {+ expr = "metric_name"+ type = "set(100)"+ granularity = 1+ }+ index "idx_metric_type_set" {+ expr = "metric_type"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics1"+ replica_name = "{replica}"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_logs34_avro_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_logs34_avro_mv.sqlnew file mode 100644index 000000000000..15d9fd2954f0--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_logs34_avro_mv.sql@@ -0,0 +1,16 @@+SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes, bytes_uncompressed),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avrodiff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_logs_avro_billing_metrics_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_logs_avro_billing_metrics_mv.sqlnew file mode 100644index 000000000000..398ada16de01--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_logs_avro_billing_metrics_mv.sql@@ -0,0 +1,20 @@+SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(_bytes_uncompressed) AS bytes_uncompressed,+ sumSimpleState(_bytes_compressed) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_namediff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_trace_spans_avro_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_trace_spans_avro_mv.sqlnew file mode 100644index 000000000000..0ca8e7ee842d--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/kafka_trace_spans_avro_mv.sql@@ -0,0 +1,18 @@+SELECT+ * EXCEPT(attributes, resource_attributes, kind, flags, dropped_attributes_count, dropped_events_count, dropped_links_count, status_code),+ toInt8(kind) AS kind,+ toUInt32(flags) AS flags,+ toUInt32(dropped_attributes_count) AS dropped_attributes_count,+ toUInt32(dropped_events_count) AS dropped_events_count,+ toUInt32(dropped_links_count) AS dropped_links_count,+ toInt16(status_code) AS status_code,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) AS _bytes_compressed+FROM posthog.kafka_trace_spans_avrodiff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_attributes.sql b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_attributes.sqlnew file mode 100644index 000000000000..6d04bf3d4469--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_attributes.sql@@ -0,0 +1,26 @@+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )diff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_resource_attributes.sql b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_resource_attributes.sqlnew file mode 100644index 000000000000..05cbac84f741--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_resource_attributes.sql@@ -0,0 +1,26 @@+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_resource_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )diff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_span_attributes.sql b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_span_attributes.sqlnew file mode 100644index 000000000000..5d1b29750379--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/sql/trace_span_to_span_attributes.sql@@ -0,0 +1,25 @@+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ 'name' AS attribute_key,+ name AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, name+ )diff --git a/posthog/clickhouse/hcl/roles/logs/prod-eu/tables.hcl b/posthog/clickhouse/hcl/roles/logs/prod-eu/tables.hclnew file mode 100644index 000000000000..add29fce0692--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-eu/tables.hcl@@ -0,0 +1,1324 @@+# LOGS prod-eu overlay — env-specific / differing logs objects.+database "posthog" {+ materialized_view "kafka_logs34_avro_mv" {+ to_table = "posthog.logs34"+ query = file("sql/kafka_logs34_avro_mv.sql")+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "Int64"+ }+ column "_bytes_uncompressed" {+ type = "Nullable(Int64)"+ }+ column "_bytes_compressed" {+ type = "Nullable(Int64)"+ }+ }+ table "kafka_logs_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "bytes_uncompressed" {+ type = "Int64"+ }+ engine "kafka" {+ broker_list = "warpstream_logs"+ topic_list = "kafka_topic_list = 'clickhouse_logs'"+ group_name = "kafka_group_name = 'clickhouse-logs-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }+ materialized_view "kafka_logs_avro_billing_metrics_mv" {+ to_table = "posthog.logs_billing_metrics"+ query = file("sql/kafka_logs_avro_billing_metrics_mv.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "kafka_trace_spans_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int32"+ }+ column "flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "Int32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "Int32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "Int32"+ }+ column "status_code" {+ type = "Int32"+ }+ engine "kafka" {+ broker_list = "warpstream_traces"+ topic_list = "kafka_topic_list = 'clickhouse_traces'"+ group_name = "kafka_group_name = 'clickhouse-traces-avro'"+ format = "kafka_format = 'Avro'"+ num_consumers = 2+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }+ materialized_view "kafka_trace_spans_avro_mv" {+ to_table = "posthog.trace_spans"+ query = file("sql/kafka_trace_spans_avro_mv.sql")+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "status_code" {+ type = "Int16"+ }+ column "team_id" {+ type = "Int32"+ }+ }+ table "log_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "log_attributes2"+ }+ }+ table "logs34" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "severity_text", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ add_minmax_index_for_numeric_columns = "1"+ allow_experimental_reverse_key = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ storage_policy = "s3_tiered"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_severity_text_set" {+ expr = "severity_text"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_mat_body_ipv4_matches" {+ expr = "mat_body_ipv4_matches"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_body_ngram3" {+ expr = "lower(body)"+ type = "ngrambf_v1(3, 25000, 2, 0)"+ granularity = 1+ }+ index "idx_uuid_bloom" {+ expr = "uuid"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.logs34"+ replica_name = "{replica}"+ }+ }+ table "logs_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs34"+ }+ }+ table "metrics" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "metrics1"+ }+ }+ table "metrics1" {+ order_by = ["team_id", "time_bucket", "service_name", "metric_name", "resource_fingerprint", "timestamp"]+ partition_by = "toDate(timestamp)"+ settings = {+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ index "idx_metric_name_set" {+ expr = "metric_name"+ type = "set(100)"+ granularity = 1+ }+ index "idx_metric_type_set" {+ expr = "metric_type"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics1"+ replica_name = "{replica}"+ }+ }+ table "trace_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(original_expiry_time_bucket)"+ ttl = "original_expiry_time_bucket"+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_attributes"+ replica_name = "{replica}"+ }+ }+ table "trace_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_attributes"+ }+ }+ materialized_view "trace_span_to_attributes" {+ to_table = "posthog.trace_attributes"+ query = file("sql/trace_span_to_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ materialized_view "trace_span_to_resource_attributes" {+ to_table = "posthog.trace_attributes"+ query = file("sql/trace_span_to_resource_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ materialized_view "trace_span_to_span_attributes" {+ to_table = "posthog.trace_attributes"+ query = file("sql/trace_span_to_span_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "trace_spans" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "status_code", "name", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ allow_part_offset_column_in_projections = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_name" {+ expr = "name"+ type = "ngrambf_v1(4, 5000, 2, 0)"+ granularity = 16+ }+ index "idx_kind" {+ expr = "kind"+ type = "minmax"+ granularity = 4+ }+ index "idx_duration" {+ expr = "duration_nano"+ type = "minmax"+ granularity = 1+ }+ index "idx_status_code" {+ expr = "status_code"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 16+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 16+ }+ index "idx_trace_bloom_part" {+ expr = "trace_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ index "idx_span_id_bloom_part" {+ expr = "span_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_spans"+ replica_name = "{replica}"+ }+ }+ table "trace_spans_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_spans"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_logs34_avro_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_logs34_avro_mv.sqlnew file mode 100644index 000000000000..a1132b907b05--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_logs34_avro_mv.sql@@ -0,0 +1,16 @@+SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avrodiff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_logs_avro_billing_metrics_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_logs_avro_billing_metrics_mv.sqlnew file mode 100644index 000000000000..2dce06860d5e--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_logs_avro_billing_metrics_mv.sql@@ -0,0 +1,20 @@+SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(floor(_bytes_uncompressed / _record_count)) AS bytes_uncompressed,+ sumSimpleState(floor(_bytes_compressed / _record_count)) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_namediff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_trace_spans_avro_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_trace_spans_avro_mv.sqlnew file mode 100644index 000000000000..0ca8e7ee842d--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/kafka_trace_spans_avro_mv.sql@@ -0,0 +1,18 @@+SELECT+ * EXCEPT(attributes, resource_attributes, kind, flags, dropped_attributes_count, dropped_events_count, dropped_links_count, status_code),+ toInt8(kind) AS kind,+ toUInt32(flags) AS flags,+ toUInt32(dropped_attributes_count) AS dropped_attributes_count,+ toUInt32(dropped_events_count) AS dropped_events_count,+ toUInt32(dropped_links_count) AS dropped_links_count,+ toInt16(status_code) AS status_code,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) AS _bytes_compressed+FROM posthog.kafka_trace_spans_avrodiff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_attributes.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_attributes.sqlnew file mode 100644index 000000000000..6d04bf3d4469--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_attributes.sql@@ -0,0 +1,26 @@+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )diff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_resource_attributes.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_resource_attributes.sqlnew file mode 100644index 000000000000..05cbac84f741--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_resource_attributes.sql@@ -0,0 +1,26 @@+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_resource_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ )diff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_span_attributes.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_span_attributes.sqlnew file mode 100644index 000000000000..5d1b29750379--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_span_to_span_attributes.sql@@ -0,0 +1,25 @@+SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ 'name' AS attribute_key,+ name AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, name+ )diff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_spans_to_kafka_metrics_mv.sql b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_spans_to_kafka_metrics_mv.sqlnew file mode 100644index 000000000000..576d92e2a7b5--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/sql/trace_spans_to_kafka_metrics_mv.sql@@ -0,0 +1,11 @@+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.trace_spans+GROUP BY+ _partition, _topicdiff --git a/posthog/clickhouse/hcl/roles/logs/prod-us/tables.hcl b/posthog/clickhouse/hcl/roles/logs/prod-us/tables.hclnew file mode 100644index 000000000000..d6cfa22730dc--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/prod-us/tables.hcl@@ -0,0 +1,1363 @@+# LOGS prod-us overlay — env-specific / differing logs objects.+database "posthog" {+ materialized_view "kafka_logs34_avro_mv" {+ to_table = "posthog.logs34"+ query = file("sql/kafka_logs34_avro_mv.sql")+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "Int64"+ }+ column "_bytes_uncompressed" {+ type = "Nullable(Int64)"+ }+ column "_bytes_compressed" {+ type = "Nullable(Int64)"+ }+ }+ table "kafka_logs_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "String"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ engine "kafka" {+ broker_list = "warpstream_logs"+ topic_list = "kafka_topic_list = 'clickhouse_logs'"+ group_name = "kafka_group_name = 'clickhouse-logs-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 32+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }+ materialized_view "kafka_logs_avro_billing_metrics_mv" {+ to_table = "posthog.logs_billing_metrics"+ query = file("sql/kafka_logs_avro_billing_metrics_mv.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, Float64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "kafka_trace_spans_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int32"+ }+ column "flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "Int32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "Int32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "Int32"+ }+ column "status_code" {+ type = "Int32"+ }+ engine "kafka" {+ broker_list = "warpstream_traces"+ topic_list = "kafka_topic_list = 'clickhouse_traces'"+ group_name = "kafka_group_name = 'clickhouse-traces-avro'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }+ materialized_view "kafka_trace_spans_avro_mv" {+ to_table = "posthog.trace_spans"+ query = file("sql/kafka_trace_spans_avro_mv.sql")+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "String"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "links" {+ type = "Array(String)"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "status_code" {+ type = "Int16"+ }+ column "team_id" {+ type = "Int32"+ }+ }+ table "log_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "log_attributes2"+ }+ }+ table "logs34" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "severity_text", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ add_minmax_index_for_numeric_columns = "1"+ allow_experimental_reverse_key = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_buckets_strategy = "constant"+ map_serialization_version = "with_buckets"+ max_buckets_in_map = "32"+ storage_policy = "s3_tiered"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_severity_text_set" {+ expr = "severity_text"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_mat_body_ipv4_matches" {+ expr = "mat_body_ipv4_matches"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_body_ngram3" {+ expr = "lower(body)"+ type = "ngrambf_v1(3, 25000, 2, 0)"+ granularity = 1+ }+ index "idx_uuid_bloom" {+ expr = "uuid"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.logs34"+ replica_name = "{replica}"+ }+ }+ table "logs_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ codec = "DoubleDelta"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "body" {+ type = "String"+ }+ column "severity_text" {+ type = "LowCardinality(String)"+ }+ column "severity_number" {+ type = "Int32"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "event_name" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "level" {+ type = "String"+ alias = "severity_text"+ }+ column "mat_body_ipv4_matches" {+ type = "Array(String)"+ alias = "extractAll(body, '(\\\\d\\\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\\\.)(2, 2)([0-9]))')"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs34"+ }+ }+ table "metrics" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "metrics1"+ }+ }+ table "metrics1" {+ order_by = ["team_id", "time_bucket", "service_name", "metric_name", "resource_fingerprint", "timestamp"]+ partition_by = "toDate(timestamp)"+ settings = {+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfDay(timestamp)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "metric_name" {+ type = "LowCardinality(String)"+ }+ column "metric_type" {+ type = "LowCardinality(String)"+ }+ column "value" {+ type = "Float64"+ codec = "Gorilla(8)"+ }+ column "count" {+ type = "UInt64"+ default = "1"+ codec = "T64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "LowCardinality(String)"+ }+ column "aggregation_temporality" {+ type = "LowCardinality(String)"+ }+ column "is_monotonic" {+ type = "Bool"+ default = "false"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ }+ column "time_minute" {+ type = "DateTime"+ alias = "toStartOfMinute(timestamp)"+ }+ column "attributes" {+ type = "Map(String, String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ index "idx_metric_name_set" {+ expr = "metric_name"+ type = "set(100)"+ granularity = 1+ }+ index "idx_metric_type_set" {+ expr = "metric_type"+ type = "set(10)"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics1"+ replica_name = "{replica}"+ }+ }+ table "trace_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(original_expiry_time_bucket)"+ ttl = "original_expiry_time_bucket"+ settings = {+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 4+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 4+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_attributes"+ replica_name = "{replica}"+ }+ }+ table "trace_attributes_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_attributes"+ }+ }+ materialized_view "trace_span_to_attributes" {+ to_table = "posthog.trace_attributes"+ query = file("sql/trace_span_to_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ materialized_view "trace_span_to_resource_attributes" {+ to_table = "posthog.trace_attributes"+ query = file("sql/trace_span_to_resource_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ materialized_view "trace_span_to_span_attributes" {+ to_table = "posthog.trace_attributes"+ query = file("sql/trace_span_to_span_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "trace_spans" {+ order_by = ["team_id", "time_bucket", "service_name", "resource_fingerprint", "status_code", "name", "timestamp"]+ partition_by = "toDate(original_expiry_timestamp)"+ ttl = "original_expiry_timestamp"+ settings = {+ allow_part_offset_column_in_projections = "1"+ index_granularity = "8192"+ index_granularity_bytes = "104857600"+ map_serialization_version = "with_buckets"+ ttl_only_drop_parts = "1"+ }+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "_offset" {+ type = "UInt64"+ }+ column "_bytes_uncompressed" {+ type = "UInt64"+ }+ column "_bytes_compressed" {+ type = "UInt64"+ }+ column "_record_count" {+ type = "UInt64"+ }+ index "idx_name" {+ expr = "name"+ type = "ngrambf_v1(4, 5000, 2, 0)"+ granularity = 16+ }+ index "idx_kind" {+ expr = "kind"+ type = "minmax"+ granularity = 4+ }+ index "idx_duration" {+ expr = "duration_nano"+ type = "minmax"+ granularity = 1+ }+ index "idx_status_code" {+ expr = "status_code"+ type = "minmax"+ granularity = 1+ }+ index "idx_timestamp_minmax" {+ expr = "timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_observed_minmax" {+ expr = "observed_timestamp"+ type = "minmax"+ granularity = 1+ }+ index "idx_attributes_str_keys" {+ expr = "mapKeys(attributes_map_str)"+ type = "bloom_filter(0.01)"+ granularity = 16+ }+ index "idx_attributes_str_values" {+ expr = "mapValues(attributes_map_str)"+ type = "bloom_filter(0.001)"+ granularity = 16+ }+ index "idx_trace_bloom_part" {+ expr = "trace_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ index "idx_span_id_bloom_part" {+ expr = "span_id"+ type = "bloom_filter(0.00001)"+ granularity = 99999+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_spans"+ replica_name = "{replica}"+ }+ }+ table "trace_spans_distributed" {+ column "time_bucket" {+ type = "DateTime"+ materialized = "toStartOfInterval(timestamp, toIntervalHour(4))"+ }+ column "original_expiry_timestamp" {+ type = "DateTime64(6)"+ }+ column "uuid" {+ type = "String"+ }+ column "team_id" {+ type = "Int32"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "parent_span_id" {+ type = "String"+ }+ column "is_root_span" {+ type = "Bool"+ materialized = "replaceAll(trimRight(parent_span_id, '='), 'A', '') = ''"+ }+ column "trace_state" {+ type = "String"+ }+ column "name" {+ type = "LowCardinality(String)"+ }+ column "kind" {+ type = "Int8"+ }+ column "flags" {+ type = "UInt32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "end_time" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "created_at" {+ type = "DateTime64(6)"+ materialized = "now()"+ }+ column "duration_nano" {+ type = "UInt64"+ materialized = "toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000"+ }+ column "status_code" {+ type = "Int16"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_attributes" {+ type = "Map(LowCardinality(String), String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ materialized = "cityHash64(resource_attributes)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(LowCardinality(String), String)"+ }+ column "attributes" {+ type = "Map(LowCardinality(String), String)"+ alias = "mapApply((k, v) -> (left(k, -5), v), attributes_map_str)"+ }+ column "attributes_map_float" {+ type = "Map(LowCardinality(String), Float64)"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str))"+ }+ column "attributes_map_datetime" {+ type = "Map(LowCardinality(String), DateTime64(6))"+ materialized = "mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str))"+ }+ column "dropped_attributes_count" {+ type = "UInt32"+ }+ column "dropped_events_count" {+ type = "UInt32"+ }+ column "dropped_links_count" {+ type = "UInt32"+ }+ column "events" {+ type = "Array(String)"+ }+ column "links" {+ type = "Array(String)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "trace_spans"+ }+ }+ table "trace_spans_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.trace_spans_kafka_metrics"+ replica_name = "{replica}"+ }+ }+ materialized_view "trace_spans_to_kafka_metrics_mv" {+ to_table = "posthog.trace_spans_kafka_metrics"+ query = file("sql/trace_spans_to_kafka_metrics_mv.sql")+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/custom_metrics.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/custom_metrics.sqlnew file mode 100644index 000000000000..1fc4f30cf4c7--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/custom_metrics.sql@@ -0,0 +1,70 @@+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )diff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_logs_avro_kafka_metrics_mv.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_logs_avro_kafka_metrics_mv.sqlnew file mode 100644index 000000000000..6f4c3cdd0ba4--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_logs_avro_kafka_metrics_mv.sql@@ -0,0 +1,11 @@+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topicdiff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_metrics_avro_kafka_metrics_mv.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_metrics_avro_kafka_metrics_mv.sqlnew file mode 100644index 000000000000..78119c311222--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_metrics_avro_kafka_metrics_mv.sql@@ -0,0 +1,11 @@+SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topicdiff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_metrics_avro_mv.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_metrics_avro_mv.sqlnew file mode 100644index 000000000000..83238b61833c--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/kafka_metrics_avro_mv.sql@@ -0,0 +1,34 @@+SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0diff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/logs34_to_log_attributes.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/logs34_to_log_attributes.sqlnew file mode 100644index 000000000000..d91daf759806--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/logs34_to_log_attributes.sql@@ -0,0 +1,28 @@+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ )diff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/logs34_to_resource_attributes.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/logs34_to_resource_attributes.sqlnew file mode 100644index 000000000000..79176a74ef32--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/logs34_to_resource_attributes.sql@@ -0,0 +1,27 @@+SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ )diff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/metrics1_to_metric_attributes.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/metrics1_to_metric_attributes.sqlnew file mode 100644index 000000000000..a43fd58c454c--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/metrics1_to_metric_attributes.sql@@ -0,0 +1,26 @@+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ )diff --git a/posthog/clickhouse/hcl/roles/logs/shared/sql/metrics1_to_resource_attributes.sql b/posthog/clickhouse/hcl/roles/logs/shared/sql/metrics1_to_resource_attributes.sqlnew file mode 100644index 000000000000..eb2c5b822254--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/sql/metrics1_to_resource_attributes.sql@@ -0,0 +1,25 @@+SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ )diff --git a/posthog/clickhouse/hcl/roles/logs/shared/tables.hcl b/posthog/clickhouse/hcl/roles/logs/shared/tables.hclnew file mode 100644index 000000000000..8c051eb73466--- /dev/null+++ b/posthog/clickhouse/hcl/roles/logs/shared/tables.hcl@@ -0,0 +1,578 @@+# LOGS role — managed logs/traces/metrics objects extracted from *-logs.hcl dumps.+database "posthog" {+ view "custom_metrics" {+ query = file("sql/custom_metrics.sql")+ }+ materialized_view "kafka_logs_avro_kafka_metrics_mv" {+ to_table = "posthog.logs_kafka_metrics"+ query = file("sql/kafka_logs_avro_kafka_metrics_mv.sql")+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }+ table "kafka_metrics_avro" {+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Nullable(Int32)"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "Nullable(String)"+ }+ column "metric_name" {+ type = "Nullable(String)"+ }+ column "metric_type" {+ type = "Nullable(String)"+ }+ column "value" {+ type = "Nullable(Float64)"+ }+ column "count" {+ type = "Nullable(Int64)"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(Int64)"+ }+ column "unit" {+ type = "Nullable(String)"+ }+ column "aggregation_temporality" {+ type = "Nullable(String)"+ }+ column "is_monotonic" {+ type = "Nullable(UInt8)"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "Nullable(String)"+ }+ column "attributes" {+ type = "Map(String, String)"+ }+ engine "kafka" {+ broker_list = "warpstream_metrics"+ topic_list = "kafka_topic_list = 'clickhouse_metrics'"+ group_name = "kafka_group_name = 'clickhouse-metrics-avro-new'"+ format = "kafka_format = 'Avro'"+ num_consumers = 8+ skip_broken_messages = 100+ poll_timeout_ms = 3000+ poll_max_batch_size = 1000+ thread_per_consumer = true+ }+ }+ materialized_view "kafka_metrics_avro_kafka_metrics_mv" {+ to_table = "posthog.metrics_kafka_metrics"+ query = file("sql/kafka_metrics_avro_kafka_metrics_mv.sql")+ column "_partition" {+ type = "UInt64"+ }+ column "_topic" {+ type = "LowCardinality(String)"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(6))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime)"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, Decimal(18, 6))"+ }+ }+ materialized_view "kafka_metrics_avro_mv" {+ to_table = "posthog.metrics1"+ query = file("sql/kafka_metrics_avro_mv.sql")+ column "uuid" {+ type = "String"+ }+ column "trace_id" {+ type = "String"+ }+ column "span_id" {+ type = "String"+ }+ column "trace_flags" {+ type = "Int32"+ }+ column "timestamp" {+ type = "DateTime64(6)"+ }+ column "observed_timestamp" {+ type = "DateTime64(6)"+ }+ column "service_name" {+ type = "String"+ }+ column "metric_name" {+ type = "String"+ }+ column "metric_type" {+ type = "String"+ }+ column "value" {+ type = "Float64"+ }+ column "count" {+ type = "UInt64"+ }+ column "histogram_bounds" {+ type = "Array(Float64)"+ }+ column "histogram_counts" {+ type = "Array(UInt64)"+ }+ column "unit" {+ type = "String"+ }+ column "aggregation_temporality" {+ type = "String"+ }+ column "is_monotonic" {+ type = "UInt8"+ }+ column "resource_attributes" {+ type = "Map(String, String)"+ }+ column "instrumentation_scope" {+ type = "String"+ }+ column "attributes_map_str" {+ type = "Map(String, String)"+ }+ column "attributes_map_float" {+ type = "Map(String, Nullable(Float64))"+ }+ column "team_id" {+ type = "Int32"+ }+ }+ table "log_attributes2" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ ttl = "time_bucket + toIntervalDay(15)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ codec = "ZSTD(5)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ default = "'log'"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime"+ default = "now()"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/log_attributes34"+ replica_name = "{replica}"+ }+ }+ materialized_view "logs34_to_log_attributes" {+ to_table = "posthog.log_attributes2"+ query = file("sql/logs34_to_log_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ materialized_view "logs34_to_resource_attributes" {+ to_table = "posthog.log_attributes2"+ query = file("sql/logs34_to_resource_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "original_expiry_time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "logs_billing_metrics" {+ order_by = ["team_id", "time_bucket", "service_name"]+ partition_by = "toYYYYMM(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_billing_metrics"+ replica_name = "{replica}"+ }+ }+ table "logs_billing_metrics_distributed" {+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "bytes_uncompressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "bytes_compressed" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "record_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_billing_metrics"+ }+ }+ table "logs_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ deduplicate_merge_projection_mode = "rebuild"+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/logs_kafka_metrics"+ replica_name = "{replica}"+ }+ }+ table "logs_kafka_metrics_distributed" {+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "distributed" {+ cluster_name = "logs"+ remote_database = "posthog"+ remote_table = "logs_kafka_metrics"+ }+ }+ table "metric_attributes" {+ order_by = ["team_id", "attribute_type", "time_bucket", "resource_fingerprint", "attribute_key", "attribute_value"]+ partition_by = "toDate(time_bucket)"+ settings = {+ deduplicate_merge_projection_mode = "drop"+ index_granularity = "8192"+ }+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ default = "0"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ index "idx_attribute_key" {+ expr = "attribute_key"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_value" {+ expr = "attribute_value"+ type = "bloom_filter(0.01)"+ granularity = 1+ }+ index "idx_attribute_key_n3" {+ expr = "attribute_key"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ index "idx_attribute_value_n3" {+ expr = "attribute_value"+ type = "ngrambf_v1(3, 32768, 3, 0)"+ granularity = 1+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metric_attributes"+ replica_name = "{replica}"+ }+ }+ materialized_view "metrics1_to_metric_attributes" {+ to_table = "posthog.metric_attributes"+ query = file("sql/metrics1_to_metric_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ materialized_view "metrics1_to_resource_attributes" {+ to_table = "posthog.metric_attributes"+ query = file("sql/metrics1_to_resource_attributes.sql")+ column "team_id" {+ type = "Int32"+ }+ column "time_bucket" {+ type = "DateTime64(0)"+ }+ column "service_name" {+ type = "LowCardinality(String)"+ }+ column "resource_fingerprint" {+ type = "UInt64"+ }+ column "attribute_key" {+ type = "LowCardinality(String)"+ }+ column "attribute_value" {+ type = "String"+ }+ column "attribute_type" {+ type = "LowCardinality(String)"+ }+ column "attribute_count" {+ type = "SimpleAggregateFunction(sum, UInt64)"+ }+ }+ table "metrics_kafka_metrics" {+ order_by = ["_topic", "_partition"]+ settings = {+ index_granularity = "8192"+ }+ column "_partition" {+ type = "UInt32"+ }+ column "_topic" {+ type = "String"+ }+ column "max_offset" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ column "max_observed_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_timestamp" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_created_at" {+ type = "SimpleAggregateFunction(max, DateTime64(9))"+ }+ column "max_lag" {+ type = "SimpleAggregateFunction(max, UInt64)"+ }+ engine "replicated_aggregating_merge_tree" {+ zoo_path = "/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics"+ replica_name = "{replica}"+ }+ }+}diff --git a/posthog/clickhouse/hcl/ops/env/dev/ops.hcl b/posthog/clickhouse/hcl/roles/ops/dev/ops.hclsimilarity index 100%rename from posthog/clickhouse/hcl/ops/env/dev/ops.hclrename to posthog/clickhouse/hcl/roles/ops/dev/ops.hcldiff --git a/posthog/clickhouse/hcl/ops/env/local/ops.hcl b/posthog/clickhouse/hcl/roles/ops/local/ops.hclsimilarity index 100%rename from posthog/clickhouse/hcl/ops/env/local/ops.hclrename to posthog/clickhouse/hcl/roles/ops/local/ops.hcldiff --git a/posthog/clickhouse/hcl/ops/env/prod-eu/ops.hcl b/posthog/clickhouse/hcl/roles/ops/prod-eu/ops.hclsimilarity index 100%rename from posthog/clickhouse/hcl/ops/env/prod-eu/ops.hclrename to posthog/clickhouse/hcl/roles/ops/prod-eu/ops.hcldiff --git a/posthog/clickhouse/hcl/ops/env/prod-us/ops.hcl b/posthog/clickhouse/hcl/roles/ops/prod-us/ops.hclsimilarity index 100%rename from posthog/clickhouse/hcl/ops/env/prod-us/ops.hclrename to posthog/clickhouse/hcl/roles/ops/prod-us/ops.hcldiff --git a/posthog/clickhouse/hcl/ops/prod/ops.hcl b/posthog/clickhouse/hcl/roles/ops/prod/metrics.hclsimilarity index 87%rename from posthog/clickhouse/hcl/ops/prod/ops.hclrename to posthog/clickhouse/hcl/roles/ops/prod/metrics.hclindex 55f51a92d392..0878d20cc8c4 100644--- a/posthog/clickhouse/hcl/ops/prod/ops.hcl+++ b/posthog/clickhouse/hcl/roles/ops/prod/metrics.hcl@@ -1,13 +1,6 @@-# OPS prod layer — metrics suite, identical across prod-us and prod-eu-#-# Generated/maintained as the declarative source of truth for the OPS ClickHouse cluster.-# Resolve with: hclexp load -layer <base>,<...>+# OPS role, prod only — metrics suite + sharded_tophog abstract.database "posthog" {- # Shared shape for the per-env sharded_tophog tables. prod-us and prod-eu- # differ only in the engine zoo_path (tophog_new vs tophog), so the columns- # and table settings live here and each env layer instantiates a concrete- # sharded_tophog via `extend`, supplying just its engine block.table "sharded_tophog_base" {abstract = trueorder_by = ["pipeline", "lane", "metric", "timestamp", "key"]@@ -214,7 +207,7 @@ database "posthog" {}materialized_view "metrics_label_index_from_series_mv" {to_table = "posthog.metrics_label_index"- query = "SELECT team_id, metric_name, tupleElement(label_pair, 1) AS label_name, tupleElement(label_pair, 2) AS label_value, id FROM posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair"+ query = file("sql/metrics_label_index_from_series_mv.sql")column "team_id" {type = "UInt64"}diff --git a/posthog/clickhouse/hcl/roles/ops/prod/sql/metrics_label_index_from_series_mv.sql b/posthog/clickhouse/hcl/roles/ops/prod/sql/metrics_label_index_from_series_mv.sqlnew file mode 100644index 000000000000..3f54275a8019--- /dev/null+++ b/posthog/clickhouse/hcl/roles/ops/prod/sql/metrics_label_index_from_series_mv.sql@@ -0,0 +1,8 @@+SELECT+ team_id,+ metric_name,+ tupleElement(label_pair, 1) AS label_name,+ tupleElement(label_pair, 2) AS label_value,+ id+FROM+ posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pairdiff --git a/posthog/clickhouse/hcl/roles/ops/shared/core.hcl b/posthog/clickhouse/hcl/roles/ops/shared/core.hclnew file mode 100644index 000000000000..59b4cc58c538--- /dev/null+++ b/posthog/clickhouse/hcl/roles/ops/shared/core.hcl@@ -0,0 +1,522 @@+# OPS role — objects exclusive to the OPS node, all envs.++database "posthog" {+ table "events_team_daily_stats" {+ order_by = ["analysis_date", "team_id", "event"]+ settings = {+ index_granularity = "8192"+ }+ column "analysis_date" {+ type = "Date"+ }+ column "team_id" {+ type = "Int64"+ }+ column "event" {+ type = "String"+ }+ column "event_count" {+ type = "UInt64"+ }+ column "total_event_bytes" {+ type = "UInt64"+ }+ column "min_event_bytes" {+ type = "UInt64"+ }+ column "max_event_bytes" {+ type = "UInt64"+ }+ column "avg_event_bytes" {+ type = "Float64"+ }+ column "p50_event_bytes" {+ type = "Float64"+ }+ column "p90_event_bytes" {+ type = "Float64"+ }+ column "p95_event_bytes" {+ type = "Float64"+ }+ column "p99_event_bytes" {+ type = "Float64"+ }+ column "event_size_histogram" {+ type = "Array(Tuple(Float64, Float64, UInt64))"+ }+ column "computed_at" {+ type = "DateTime"+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/ops/tables/{shard}/posthog.events_team_daily_stats"+ replica_name = "{replica}"+ }+ }+ table "query_log_archive_buffer" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ engine "buffer" {+ database = "posthog"+ table = "sharded_query_log_archive"+ num_layers = 16+ min_time = 10+ max_time = 60+ min_rows = 10000+ max_rows = 1000000+ min_bytes = 10000000+ max_bytes = 100000000+ }+ }+ table "sharded_query_log_archive" {+ order_by = ["team_id", "event_date", "event_time", "query_id"]+ partition_by = "toYYYYMM(event_date)"+ settings = {+ index_granularity = "8192"+ object_serialization_version = "v3"+ object_shared_data_serialization_version = "map_with_buckets"+ }+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ column "exception_name" {+ type = "String"+ alias = "errorCodeToName(exception_code)"+ }+ column "ProfileEvents_RealTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['RealTimeMicroseconds']"+ }+ column "ProfileEvents_OSCPUVirtualTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['OSCPUVirtualTimeMicroseconds']"+ }+ column "ProfileEvents_S3Clients" {+ type = "Int64"+ alias = "ProfileEvents['S3Clients']"+ }+ column "ProfileEvents_S3DeleteObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3DeleteObjects']"+ }+ column "ProfileEvents_S3CopyObject" {+ type = "Int64"+ alias = "ProfileEvents['S3CopyObject']"+ }+ column "ProfileEvents_S3ListObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3ListObjects']"+ }+ column "ProfileEvents_S3HeadObject" {+ type = "Int64"+ alias = "ProfileEvents['S3HeadObject']"+ }+ column "ProfileEvents_S3GetObjectAttributes" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObjectAttributes']"+ }+ column "ProfileEvents_S3CreateMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CreateMultipartUpload']"+ }+ column "ProfileEvents_S3UploadPartCopy" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPartCopy']"+ }+ column "ProfileEvents_S3UploadPart" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPart']"+ }+ column "ProfileEvents_S3AbortMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3AbortMultipartUpload']"+ }+ column "ProfileEvents_S3CompleteMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CompleteMultipartUpload']"+ }+ column "ProfileEvents_S3PutObject" {+ type = "Int64"+ alias = "ProfileEvents['S3PutObject']"+ }+ column "ProfileEvents_S3GetObject" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObject']"+ }+ column "ProfileEvents_ReadBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['ReadBufferFromS3Bytes']"+ }+ column "ProfileEvents_WriteBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['WriteBufferFromS3Bytes']"+ }+ column "lc_workflow" {+ type = "LowCardinality(String)"+ alias = "log_comment.workflow"+ }+ column "lc_kind" {+ type = "LowCardinality(String)"+ alias = "log_comment.kind"+ }+ column "lc_id" {+ type = "String"+ alias = "CAST(log_comment.id, 'String')"+ }+ column "lc_route_id" {+ type = "String"+ alias = "CAST(log_comment.route_id, 'String')"+ }+ column "lc_access_method" {+ type = "LowCardinality(String)"+ alias = "log_comment.access_method"+ }+ column "lc_api_key_label" {+ type = "String"+ alias = "CAST(log_comment.api_key_label, 'String')"+ }+ column "lc_api_key_mask" {+ type = "String"+ alias = "CAST(log_comment.api_key_mask, 'String')"+ }+ column "lc_query_type" {+ type = "LowCardinality(String)"+ alias = "log_comment.query_type"+ }+ column "lc_product" {+ type = "LowCardinality(String)"+ alias = "log_comment.product"+ }+ column "lc_chargeable" {+ type = "Bool"+ alias = "log_comment.chargeable"+ }+ column "lc_name" {+ type = "String"+ alias = "CAST(log_comment.name, 'String')"+ }+ column "lc_request_name" {+ type = "String"+ alias = "CAST(log_comment.request_name, 'String')"+ }+ column "lc_client_query_id" {+ type = "String"+ alias = "CAST(log_comment.client_query_id, 'String')"+ }+ column "lc_org_id" {+ type = "String"+ alias = "CAST(log_comment.org_id, 'String')"+ }+ column "lc_user_id" {+ type = "Int64"+ alias = "log_comment.user_id"+ }+ column "lc_is_impersonated" {+ type = "Bool"+ alias = "log_comment.is_impersonated"+ }+ column "lc_session_id" {+ type = "String"+ alias = "CAST(log_comment.session_id, 'String')"+ }+ column "lc_dashboard_id" {+ type = "Int64"+ alias = "log_comment.dashboard_id"+ }+ column "lc_insight_id" {+ type = "Int64"+ alias = "log_comment.insight_id"+ }+ column "lc_cohort_id" {+ type = "Int64"+ alias = "log_comment.cohort_id"+ }+ column "lc_batch_export_id" {+ type = "String"+ alias = "CAST(log_comment.batch_export_id, 'String')"+ }+ column "lc_experiment_id" {+ type = "Int64"+ alias = "log_comment.experiment_id"+ }+ column "lc_experiment_feature_flag_key" {+ type = "String"+ alias = "CAST(log_comment.experiment_feature_flag_key, 'String')"+ }+ column "lc_alert_config_id" {+ type = "String"+ alias = "CAST(log_comment.alert_config_id, 'String')"+ }+ column "lc_feature" {+ type = "LowCardinality(String)"+ alias = "log_comment.feature"+ }+ column "lc_table_id" {+ type = "String"+ alias = "CAST(log_comment.table_id, 'String')"+ }+ column "lc_warehouse_query" {+ type = "Bool"+ alias = "log_comment.warehouse_query"+ }+ column "lc_person_on_events_mode" {+ type = "LowCardinality(String)"+ alias = "log_comment.person_on_events_mode"+ }+ column "lc_service_name" {+ type = "String"+ alias = "CAST(log_comment.service_name, 'String')"+ }+ column "lc_workload" {+ type = "LowCardinality(String)"+ alias = "log_comment.workload"+ }+ column "lc_query__kind" {+ type = "LowCardinality(String)"+ alias = "if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind'))"+ }+ column "lc_query__query" {+ type = "String"+ alias = "multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query'))"+ }+ column "lc_query" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), '')"+ }+ column "lc_temporal__workflow_namespace" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_namespace`, 'String')"+ }+ column "lc_temporal__workflow_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_type`, 'String')"+ }+ column "lc_temporal__workflow_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_id`, 'String')"+ }+ column "lc_temporal__workflow_run_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_run_id`, 'String')"+ }+ column "lc_temporal__activity_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_type`, 'String')"+ }+ column "lc_temporal__activity_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_id`, 'String')"+ }+ column "lc_temporal__attempt" {+ type = "Int64"+ alias = "log_comment.`temporal.attempt`"+ }+ column "lc_dagster__job_name" {+ type = "String"+ alias = "CAST(log_comment.`dagster.job_name`, 'String')"+ }+ column "lc_dagster__run_id" {+ type = "String"+ alias = "CAST(log_comment.`dagster.run_id`, 'String')"+ }+ column "lc_dagster__owner" {+ type = "String"+ alias = "CAST(log_comment.`dagster.tags.owner`, 'String')"+ }+ column "lc_modifiers" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')"+ }+ engine "replicated_merge_tree" {+ zoo_path = "/clickhouse/tables/noshard/posthog.sharded_query_log_archive"+ replica_name = "{replica}-{shard}"+ }+ }+ view "daily_aggregated_query_log_archive" {+ query = file("sql/daily_aggregated_query_log_archive.sql")+ }+ view "custom_metrics" {+ query = file("sql/custom_metrics.sql")+ }+}diff --git a/posthog/clickhouse/hcl/roles/ops/shared/sql/custom_metrics.sql b/posthog/clickhouse/hcl/roles/ops/shared/sql/custom_metrics.sqlnew file mode 100644index 000000000000..1fc4f30cf4c7--- /dev/null+++ b/posthog/clickhouse/hcl/roles/ops/shared/sql/custom_metrics.sql@@ -0,0 +1,70 @@+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ )diff --git a/posthog/clickhouse/hcl/roles/ops/shared/sql/daily_aggregated_query_log_archive.sql b/posthog/clickhouse/hcl/roles/ops/shared/sql/daily_aggregated_query_log_archive.sqlnew file mode 100644index 000000000000..4007d8448faa--- /dev/null+++ b/posthog/clickhouse/hcl/roles/ops/shared/sql/daily_aggregated_query_log_archive.sql@@ -0,0 +1,28 @@+SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_labeldiff --git a/posthog/clickhouse/hcl/roles/shared/custom_metrics.hcl b/posthog/clickhouse/hcl/roles/shared/custom_metrics.hclnew file mode 100644index 000000000000..69a5c0606f9e--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/custom_metrics.hcl@@ -0,0 +1,25 @@+# Shared: invariant custom_metrics_* sub-views (identical on every role). The custom_metrics aggregator is role-specific (see roles/ops).++database "posthog" {+ view "custom_metrics_backups" {+ query = file("sql/custom_metrics_backups.sql")+ }+ view "custom_metrics_dictionaries" {+ query = file("sql/custom_metrics_dictionaries.sql")+ }+ view "custom_metrics_part_counts" {+ query = file("sql/custom_metrics_part_counts.sql")+ }+ view "custom_metrics_replication_queue" {+ query = file("sql/custom_metrics_replication_queue.sql")+ }+ view "custom_metrics_server_crash" {+ query = file("sql/custom_metrics_server_crash.sql")+ }+ view "custom_metrics_table_sizes" {+ query = file("sql/custom_metrics_table_sizes.sql")+ }+ view "custom_metrics_test" {+ query = file("sql/custom_metrics_test.sql")+ }+}diff --git a/posthog/clickhouse/hcl/roles/shared/qla.hcl b/posthog/clickhouse/hcl/roles/shared/qla.hclnew file mode 100644index 000000000000..37350c22c33f--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/qla.hcl@@ -0,0 +1,549 @@+# Shared: query_log_archive read/write path + MV — present on every node role, every env++database "posthog" {+ table "query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ column "exception_name" {+ type = "String"+ alias = "errorCodeToName(exception_code)"+ }+ column "ProfileEvents_RealTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['RealTimeMicroseconds']"+ }+ column "ProfileEvents_OSCPUVirtualTimeMicroseconds" {+ type = "Int64"+ alias = "ProfileEvents['OSCPUVirtualTimeMicroseconds']"+ }+ column "ProfileEvents_S3Clients" {+ type = "Int64"+ alias = "ProfileEvents['S3Clients']"+ }+ column "ProfileEvents_S3DeleteObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3DeleteObjects']"+ }+ column "ProfileEvents_S3CopyObject" {+ type = "Int64"+ alias = "ProfileEvents['S3CopyObject']"+ }+ column "ProfileEvents_S3ListObjects" {+ type = "Int64"+ alias = "ProfileEvents['S3ListObjects']"+ }+ column "ProfileEvents_S3HeadObject" {+ type = "Int64"+ alias = "ProfileEvents['S3HeadObject']"+ }+ column "ProfileEvents_S3GetObjectAttributes" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObjectAttributes']"+ }+ column "ProfileEvents_S3CreateMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CreateMultipartUpload']"+ }+ column "ProfileEvents_S3UploadPartCopy" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPartCopy']"+ }+ column "ProfileEvents_S3UploadPart" {+ type = "Int64"+ alias = "ProfileEvents['S3UploadPart']"+ }+ column "ProfileEvents_S3AbortMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3AbortMultipartUpload']"+ }+ column "ProfileEvents_S3CompleteMultipartUpload" {+ type = "Int64"+ alias = "ProfileEvents['S3CompleteMultipartUpload']"+ }+ column "ProfileEvents_S3PutObject" {+ type = "Int64"+ alias = "ProfileEvents['S3PutObject']"+ }+ column "ProfileEvents_S3GetObject" {+ type = "Int64"+ alias = "ProfileEvents['S3GetObject']"+ }+ column "ProfileEvents_ReadBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['ReadBufferFromS3Bytes']"+ }+ column "ProfileEvents_WriteBufferFromS3Bytes" {+ type = "Int64"+ alias = "ProfileEvents['WriteBufferFromS3Bytes']"+ }+ column "lc_workflow" {+ type = "LowCardinality(String)"+ alias = "log_comment.workflow"+ }+ column "lc_kind" {+ type = "LowCardinality(String)"+ alias = "log_comment.kind"+ }+ column "lc_id" {+ type = "String"+ alias = "CAST(log_comment.id, 'String')"+ }+ column "lc_route_id" {+ type = "String"+ alias = "CAST(log_comment.route_id, 'String')"+ }+ column "lc_access_method" {+ type = "LowCardinality(String)"+ alias = "log_comment.access_method"+ }+ column "lc_api_key_label" {+ type = "String"+ alias = "CAST(log_comment.api_key_label, 'String')"+ }+ column "lc_api_key_mask" {+ type = "String"+ alias = "CAST(log_comment.api_key_mask, 'String')"+ }+ column "lc_query_type" {+ type = "LowCardinality(String)"+ alias = "log_comment.query_type"+ }+ column "lc_product" {+ type = "LowCardinality(String)"+ alias = "log_comment.product"+ }+ column "lc_chargeable" {+ type = "Bool"+ alias = "log_comment.chargeable"+ }+ column "lc_name" {+ type = "String"+ alias = "CAST(log_comment.name, 'String')"+ }+ column "lc_request_name" {+ type = "String"+ alias = "CAST(log_comment.request_name, 'String')"+ }+ column "lc_client_query_id" {+ type = "String"+ alias = "CAST(log_comment.client_query_id, 'String')"+ }+ column "lc_org_id" {+ type = "String"+ alias = "CAST(log_comment.org_id, 'String')"+ }+ column "lc_user_id" {+ type = "Int64"+ alias = "log_comment.user_id"+ }+ column "lc_is_impersonated" {+ type = "Bool"+ alias = "log_comment.is_impersonated"+ }+ column "lc_session_id" {+ type = "String"+ alias = "CAST(log_comment.session_id, 'String')"+ }+ column "lc_dashboard_id" {+ type = "Int64"+ alias = "log_comment.dashboard_id"+ }+ column "lc_insight_id" {+ type = "Int64"+ alias = "log_comment.insight_id"+ }+ column "lc_cohort_id" {+ type = "Int64"+ alias = "log_comment.cohort_id"+ }+ column "lc_batch_export_id" {+ type = "String"+ alias = "CAST(log_comment.batch_export_id, 'String')"+ }+ column "lc_experiment_id" {+ type = "Int64"+ alias = "log_comment.experiment_id"+ }+ column "lc_experiment_feature_flag_key" {+ type = "String"+ alias = "CAST(log_comment.experiment_feature_flag_key, 'String')"+ }+ column "lc_alert_config_id" {+ type = "String"+ alias = "CAST(log_comment.alert_config_id, 'String')"+ }+ column "lc_feature" {+ type = "LowCardinality(String)"+ alias = "log_comment.feature"+ }+ column "lc_table_id" {+ type = "String"+ alias = "CAST(log_comment.table_id, 'String')"+ }+ column "lc_warehouse_query" {+ type = "Bool"+ alias = "log_comment.warehouse_query"+ }+ column "lc_person_on_events_mode" {+ type = "LowCardinality(String)"+ alias = "log_comment.person_on_events_mode"+ }+ column "lc_service_name" {+ type = "String"+ alias = "CAST(log_comment.service_name, 'String')"+ }+ column "lc_workload" {+ type = "LowCardinality(String)"+ alias = "log_comment.workload"+ }+ column "lc_query__kind" {+ type = "LowCardinality(String)"+ alias = "if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind'))"+ }+ column "lc_query__query" {+ type = "String"+ alias = "multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query'))"+ }+ column "lc_query" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), '')"+ }+ column "lc_temporal__workflow_namespace" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_namespace`, 'String')"+ }+ column "lc_temporal__workflow_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_type`, 'String')"+ }+ column "lc_temporal__workflow_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_id`, 'String')"+ }+ column "lc_temporal__workflow_run_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.workflow_run_id`, 'String')"+ }+ column "lc_temporal__activity_type" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_type`, 'String')"+ }+ column "lc_temporal__activity_id" {+ type = "String"+ alias = "CAST(log_comment.`temporal.activity_id`, 'String')"+ }+ column "lc_temporal__attempt" {+ type = "Int64"+ alias = "log_comment.`temporal.attempt`"+ }+ column "lc_dagster__job_name" {+ type = "String"+ alias = "CAST(log_comment.`dagster.job_name`, 'String')"+ }+ column "lc_dagster__run_id" {+ type = "String"+ alias = "CAST(log_comment.`dagster.run_id`, 'String')"+ }+ column "lc_dagster__owner" {+ type = "String"+ alias = "CAST(log_comment.`dagster.tags.owner`, 'String')"+ }+ column "lc_modifiers" {+ type = "String"+ alias = "if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "sharded_query_log_archive"+ }+ }+ table "writable_query_log_archive" {+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email)"+ }+ column "ProfileEvents" {+ type = "Map(String, UInt64)"+ }+ engine "distributed" {+ cluster_name = "ops"+ remote_database = "posthog"+ remote_table = "query_log_archive_buffer"+ }+ }+ materialized_view "ops_query_log_archive_mv" {+ to_table = "posthog.writable_query_log_archive"+ query = file("sql/ops_query_log_archive_mv.sql")+ column "hostname" {+ type = "LowCardinality(String)"+ }+ column "user" {+ type = "LowCardinality(String)"+ }+ column "query_id" {+ type = "String"+ }+ column "initial_query_id" {+ type = "String"+ }+ column "is_initial_query" {+ type = "UInt8"+ }+ column "type" {+ type = "Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4)"+ }+ column "event_date" {+ type = "Date"+ }+ column "event_time" {+ type = "DateTime"+ }+ column "event_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_start_time" {+ type = "DateTime"+ }+ column "query_start_time_microseconds" {+ type = "DateTime64(6)"+ }+ column "query_duration_ms" {+ type = "UInt64"+ }+ column "read_rows" {+ type = "UInt64"+ }+ column "read_bytes" {+ type = "UInt64"+ }+ column "written_rows" {+ type = "UInt64"+ }+ column "written_bytes" {+ type = "UInt64"+ }+ column "result_rows" {+ type = "UInt64"+ }+ column "result_bytes" {+ type = "UInt64"+ }+ column "memory_usage" {+ type = "UInt64"+ }+ column "peak_threads_usage" {+ type = "UInt64"+ }+ column "current_database" {+ type = "LowCardinality(String)"+ }+ column "query" {+ type = "String"+ }+ column "formatted_query" {+ type = "String"+ }+ column "normalized_query_hash" {+ type = "UInt64"+ }+ column "query_kind" {+ type = "LowCardinality(String)"+ }+ column "exception_code" {+ type = "Int32"+ }+ column "exception" {+ type = "String"+ }+ column "stack_trace" {+ type = "String"+ }+ column "team_id" {+ type = "Int64"+ }+ column "log_comment" {+ type = "String"+ }+ column "ProfileEvents" {+ type = "Map(LowCardinality(String), UInt64)"+ }+ }+}diff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_backups.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_backups.sqlnew file mode 100644index 000000000000..e025c4cf64e5--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_backups.sql@@ -0,0 +1,16 @@+WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_datediff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_dictionaries.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_dictionaries.sqlnew file mode 100644index 000000000000..f9d92aa96dda--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_dictionaries.sql@@ -0,0 +1,23 @@+SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS ddiff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_part_counts.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_part_counts.sqlnew file mode 100644index 000000000000..da70c2431f7b--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_part_counts.sql@@ -0,0 +1,19 @@+SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ )diff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_replication_queue.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_replication_queue.sqlnew file mode 100644index 000000000000..e0b3019732fa--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_replication_queue.sql@@ -0,0 +1,17 @@+WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0diff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_server_crash.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_server_crash.sqlnew file mode 100644index 000000000000..61ffa6000986--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_server_crash.sql@@ -0,0 +1,10 @@+SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname()diff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_table_sizes.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_table_sizes.sqlnew file mode 100644index 000000000000..10d65a6e768f--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_table_sizes.sql@@ -0,0 +1,11 @@+SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL)diff --git a/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_test.sql b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_test.sqlnew file mode 100644index 000000000000..7ae1eaf428c2--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/custom_metrics_test.sql@@ -0,0 +1,6 @@+SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS typediff --git a/posthog/clickhouse/hcl/roles/shared/sql/ops_query_log_archive_mv.sql b/posthog/clickhouse/hcl/roles/shared/sql/ops_query_log_archive_mv.sqlnew file mode 100644index 000000000000..523c3d6af605--- /dev/null+++ b/posthog/clickhouse/hcl/roles/shared/sql/ops_query_log_archive_mv.sql@@ -0,0 +1,34 @@+SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart'diff --git a/posthog/clickhouse/hcl/sql/dev-logs.sql b/posthog/clickhouse/hcl/sql/dev-logs.sqlnew file mode 100644index 000000000000..5e8a5a7fa9f3--- /dev/null+++ b/posthog/clickhouse/hcl/sql/dev-logs.sql@@ -0,0 +1,790 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the dev/logs node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.kafka_logs_avro (+ uuid String,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ body String,+ severity_text String,+ severity_number Int32,+ service_name String,+ resource_attributes Map(LowCardinality(String), String),+ instrumentation_scope String,+ event_name String,+ attributes Map(LowCardinality(String), String)+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_logs', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-logs-avro-new\'', kafka_num_consumers = 8, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_logs\'';+CREATE TABLE posthog.kafka_metrics_avro (+ uuid String,+ trace_id String,+ span_id String,+ trace_flags Nullable(Int32),+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ service_name Nullable(String),+ metric_name Nullable(String),+ metric_type Nullable(String),+ value Nullable(Float64),+ count Nullable(Int64),+ histogram_bounds Array(Float64),+ histogram_counts Array(Int64),+ unit Nullable(String),+ aggregation_temporality Nullable(String),+ is_monotonic Nullable(UInt8),+ resource_attributes Map(String, String),+ instrumentation_scope Nullable(String),+ attributes Map(String, String)+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_metrics', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-metrics-avro-new\'', kafka_num_consumers = 8, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_metrics\'';+CREATE TABLE posthog.log_attributes2 (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String CODEC(ZSTD(5)),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String) DEFAULT 'log',+ original_expiry_time_bucket DateTime DEFAULT now(),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/log_attributes34', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(15) SETTINGS deduplicate_merge_projection_mode = 'drop', index_granularity = 8192;+CREATE TABLE posthog.log_attributes_distributed (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String CODEC(ZSTD(5)),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String) DEFAULT 'log',+ original_expiry_time_bucket DateTime DEFAULT now()+) ENGINE = Distributed('logs', 'posthog', 'log_attributes2');+CREATE TABLE posthog.logs34 (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6) CODEC(DoubleDelta),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ body String,+ severity_text LowCardinality(String),+ severity_number Int32,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ event_name String,+ attributes_map_str Map(LowCardinality(String), String),+ level String ALIAS severity_text,+ mat_body_ipv4_matches Array(String) ALIAS extractAll(body, '(\\d\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\.)(2, 2)([0-9]))'),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64,+ INDEX idx_severity_text_set severity_text TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_mat_body_ipv4_matches mat_body_ipv4_matches TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_body_ngram3 lower(body) TYPE ngrambf_v1(3, 25000, 2, 0) GRANULARITY 1,+ INDEX idx_uuid_bloom uuid TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_timestamp_minmax timestamp TYPE minmax GRANULARITY 1+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.logs34', '{replica}') ORDER BY (team_id, time_bucket, service_name, resource_fingerprint, severity_text, timestamp) PARTITION BY toDate(original_expiry_timestamp) TTL original_expiry_timestamp SETTINGS add_minmax_index_for_numeric_columns = 1, allow_experimental_reverse_key = 1, index_granularity = 8192, index_granularity_bytes = 104857600, map_serialization_version = 'with_buckets', ttl_only_drop_parts = 1;+CREATE TABLE posthog.logs_billing_metrics (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ bytes_uncompressed SimpleAggregateFunction(sum, UInt64),+ bytes_compressed SimpleAggregateFunction(sum, UInt64),+ record_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/logs_billing_metrics', '{replica}') ORDER BY (team_id, time_bucket, service_name) PARTITION BY toYYYYMM(time_bucket) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 8192;+CREATE TABLE posthog.logs_billing_metrics_distributed (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ bytes_uncompressed SimpleAggregateFunction(sum, UInt64),+ bytes_compressed SimpleAggregateFunction(sum, UInt64),+ record_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'logs_billing_metrics');+CREATE TABLE posthog.logs_distributed (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6) CODEC(DoubleDelta),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ body String,+ severity_text LowCardinality(String),+ severity_number Int32,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ event_name String,+ attributes_map_str Map(LowCardinality(String), String),+ level String ALIAS severity_text,+ mat_body_ipv4_matches Array(String) ALIAS extractAll(body, '(\\d\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\.)(2, 2)([0-9]))'),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64+) ENGINE = Distributed('logs', 'posthog', 'logs34');+CREATE TABLE posthog.logs_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/logs_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 8192;+CREATE TABLE posthog.logs_kafka_metrics_distributed (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'logs_kafka_metrics');+CREATE TABLE posthog.metric_attributes (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/posthog.metric_attributes', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(time_bucket) SETTINGS deduplicate_merge_projection_mode = 'drop', index_granularity = 8192;+CREATE TABLE posthog.metrics1 (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ service_name LowCardinality(String),+ metric_name LowCardinality(String),+ metric_type LowCardinality(String),+ value Float64,+ count UInt64 DEFAULT 1,+ histogram_bounds Array(Float64),+ histogram_counts Array(UInt64),+ unit LowCardinality(String),+ aggregation_temporality LowCardinality(String),+ is_monotonic Bool DEFAULT false,+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes_map_float Map(LowCardinality(String), Float64),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.metrics1', '{replica}') ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp) PARTITION BY toDate(timestamp) SETTINGS index_granularity = 8192, index_granularity_bytes = 104857600, ttl_only_drop_parts = 1;+CREATE TABLE posthog.metrics_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.kafka_logs34_avro_mv TO posthog.logs34 (uuid String, trace_id String, span_id String, trace_flags Int32, timestamp DateTime64(6), observed_timestamp DateTime64(6), body String, severity_text String, severity_number Int32, service_name String, instrumentation_scope String, event_name String, attributes_map_str Map(String, String), resource_attributes Map(String, String), team_id Int32, original_expiry_timestamp DateTime64(6), _partition UInt64, _topic LowCardinality(String), _offset UInt64, _record_count Int64, _bytes_uncompressed Nullable(Int64), _bytes_compressed Nullable(Int64)) AS SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avro;+CREATE MATERIALIZED VIEW posthog.kafka_logs_avro_billing_metrics_mv TO posthog.logs_billing_metrics (team_id Int32, time_bucket DateTime, service_name LowCardinality(String), bytes_uncompressed SimpleAggregateFunction(sum, Float64), bytes_compressed SimpleAggregateFunction(sum, Float64), record_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(floor(_bytes_uncompressed / _record_count)) AS bytes_uncompressed,+ sumSimpleState(floor(_bytes_compressed / _record_count)) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_name;+CREATE MATERIALIZED VIEW posthog.kafka_logs_avro_kafka_metrics_mv TO posthog.logs_kafka_metrics (_partition UInt32, _topic String, max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topic;+CREATE MATERIALIZED VIEW posthog.kafka_metrics_avro_kafka_metrics_mv TO posthog.metrics_kafka_metrics (_partition UInt64, _topic LowCardinality(String), max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topic;+CREATE MATERIALIZED VIEW posthog.kafka_metrics_avro_mv TO posthog.metrics1 (uuid String, trace_id String, span_id String, trace_flags Int32, timestamp DateTime64(6), observed_timestamp DateTime64(6), service_name String, metric_name String, metric_type String, value Float64, count UInt64, histogram_bounds Array(Float64), histogram_counts Array(UInt64), unit String, aggregation_temporality String, is_monotonic UInt8, resource_attributes Map(String, String), instrumentation_scope String, attributes_map_str Map(String, String), attributes_map_float Map(String, Nullable(Float64)), team_id Int32) AS SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0;+CREATE MATERIALIZED VIEW posthog.logs34_to_log_attributes TO posthog.log_attributes2 (team_id Int32, time_bucket DateTime64(0), original_expiry_time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ );+CREATE MATERIALIZED VIEW posthog.logs34_to_resource_attributes TO posthog.log_attributes2 (team_id Int32, time_bucket DateTime64(0), original_expiry_time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ );+CREATE MATERIALIZED VIEW posthog.metrics1_to_metric_attributes TO posthog.metric_attributes (team_id Int32, time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ );+CREATE MATERIALIZED VIEW posthog.metrics1_to_resource_attributes TO posthog.metric_attributes (team_id Int32, time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ );+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE TABLE posthog.metrics (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ service_name LowCardinality(String),+ metric_name LowCardinality(String),+ metric_type LowCardinality(String),+ value Float64,+ count UInt64 DEFAULT 1,+ histogram_bounds Array(Float64),+ histogram_counts Array(UInt64),+ unit LowCardinality(String),+ aggregation_temporality LowCardinality(String),+ is_monotonic Bool DEFAULT false,+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes_map_float Map(LowCardinality(String), Float64),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str)+) ENGINE = Distributed('logs', 'posthog', 'metrics1');+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );diff --git a/posthog/clickhouse/hcl/sql/dev-ops.sql b/posthog/clickhouse/hcl/sql/dev-ops.sqlnew file mode 100644index 000000000000..889ca2a83d70--- /dev/null+++ b/posthog/clickhouse/hcl/sql/dev-ops.sql@@ -0,0 +1,575 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the dev/ops node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.events_team_daily_stats (+ analysis_date Date,+ team_id Int64,+ event String,+ event_count UInt64,+ total_event_bytes UInt64,+ min_event_bytes UInt64,+ max_event_bytes UInt64,+ avg_event_bytes Float64,+ p50_event_bytes Float64,+ p90_event_bytes Float64,+ p95_event_bytes Float64,+ p99_event_bytes Float64,+ event_size_histogram Array(Tuple(Float64, Float64, UInt64)),+ computed_at DateTime+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.events_team_daily_stats', '{replica}') ORDER BY (analysis_date, team_id, event) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.prom_metrics_data (+ id UUID,+ timestamp DateTime64(3),+ value Float64+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.prom_metrics/data', '{replica}') ORDER BY (id, timestamp) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.prom_metrics_metrics (+ metric_family_name String,+ type String,+ unit String,+ help String+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.prom_metrics/metrics', '{replica}') ORDER BY (metric_family_name) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.prom_metrics_tags (+ id UUID DEFAULT reinterpretAsUUID(sipHash128(metric_name, all_tags)),+ metric_name LowCardinality(String),+ tags Map(LowCardinality(String), String),+ all_tags Map(String, String),+ min_time SimpleAggregateFunction(min, Nullable(DateTime64(3))),+ max_time SimpleAggregateFunction(max, Nullable(DateTime64(3)))+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/ops/tables/{shard}/posthog.prom_metrics/tags', '{replica}') PRIMARY KEY (metric_name) ORDER BY (metric_name, id) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.sharded_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/noshard/posthog.sharded_query_log_archive', '{replica}-{shard}') ORDER BY (team_id, event_date, event_time, query_id) PARTITION BY toYYYYMM(event_date) SETTINGS index_granularity = 8192, object_serialization_version = 'v3', object_shared_data_serialization_version = 'map_with_buckets';+CREATE TABLE posthog.writable_prom_metrics_data (+ id UUID,+ timestamp DateTime64(3),+ value Float64+) ENGINE = Buffer('posthog', 'prom_metrics_data', 1, 2, 5, 1, 1000000, 1, 100000000);+CREATE TABLE posthog.writable_prom_metrics_metrics (+ metric_family_name String,+ type String,+ unit String,+ help String+) ENGINE = Buffer('posthog', 'prom_metrics_metrics', 1, 2, 5, 1, 1000000, 1, 100000000);+CREATE TABLE posthog.writable_prom_metrics_tags (+ id UUID DEFAULT reinterpretAsUUID(sipHash128(metric_name, all_tags)),+ metric_name LowCardinality(String),+ tags Map(LowCardinality(String), String),+ all_tags Map(String, String),+ min_time SimpleAggregateFunction(min, Nullable(DateTime64(3))),+ max_time SimpleAggregateFunction(max, Nullable(DateTime64(3)))+) ENGINE = Buffer('posthog', 'prom_metrics_tags', 1, 2, 5, 1, 1000000, 1, 100000000);+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE VIEW posthog.daily_aggregated_query_log_archive AS SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label;+CREATE TABLE posthog.prom_metrics (+ id UUID DEFAULT reinterpretAsUUID(sipHash128(metric_name, all_tags)),+ timestamp DateTime64(3),+ value Float64,+ metric_name LowCardinality(String),+ tags Map(LowCardinality(String), String),+ all_tags Map(String, String),+ min_time Nullable(DateTime64(3)),+ max_time Nullable(DateTime64(3)),+ metric_family_name String,+ type String,+ unit String,+ help String+) ENGINE = TimeSeries SAMPLES posthog.prom_metrics_data TAGS posthog.prom_metrics_tags METRICS posthog.prom_metrics_metrics;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.query_log_archive_buffer (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Buffer('posthog', 'sharded_query_log_archive', 16, 10, 60, 10000, 1000000, 10000000, 100000000);+CREATE TABLE posthog.writable_prom_metrics (+ id UUID DEFAULT reinterpretAsUUID(sipHash128(metric_name, all_tags)),+ timestamp DateTime64(3),+ value Float64,+ metric_name LowCardinality(String),+ tags Map(LowCardinality(String), String),+ all_tags Map(String, String),+ min_time Nullable(DateTime64(3)),+ max_time Nullable(DateTime64(3)),+ metric_family_name String,+ type String,+ unit String,+ help String+) ENGINE = TimeSeries SAMPLES posthog.writable_prom_metrics_data TAGS posthog.writable_prom_metrics_tags METRICS posthog.writable_prom_metrics_metrics;+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );diff --git a/posthog/clickhouse/hcl/sql/local-ops.sql b/posthog/clickhouse/hcl/sql/local-ops.sqlnew file mode 100644index 000000000000..bda04eea146e--- /dev/null+++ b/posthog/clickhouse/hcl/sql/local-ops.sql@@ -0,0 +1,509 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the local/ops node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.events_team_daily_stats (+ analysis_date Date,+ team_id Int64,+ event String,+ event_count UInt64,+ total_event_bytes UInt64,+ min_event_bytes UInt64,+ max_event_bytes UInt64,+ avg_event_bytes Float64,+ p50_event_bytes Float64,+ p90_event_bytes Float64,+ p95_event_bytes Float64,+ p99_event_bytes Float64,+ event_size_histogram Array(Tuple(Float64, Float64, UInt64)),+ computed_at DateTime+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.events_team_daily_stats', '{replica}') ORDER BY (analysis_date, team_id, event) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.sharded_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/noshard/posthog.sharded_query_log_archive', '{replica}-{shard}') ORDER BY (team_id, event_date, event_time, query_id) PARTITION BY toYYYYMM(event_date) SETTINGS index_granularity = 8192, object_serialization_version = 'v3', object_shared_data_serialization_version = 'map_with_buckets';+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE VIEW posthog.daily_aggregated_query_log_archive AS SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.query_log_archive_buffer (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Buffer('posthog', 'sharded_query_log_archive', 16, 10, 60, 10000, 1000000, 10000000, 100000000);+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );diff --git a/posthog/clickhouse/hcl/sql/prod-eu-logs.sql b/posthog/clickhouse/hcl/sql/prod-eu-logs.sqlnew file mode 100644index 000000000000..af4ce4d704fd--- /dev/null+++ b/posthog/clickhouse/hcl/sql/prod-eu-logs.sql@@ -0,0 +1,1023 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the prod-eu/logs node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.kafka_logs_avro (+ uuid String,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ body String,+ severity_text String,+ severity_number Int32,+ service_name String,+ resource_attributes Map(LowCardinality(String), String),+ instrumentation_scope String,+ event_name String,+ attributes Map(LowCardinality(String), String),+ bytes_uncompressed Int64+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_logs', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-logs-avro-new\'', kafka_num_consumers = 8, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_logs\'';+CREATE TABLE posthog.kafka_metrics_avro (+ uuid String,+ trace_id String,+ span_id String,+ trace_flags Nullable(Int32),+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ service_name Nullable(String),+ metric_name Nullable(String),+ metric_type Nullable(String),+ value Nullable(Float64),+ count Nullable(Int64),+ histogram_bounds Array(Float64),+ histogram_counts Array(Int64),+ unit Nullable(String),+ aggregation_temporality Nullable(String),+ is_monotonic Nullable(UInt8),+ resource_attributes Map(String, String),+ instrumentation_scope Nullable(String),+ attributes Map(String, String)+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_metrics', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-metrics-avro-new\'', kafka_num_consumers = 8, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_metrics\'';+CREATE TABLE posthog.kafka_trace_spans_avro (+ uuid String,+ trace_id String,+ span_id String,+ parent_span_id String,+ trace_state String,+ name String,+ kind Int32,+ flags Int32,+ timestamp DateTime64(6),+ end_time DateTime64(6),+ observed_timestamp DateTime64(6),+ service_name String,+ resource_attributes Map(LowCardinality(String), String),+ instrumentation_scope String,+ attributes Map(LowCardinality(String), String),+ dropped_attributes_count Int32,+ events Array(String),+ dropped_events_count Int32,+ links Array(String),+ dropped_links_count Int32,+ status_code Int32+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_traces', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-traces-avro\'', kafka_num_consumers = 2, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_traces\'';+CREATE TABLE posthog.log_attributes2 (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String CODEC(ZSTD(5)),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String) DEFAULT 'log',+ original_expiry_time_bucket DateTime DEFAULT now(),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/log_attributes34', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(15) SETTINGS deduplicate_merge_projection_mode = 'drop', index_granularity = 8192;+CREATE TABLE posthog.log_attributes_distributed (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String) DEFAULT 'log',+ original_expiry_time_bucket DateTime DEFAULT now()+) ENGINE = Distributed('logs', 'posthog', 'log_attributes2');+CREATE TABLE posthog.logs34 (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6) CODEC(DoubleDelta),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ body String,+ severity_text LowCardinality(String),+ severity_number Int32,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ event_name String,+ attributes_map_str Map(LowCardinality(String), String),+ level String ALIAS severity_text,+ mat_body_ipv4_matches Array(String) ALIAS extractAll(body, '(\\d\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\.)(2, 2)([0-9]))'),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64,+ INDEX idx_severity_text_set severity_text TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_mat_body_ipv4_matches mat_body_ipv4_matches TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_body_ngram3 lower(body) TYPE ngrambf_v1(3, 25000, 2, 0) GRANULARITY 1,+ INDEX idx_uuid_bloom uuid TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_timestamp_minmax timestamp TYPE minmax GRANULARITY 1+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.logs34', '{replica}') ORDER BY (team_id, time_bucket, service_name, resource_fingerprint, severity_text, timestamp) PARTITION BY toDate(original_expiry_timestamp) TTL original_expiry_timestamp SETTINGS add_minmax_index_for_numeric_columns = 1, allow_experimental_reverse_key = 1, index_granularity = 8192, index_granularity_bytes = 104857600, map_serialization_version = 'with_buckets', storage_policy = 's3_tiered', ttl_only_drop_parts = 1;+CREATE TABLE posthog.logs_billing_metrics (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ bytes_uncompressed SimpleAggregateFunction(sum, UInt64),+ bytes_compressed SimpleAggregateFunction(sum, UInt64),+ record_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/logs_billing_metrics', '{replica}') ORDER BY (team_id, time_bucket, service_name) PARTITION BY toYYYYMM(time_bucket) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 8192;+CREATE TABLE posthog.logs_billing_metrics_distributed (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ bytes_uncompressed SimpleAggregateFunction(sum, UInt64),+ bytes_compressed SimpleAggregateFunction(sum, UInt64),+ record_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'logs_billing_metrics');+CREATE TABLE posthog.logs_distributed (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ body String,+ severity_text LowCardinality(String),+ severity_number Int32,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ event_name String,+ attributes_map_str Map(LowCardinality(String), String),+ level String ALIAS severity_text,+ mat_body_ipv4_matches Array(String) ALIAS extractAll(body, '(\\d\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\.)(2, 2)([0-9]))'),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64+) ENGINE = Distributed('logs', 'posthog', 'logs34');+CREATE TABLE posthog.logs_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/logs_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 8192;+CREATE TABLE posthog.logs_kafka_metrics_distributed (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'logs_kafka_metrics');+CREATE TABLE posthog.metric_attributes (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/posthog.metric_attributes', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(time_bucket) SETTINGS deduplicate_merge_projection_mode = 'drop', index_granularity = 8192;+CREATE TABLE posthog.metrics1 (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ service_name LowCardinality(String),+ metric_name LowCardinality(String),+ metric_type LowCardinality(String),+ value Float64 CODEC(Gorilla(8)),+ count UInt64 DEFAULT 1 CODEC(T64),+ histogram_bounds Array(Float64),+ histogram_counts Array(UInt64),+ unit LowCardinality(String),+ aggregation_temporality LowCardinality(String),+ is_monotonic Bool DEFAULT false,+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes_map_float Map(LowCardinality(String), Float64),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.metrics1', '{replica}') ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp) PARTITION BY toDate(timestamp) SETTINGS index_granularity = 8192, index_granularity_bytes = 104857600, ttl_only_drop_parts = 1;+CREATE TABLE posthog.metrics_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.trace_attributes (+ team_id Int32,+ original_expiry_time_bucket DateTime64(0),+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_type LowCardinality(String),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 4,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 4,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 4,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 4+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.trace_attributes', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(original_expiry_time_bucket) TTL original_expiry_time_bucket SETTINGS index_granularity = 8192;+CREATE TABLE posthog.trace_attributes_distributed (+ team_id Int32,+ original_expiry_time_bucket DateTime64(0),+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_type LowCardinality(String),+ attribute_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'trace_attributes');+CREATE TABLE posthog.trace_spans (+ time_bucket DateTime MATERIALIZED toStartOfInterval(timestamp, toIntervalHour(4)),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ parent_span_id String,+ is_root_span Bool MATERIALIZED replaceAll(trimRight(parent_span_id, '='), 'A', '') = '',+ trace_state String,+ name LowCardinality(String),+ kind Int8,+ flags UInt32,+ timestamp DateTime64(6),+ end_time DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ duration_nano UInt64 MATERIALIZED toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000,+ status_code Int16,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ dropped_attributes_count UInt32,+ dropped_events_count UInt32,+ dropped_links_count UInt32,+ events Array(String),+ links Array(String),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64,+ INDEX idx_name name TYPE ngrambf_v1(4, 5000, 2, 0) GRANULARITY 16,+ INDEX idx_kind kind TYPE minmax GRANULARITY 4,+ INDEX idx_duration duration_nano TYPE minmax GRANULARITY 1,+ INDEX idx_status_code status_code TYPE minmax GRANULARITY 1,+ INDEX idx_timestamp_minmax timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 16,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 16,+ INDEX idx_trace_bloom_part trace_id TYPE bloom_filter(0.00001) GRANULARITY 99999,+ INDEX idx_span_id_bloom_part span_id TYPE bloom_filter(0.00001) GRANULARITY 99999+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.trace_spans', '{replica}') ORDER BY (team_id, time_bucket, service_name, resource_fingerprint, status_code, name, timestamp) PARTITION BY toDate(original_expiry_timestamp) TTL original_expiry_timestamp SETTINGS allow_part_offset_column_in_projections = 1, index_granularity = 8192, index_granularity_bytes = 104857600, map_serialization_version = 'with_buckets', ttl_only_drop_parts = 1;+CREATE TABLE posthog.trace_spans_distributed (+ time_bucket DateTime MATERIALIZED toStartOfInterval(timestamp, toIntervalHour(4)),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ parent_span_id String,+ is_root_span Bool MATERIALIZED replaceAll(trimRight(parent_span_id, '='), 'A', '') = '',+ trace_state String,+ name LowCardinality(String),+ kind Int8,+ flags UInt32,+ timestamp DateTime64(6),+ end_time DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ duration_nano UInt64 MATERIALIZED toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000,+ status_code Int16,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ dropped_attributes_count UInt32,+ dropped_events_count UInt32,+ dropped_links_count UInt32,+ events Array(String),+ links Array(String),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64+) ENGINE = Distributed('logs', 'posthog', 'trace_spans');+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.kafka_logs34_avro_mv TO posthog.logs34 (uuid String, trace_id String, span_id String, trace_flags Int32, timestamp DateTime64(6), observed_timestamp DateTime64(6), body String, severity_text String, severity_number Int32, service_name String, instrumentation_scope String, event_name String, attributes_map_str Map(String, String), resource_attributes Map(String, String), team_id Int32, original_expiry_timestamp DateTime64(6), _partition UInt64, _topic LowCardinality(String), _offset UInt64, _record_count Int64, _bytes_uncompressed Nullable(Int64), _bytes_compressed Nullable(Int64)) AS SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes, bytes_uncompressed),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avro;+CREATE MATERIALIZED VIEW posthog.kafka_logs_avro_billing_metrics_mv TO posthog.logs_billing_metrics (team_id Int32, time_bucket DateTime, service_name LowCardinality(String), bytes_uncompressed SimpleAggregateFunction(sum, Float64), bytes_compressed SimpleAggregateFunction(sum, Float64), record_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(_bytes_uncompressed) AS bytes_uncompressed,+ sumSimpleState(_bytes_compressed) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_name;+CREATE MATERIALIZED VIEW posthog.kafka_logs_avro_kafka_metrics_mv TO posthog.logs_kafka_metrics (_partition UInt32, _topic String, max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topic;+CREATE MATERIALIZED VIEW posthog.kafka_metrics_avro_kafka_metrics_mv TO posthog.metrics_kafka_metrics (_partition UInt64, _topic LowCardinality(String), max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topic;+CREATE MATERIALIZED VIEW posthog.kafka_metrics_avro_mv TO posthog.metrics1 (uuid String, trace_id String, span_id String, trace_flags Int32, timestamp DateTime64(6), observed_timestamp DateTime64(6), service_name String, metric_name String, metric_type String, value Float64, count UInt64, histogram_bounds Array(Float64), histogram_counts Array(UInt64), unit String, aggregation_temporality String, is_monotonic UInt8, resource_attributes Map(String, String), instrumentation_scope String, attributes_map_str Map(String, String), attributes_map_float Map(String, Nullable(Float64)), team_id Int32) AS SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0;+CREATE MATERIALIZED VIEW posthog.kafka_trace_spans_avro_mv TO posthog.trace_spans (uuid String, trace_id String, span_id String, parent_span_id String, trace_state String, name String, kind Int8, flags UInt32, timestamp DateTime64(6), end_time DateTime64(6), observed_timestamp DateTime64(6), service_name String, resource_attributes Map(LowCardinality(String), String), instrumentation_scope String, attributes_map_str Map(LowCardinality(String), String), dropped_attributes_count UInt32, events Array(String), dropped_events_count UInt32, links Array(String), dropped_links_count UInt32, status_code Int16, team_id Int32) AS SELECT+ * EXCEPT(attributes, resource_attributes, kind, flags, dropped_attributes_count, dropped_events_count, dropped_links_count, status_code),+ toInt8(kind) AS kind,+ toUInt32(flags) AS flags,+ toUInt32(dropped_attributes_count) AS dropped_attributes_count,+ toUInt32(dropped_events_count) AS dropped_events_count,+ toUInt32(dropped_links_count) AS dropped_links_count,+ toInt16(status_code) AS status_code,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) AS _bytes_compressed+FROM posthog.kafka_trace_spans_avro;+CREATE MATERIALIZED VIEW posthog.logs34_to_log_attributes TO posthog.log_attributes2 (team_id Int32, time_bucket DateTime64(0), original_expiry_time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ );+CREATE MATERIALIZED VIEW posthog.logs34_to_resource_attributes TO posthog.log_attributes2 (team_id Int32, time_bucket DateTime64(0), original_expiry_time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ );+CREATE MATERIALIZED VIEW posthog.metrics1_to_metric_attributes TO posthog.metric_attributes (team_id Int32, time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ );+CREATE MATERIALIZED VIEW posthog.metrics1_to_resource_attributes TO posthog.metric_attributes (team_id Int32, time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ );+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE MATERIALIZED VIEW posthog.trace_span_to_attributes TO posthog.trace_attributes (team_id Int32, original_expiry_time_bucket DateTime64(0), time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ );+CREATE MATERIALIZED VIEW posthog.trace_span_to_resource_attributes TO posthog.trace_attributes (team_id Int32, original_expiry_time_bucket DateTime64(0), time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_resource_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ );+CREATE MATERIALIZED VIEW posthog.trace_span_to_span_attributes TO posthog.trace_attributes (team_id Int32, original_expiry_time_bucket DateTime64(0), time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ 'name' AS attribute_key,+ name AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, name+ );+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE TABLE posthog.metrics (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ service_name LowCardinality(String),+ metric_name LowCardinality(String),+ metric_type LowCardinality(String),+ value Float64 CODEC(Gorilla(8)),+ count UInt64 DEFAULT 1 CODEC(T64),+ histogram_bounds Array(Float64),+ histogram_counts Array(UInt64),+ unit LowCardinality(String),+ aggregation_temporality LowCardinality(String),+ is_monotonic Bool DEFAULT false,+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes_map_float Map(LowCardinality(String), Float64),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str)+) ENGINE = Distributed('logs', 'posthog', 'metrics1');+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );diff --git a/posthog/clickhouse/hcl/sql/prod-eu-ops.sql b/posthog/clickhouse/hcl/sql/prod-eu-ops.sqlnew file mode 100644index 000000000000..d7b89dc5ad71--- /dev/null+++ b/posthog/clickhouse/hcl/sql/prod-eu-ops.sql@@ -0,0 +1,600 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the prod-eu/ops node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.events_main (+ uuid UUID,+ event String,+ properties String,+ timestamp DateTime64(6, 'UTC'),+ team_id Int64,+ distinct_id String,+ elements_chain String,+ created_at DateTime64(6, 'UTC'),+ person_id UUID,+ person_created_at DateTime64(3),+ person_properties String,+ group0_properties String,+ group1_properties String,+ group2_properties String,+ group3_properties String,+ group4_properties String,+ group0_created_at DateTime64(3),+ group1_created_at DateTime64(3),+ group2_created_at DateTime64(3),+ group3_created_at DateTime64(3),+ group4_created_at DateTime64(3),+ person_mode Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2),+ _timestamp DateTime,+ _offset UInt64,+ inserted_at DateTime64(6, 'UTC')+) ENGINE = Distributed('posthog', 'posthog', 'sharded_events', sipHash64(distinct_id));+CREATE TABLE posthog.events_team_daily_stats (+ analysis_date Date,+ team_id Int64,+ event String,+ event_count UInt64,+ total_event_bytes UInt64,+ min_event_bytes UInt64,+ max_event_bytes UInt64,+ avg_event_bytes Float64,+ p50_event_bytes Float64,+ p90_event_bytes Float64,+ p95_event_bytes Float64,+ p99_event_bytes Float64,+ event_size_histogram Array(Tuple(Float64, Float64, UInt64)),+ computed_at DateTime+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.events_team_daily_stats', '{replica}') ORDER BY (analysis_date, team_id, event) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.metrics_exemplars (+ team_id UInt64,+ timestamp DateTime64(3, 'UTC'),+ id UInt64,+ value Float64,+ labels_json String+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_exemplars', '{replica}') ORDER BY (team_id, id, timestamp) PARTITION BY toYYYYMMDD(timestamp) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_histograms (+ team_id UInt64,+ metric_name LowCardinality(String),+ timestamp DateTime64(3, 'UTC'),+ id UInt64,+ histogram String,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_histograms', '{replica}', version) ORDER BY (team_id, id, timestamp) PARTITION BY toYYYYMMDD(timestamp) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_label_index (+ team_id UInt64,+ metric_name LowCardinality(String),+ label_name LowCardinality(String),+ label_value String,+ id UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_label_index', '{replica}') ORDER BY (team_id, metric_name, label_name, label_value, id) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 1024;+CREATE TABLE posthog.metrics_metadata (+ team_id UInt64,+ metric_family_name LowCardinality(String),+ type LowCardinality(String),+ unit String,+ help String,+ updated_at DateTime64(3, 'UTC')+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_metadata', '{replica}', updated_at) ORDER BY (team_id, metric_family_name) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_samples (+ team_id UInt64,+ metric_name LowCardinality(String),+ timestamp DateTime64(3, 'UTC'),+ id UInt64,+ value Float64+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_samples', '{replica}') ORDER BY (team_id, metric_name, id, timestamp) PARTITION BY toYYYYMMDD(timestamp) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_series (+ team_id UInt64,+ id UInt64,+ metric_name LowCardinality(String),+ labels_json String,+ min_time DateTime64(3, 'UTC'),+ max_time DateTime64(3, 'UTC')+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_series', '{replica}') ORDER BY (team_id, metric_name, id) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.sharded_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/noshard/posthog.sharded_query_log_archive', '{replica}-{shard}') ORDER BY (team_id, event_date, event_time, query_id) PARTITION BY toYYYYMM(event_date) SETTINGS index_granularity = 8192, object_serialization_version = 'v3', object_shared_data_serialization_version = 'map_with_buckets';+CREATE TABLE posthog.sharded_tophog (+ timestamp DateTime64(6, 'UTC'),+ metric LowCardinality(String),+ type LowCardinality(String) DEFAULT 'sum',+ key Map(LowCardinality(String), String),+ value Float64,+ count UInt64 DEFAULT 0,+ pipeline LowCardinality(String),+ lane LowCardinality(String),+ labels Map(LowCardinality(String), String)+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/ops/{shard}/posthog.tophog', '{replica}') ORDER BY (pipeline, lane, metric, timestamp, key) PARTITION BY toYYYYMMDD(timestamp) TTL toDate(timestamp) + toIntervalDay(30) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;+CREATE MATERIALIZED VIEW posthog.metrics_label_index_from_series_mv TO posthog.metrics_label_index (team_id UInt64, metric_name LowCardinality(String), label_name LowCardinality(String), label_value String, id UInt64) AS SELECT+ team_id,+ metric_name,+ tupleElement(label_pair, 1) AS label_name,+ tupleElement(label_pair, 2) AS label_value,+ id+FROM+ posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair;+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE VIEW posthog.daily_aggregated_query_log_archive AS SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.query_log_archive_buffer (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Buffer('posthog', 'sharded_query_log_archive', 16, 10, 60, 10000, 1000000, 10000000, 100000000);+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );diff --git a/posthog/clickhouse/hcl/sql/prod-us-logs.sql b/posthog/clickhouse/hcl/sql/prod-us-logs.sqlnew file mode 100644index 000000000000..6158795ff48a--- /dev/null+++ b/posthog/clickhouse/hcl/sql/prod-us-logs.sql@@ -0,0 +1,1036 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the prod-us/logs node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.kafka_logs_avro (+ uuid String,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ body String,+ severity_text String,+ severity_number Int32,+ service_name String,+ resource_attributes Map(LowCardinality(String), String),+ instrumentation_scope String,+ event_name String,+ attributes Map(LowCardinality(String), String)+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_logs', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-logs-avro-new\'', kafka_num_consumers = 32, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_logs\'';+CREATE TABLE posthog.kafka_metrics_avro (+ uuid String,+ trace_id String,+ span_id String,+ trace_flags Nullable(Int32),+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ service_name Nullable(String),+ metric_name Nullable(String),+ metric_type Nullable(String),+ value Nullable(Float64),+ count Nullable(Int64),+ histogram_bounds Array(Float64),+ histogram_counts Array(Int64),+ unit Nullable(String),+ aggregation_temporality Nullable(String),+ is_monotonic Nullable(UInt8),+ resource_attributes Map(String, String),+ instrumentation_scope Nullable(String),+ attributes Map(String, String)+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_metrics', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-metrics-avro-new\'', kafka_num_consumers = 8, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_metrics\'';+CREATE TABLE posthog.kafka_trace_spans_avro (+ uuid String,+ trace_id String,+ span_id String,+ parent_span_id String,+ trace_state String,+ name String,+ kind Int32,+ flags Int32,+ timestamp DateTime64(6),+ end_time DateTime64(6),+ observed_timestamp DateTime64(6),+ service_name String,+ resource_attributes Map(LowCardinality(String), String),+ instrumentation_scope String,+ attributes Map(LowCardinality(String), String),+ dropped_attributes_count Int32,+ events Array(String),+ dropped_events_count Int32,+ links Array(String),+ dropped_links_count Int32,+ status_code Int32+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_traces', kafka_format = 'kafka_format = \'Avro\'', kafka_group_name = 'kafka_group_name = \'clickhouse-traces-avro\'', kafka_num_consumers = 8, kafka_poll_max_batch_size = 1000, kafka_poll_timeout_ms = 3000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_traces\'';+CREATE TABLE posthog.log_attributes2 (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String CODEC(ZSTD(5)),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String) DEFAULT 'log',+ original_expiry_time_bucket DateTime DEFAULT now(),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/log_attributes34', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(time_bucket) TTL time_bucket + toIntervalDay(15) SETTINGS deduplicate_merge_projection_mode = 'drop', index_granularity = 8192;+CREATE TABLE posthog.log_attributes_distributed (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String CODEC(ZSTD(5)),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String) DEFAULT 'log',+ original_expiry_time_bucket DateTime DEFAULT now()+) ENGINE = Distributed('logs', 'posthog', 'log_attributes2');+CREATE TABLE posthog.logs34 (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6) CODEC(DoubleDelta),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ body String,+ severity_text LowCardinality(String),+ severity_number Int32,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ event_name String,+ attributes_map_str Map(LowCardinality(String), String),+ level String ALIAS severity_text,+ mat_body_ipv4_matches Array(String) ALIAS extractAll(body, '(\\d\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\.)(2, 2)([0-9]))'),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64,+ INDEX idx_severity_text_set severity_text TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_mat_body_ipv4_matches mat_body_ipv4_matches TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_body_ngram3 lower(body) TYPE ngrambf_v1(3, 25000, 2, 0) GRANULARITY 1,+ INDEX idx_uuid_bloom uuid TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_timestamp_minmax timestamp TYPE minmax GRANULARITY 1+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.logs34', '{replica}') ORDER BY (team_id, time_bucket, service_name, resource_fingerprint, severity_text, timestamp) PARTITION BY toDate(original_expiry_timestamp) TTL original_expiry_timestamp SETTINGS add_minmax_index_for_numeric_columns = 1, allow_experimental_reverse_key = 1, index_granularity = 8192, index_granularity_bytes = 104857600, map_buckets_strategy = 'constant', map_serialization_version = 'with_buckets', max_buckets_in_map = 32, storage_policy = 's3_tiered', ttl_only_drop_parts = 1;+CREATE TABLE posthog.logs_billing_metrics (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ bytes_uncompressed SimpleAggregateFunction(sum, UInt64),+ bytes_compressed SimpleAggregateFunction(sum, UInt64),+ record_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/logs_billing_metrics', '{replica}') ORDER BY (team_id, time_bucket, service_name) PARTITION BY toYYYYMM(time_bucket) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 8192;+CREATE TABLE posthog.logs_billing_metrics_distributed (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ bytes_uncompressed SimpleAggregateFunction(sum, UInt64),+ bytes_compressed SimpleAggregateFunction(sum, UInt64),+ record_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'logs_billing_metrics');+CREATE TABLE posthog.logs_distributed (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6) CODEC(DoubleDelta),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ body String,+ severity_text LowCardinality(String),+ severity_number Int32,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ event_name String,+ attributes_map_str Map(LowCardinality(String), String),+ level String ALIAS severity_text,+ mat_body_ipv4_matches Array(String) ALIAS extractAll(body, '(\\d\\.((25[0-5]|(2[0-4]|1(0, 1)[0-9])(0, 1)[0-9])\\.)(2, 2)([0-9]))'),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64+) ENGINE = Distributed('logs', 'posthog', 'logs34');+CREATE TABLE posthog.logs_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/logs_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 8192;+CREATE TABLE posthog.logs_kafka_metrics_distributed (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'logs_kafka_metrics');+CREATE TABLE posthog.metric_attributes (+ team_id Int32,+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_count SimpleAggregateFunction(sum, UInt64),+ attribute_type LowCardinality(String),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 1+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/posthog.metric_attributes', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(time_bucket) SETTINGS deduplicate_merge_projection_mode = 'drop', index_granularity = 8192;+CREATE TABLE posthog.metrics1 (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ service_name LowCardinality(String),+ metric_name LowCardinality(String),+ metric_type LowCardinality(String),+ value Float64 CODEC(Gorilla(8)),+ count UInt64 DEFAULT 1 CODEC(T64),+ histogram_bounds Array(Float64),+ histogram_counts Array(UInt64),+ unit LowCardinality(String),+ aggregation_temporality LowCardinality(String),+ is_monotonic Bool DEFAULT false,+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes_map_float Map(LowCardinality(String), Float64),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ INDEX idx_metric_name_set metric_name TYPE set(100) GRANULARITY 1,+ INDEX idx_metric_type_set metric_type TYPE set(10) GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 1,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.metrics1', '{replica}') ORDER BY (team_id, time_bucket, service_name, metric_name, resource_fingerprint, timestamp) PARTITION BY toDate(timestamp) SETTINGS index_granularity = 8192, index_granularity_bytes = 104857600, ttl_only_drop_parts = 1;+CREATE TABLE posthog.metrics_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedAggregatingMergeTree('/clickhouse/tables/logs/{shard}/posthog.metrics_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.trace_attributes (+ team_id Int32,+ original_expiry_time_bucket DateTime64(0),+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_type LowCardinality(String),+ attribute_count SimpleAggregateFunction(sum, UInt64),+ INDEX idx_attribute_key attribute_key TYPE bloom_filter(0.01) GRANULARITY 4,+ INDEX idx_attribute_value attribute_value TYPE bloom_filter(0.01) GRANULARITY 4,+ INDEX idx_attribute_key_n3 attribute_key TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 4,+ INDEX idx_attribute_value_n3 attribute_value TYPE ngrambf_v1(3, 32768, 3, 0) GRANULARITY 4+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.trace_attributes', '{replica}') ORDER BY (team_id, attribute_type, time_bucket, resource_fingerprint, attribute_key, attribute_value) PARTITION BY toDate(original_expiry_time_bucket) TTL original_expiry_time_bucket SETTINGS index_granularity = 8192;+CREATE TABLE posthog.trace_attributes_distributed (+ team_id Int32,+ original_expiry_time_bucket DateTime64(0),+ time_bucket DateTime64(0),+ service_name LowCardinality(String),+ resource_fingerprint UInt64 DEFAULT 0,+ attribute_key LowCardinality(String),+ attribute_value String,+ attribute_type LowCardinality(String),+ attribute_count SimpleAggregateFunction(sum, UInt64)+) ENGINE = Distributed('logs', 'posthog', 'trace_attributes');+CREATE TABLE posthog.trace_spans (+ time_bucket DateTime MATERIALIZED toStartOfInterval(timestamp, toIntervalHour(4)),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ parent_span_id String,+ is_root_span Bool MATERIALIZED replaceAll(trimRight(parent_span_id, '='), 'A', '') = '',+ trace_state String,+ name LowCardinality(String),+ kind Int8,+ flags UInt32,+ timestamp DateTime64(6),+ end_time DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ duration_nano UInt64 MATERIALIZED toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000,+ status_code Int16,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ dropped_attributes_count UInt32,+ dropped_events_count UInt32,+ dropped_links_count UInt32,+ events Array(String),+ links Array(String),+ _partition UInt32,+ _topic String,+ _offset UInt64,+ _bytes_uncompressed UInt64,+ _bytes_compressed UInt64,+ _record_count UInt64,+ INDEX idx_name name TYPE ngrambf_v1(4, 5000, 2, 0) GRANULARITY 16,+ INDEX idx_kind kind TYPE minmax GRANULARITY 4,+ INDEX idx_duration duration_nano TYPE minmax GRANULARITY 1,+ INDEX idx_status_code status_code TYPE minmax GRANULARITY 1,+ INDEX idx_timestamp_minmax timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_observed_minmax observed_timestamp TYPE minmax GRANULARITY 1,+ INDEX idx_attributes_str_keys mapKeys(attributes_map_str) TYPE bloom_filter(0.01) GRANULARITY 16,+ INDEX idx_attributes_str_values mapValues(attributes_map_str) TYPE bloom_filter(0.001) GRANULARITY 16,+ INDEX idx_trace_bloom_part trace_id TYPE bloom_filter(0.00001) GRANULARITY 99999,+ INDEX idx_span_id_bloom_part span_id TYPE bloom_filter(0.00001) GRANULARITY 99999+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.trace_spans', '{replica}') ORDER BY (team_id, time_bucket, service_name, resource_fingerprint, status_code, name, timestamp) PARTITION BY toDate(original_expiry_timestamp) TTL original_expiry_timestamp SETTINGS allow_part_offset_column_in_projections = 1, index_granularity = 8192, index_granularity_bytes = 104857600, map_serialization_version = 'with_buckets', ttl_only_drop_parts = 1;+CREATE TABLE posthog.trace_spans_distributed (+ time_bucket DateTime MATERIALIZED toStartOfInterval(timestamp, toIntervalHour(4)),+ original_expiry_timestamp DateTime64(6),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ parent_span_id String,+ is_root_span Bool MATERIALIZED replaceAll(trimRight(parent_span_id, '='), 'A', '') = '',+ trace_state String,+ name LowCardinality(String),+ kind Int8,+ flags UInt32,+ timestamp DateTime64(6),+ end_time DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ duration_nano UInt64 MATERIALIZED toUInt64(dateDiff('microsecond', timestamp, end_time)) * 1000,+ status_code Int16,+ service_name LowCardinality(String),+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes Map(LowCardinality(String), String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str),+ attributes_map_float Map(LowCardinality(String), Float64) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__float'), toFloat64OrNull(v)), attributes_map_str)),+ attributes_map_datetime Map(LowCardinality(String), DateTime64(6)) MATERIALIZED mapFilter((k, v) -> (v IS NOT NULL), mapApply((k, v) -> (concat(left(k, -5), '__datetime'), parseDateTimeBestEffortOrNull(v, 6)), attributes_map_str)),+ dropped_attributes_count UInt32,+ dropped_events_count UInt32,+ dropped_links_count UInt32,+ events Array(String),+ links Array(String)+) ENGINE = Distributed('logs', 'posthog', 'trace_spans');+CREATE TABLE posthog.trace_spans_kafka_metrics (+ _partition UInt32,+ _topic String,+ max_offset SimpleAggregateFunction(max, UInt64),+ max_observed_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_timestamp SimpleAggregateFunction(max, DateTime64(9)),+ max_created_at SimpleAggregateFunction(max, DateTime64(9)),+ max_lag SimpleAggregateFunction(max, UInt64)+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/logs/{shard}/posthog.trace_spans_kafka_metrics', '{replica}') ORDER BY (_topic, _partition) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.kafka_logs34_avro_mv TO posthog.logs34 (uuid String, trace_id String, span_id String, trace_flags Int32, timestamp DateTime64(6), observed_timestamp DateTime64(6), body String, severity_text String, severity_number Int32, service_name String, instrumentation_scope String, event_name String, attributes_map_str Map(String, String), resource_attributes Map(String, String), team_id Int32, original_expiry_timestamp DateTime64(6), _partition UInt64, _topic LowCardinality(String), _offset UInt64, _record_count Int64, _bytes_uncompressed Nullable(Int64), _bytes_compressed Nullable(Int64)) AS SELECT+ kafka_logs_avro.* EXCEPT(created_at, attribute_values, attribute_keys, attributes, attributes_map_str, attributes_map_float, attributes_map_datetime, resource_attributes),+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ observed_timestamp+ + toIntervalDay(+ toInt32OrDefault(_headers.value[indexOf(_headers.name, 'retention-days')], toInt32(15))+ ) AS original_expiry_timestamp,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) / _record_count AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) / _record_count AS _bytes_compressed+FROM posthog.kafka_logs_avro;+CREATE MATERIALIZED VIEW posthog.kafka_logs_avro_billing_metrics_mv TO posthog.logs_billing_metrics (team_id Int32, time_bucket DateTime, service_name LowCardinality(String), bytes_uncompressed SimpleAggregateFunction(sum, Float64), bytes_compressed SimpleAggregateFunction(sum, Float64), record_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ sumSimpleState(floor(_bytes_uncompressed / _record_count)) AS bytes_uncompressed,+ sumSimpleState(floor(_bytes_compressed / _record_count)) AS bytes_compressed,+ sumSimpleState(1) AS record_count+FROM+ (+ SELECT+ team_id,+ toStartOfInterval(timestamp, toIntervalMinute(1)) AS time_bucket,+ service_name AS service_name,+ _record_count,+ _bytes_uncompressed,+ _bytes_compressed+ FROM posthog.logs34+ )+GROUP BY+ team_id, time_bucket, service_name;+CREATE MATERIALIZED VIEW posthog.kafka_logs_avro_kafka_metrics_mv TO posthog.logs_kafka_metrics (_partition UInt32, _topic String, max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.logs34+GROUP BY+ _partition, _topic;+CREATE MATERIALIZED VIEW posthog.kafka_metrics_avro_kafka_metrics_mv TO posthog.metrics_kafka_metrics (_partition UInt64, _topic LowCardinality(String), max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.kafka_metrics_avro+GROUP BY+ _partition, _topic;+CREATE MATERIALIZED VIEW posthog.kafka_metrics_avro_mv TO posthog.metrics1 (uuid String, trace_id String, span_id String, trace_flags Int32, timestamp DateTime64(6), observed_timestamp DateTime64(6), service_name String, metric_name String, metric_type String, value Float64, count UInt64, histogram_bounds Array(Float64), histogram_counts Array(UInt64), unit String, aggregation_temporality String, is_monotonic UInt8, resource_attributes Map(String, String), instrumentation_scope String, attributes_map_str Map(String, String), attributes_map_float Map(String, Nullable(Float64)), team_id Int32) AS SELECT+ uuid,+ trace_id,+ span_id,+ ifNull(trace_flags, 0) AS trace_flags,+ timestamp,+ observed_timestamp,+ ifNull(service_name, '') AS service_name,+ ifNull(metric_name, '') AS metric_name,+ ifNull(metric_type, '') AS metric_type,+ ifNull(value, 0) AS value,+ toUInt64(ifNull(count, 1)) AS count,+ histogram_bounds,+ arrayMap(x -> toUInt64(x), histogram_counts) AS histogram_counts,+ ifNull(unit, '') AS unit,+ ifNull(aggregation_temporality, '') AS aggregation_temporality,+ ifNull(is_monotonic, 0) AS is_monotonic,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ ifNull(instrumentation_scope, '') AS instrumentation_scope,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(+ mapFilter(+ (k, v) -> isNotNull(v),+ mapApply(+ (k, v) -> (concat(k, '__float'), toFloat64OrNull(JSONExtract(v, 'String'))),+ attributes+ )+ )+ ) AS attributes_map_float,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id+FROM posthog.kafka_metrics_avro+SETTINGS+ min_insert_block_size_rows = 0,+ min_insert_block_size_bytes = 0;+CREATE MATERIALIZED VIEW posthog.kafka_trace_spans_avro_mv TO posthog.trace_spans (uuid String, trace_id String, span_id String, parent_span_id String, trace_state String, name String, kind Int8, flags UInt32, timestamp DateTime64(6), end_time DateTime64(6), observed_timestamp DateTime64(6), service_name String, resource_attributes Map(LowCardinality(String), String), instrumentation_scope String, attributes_map_str Map(LowCardinality(String), String), dropped_attributes_count UInt32, events Array(String), dropped_events_count UInt32, links Array(String), dropped_links_count UInt32, status_code Int16, team_id Int32) AS SELECT+ * EXCEPT(attributes, resource_attributes, kind, flags, dropped_attributes_count, dropped_events_count, dropped_links_count, status_code),+ toInt8(kind) AS kind,+ toUInt32(flags) AS flags,+ toUInt32(dropped_attributes_count) AS dropped_attributes_count,+ toUInt32(dropped_events_count) AS dropped_events_count,+ toUInt32(dropped_links_count) AS dropped_links_count,+ toInt16(status_code) AS status_code,+ mapSort(mapApply((k, v) -> (concat(k, '__str'), JSONExtractString(v)), attributes)) AS attributes_map_str,+ mapSort(mapApply((k, v) -> (k, JSONExtractString(v)), resource_attributes)) AS resource_attributes,+ toInt32OrZero(_headers.value[indexOf(_headers.name, 'team_id')]) AS team_id,+ _partition,+ _topic,+ _offset,+ toInt64OrDefault(_headers.value[indexOf(_headers.name, 'record_count')], toInt64(1)) AS _record_count,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_uncompressed')]) AS _bytes_uncompressed,+ toInt64OrNull(_headers.value[indexOf(_headers.name, 'bytes_compressed')]) AS _bytes_compressed+FROM posthog.kafka_trace_spans_avro;+CREATE MATERIALIZED VIEW posthog.logs34_to_log_attributes TO posthog.log_attributes2 (team_id Int32, time_bucket DateTime64(0), original_expiry_time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'log' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, attributes+ );+CREATE MATERIALIZED VIEW posthog.logs34_to_resource_attributes TO posthog.log_attributes2 (team_id Int32, time_bucket DateTime64(0), original_expiry_time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ original_expiry_time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.logs34+ GROUP BY+ team_id, time_bucket, original_expiry_time_bucket, service_name, resource_fingerprint, resource_attributes+ );+CREATE MATERIALIZED VIEW posthog.metrics1_to_metric_attributes TO posthog.metric_attributes (team_id Int32, time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes) AS attributes,+ arrayJoin(attributes) AS attribute,+ 'metric' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, attributes+ );+CREATE MATERIALIZED VIEW posthog.metrics1_to_resource_attributes TO posthog.metric_attributes (team_id Int32, time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ 'resource' AS attribute_type,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.metrics1+ GROUP BY+ team_id, time_bucket, service_name, resource_fingerprint, resource_attributes+ );+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE MATERIALIZED VIEW posthog.trace_span_to_attributes TO posthog.trace_attributes (team_id Int32, original_expiry_time_bucket DateTime64(0), time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(mapFilter((k, v) -> ((length(k) < 256) AND (length(v) < 256)), attributes)) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ );+CREATE MATERIALIZED VIEW posthog.trace_span_to_resource_attributes TO posthog.trace_attributes (team_id Int32, original_expiry_time_bucket DateTime64(0), time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span_resource_attribute' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ arrayJoin(resource_attributes) AS attribute,+ attribute.1 AS attribute_key,+ attribute.2 AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, attribute+ );+CREATE MATERIALIZED VIEW posthog.trace_span_to_span_attributes TO posthog.trace_attributes (team_id Int32, original_expiry_time_bucket DateTime64(0), time_bucket DateTime64(0), service_name LowCardinality(String), resource_fingerprint UInt64, attribute_key LowCardinality(String), attribute_value String, attribute_type LowCardinality(String), attribute_count SimpleAggregateFunction(sum, UInt64)) AS SELECT+ team_id,+ original_expiry_time_bucket,+ time_bucket,+ service_name,+ resource_fingerprint,+ attribute_key,+ attribute_value,+ 'span' AS attribute_type,+ attribute_count+FROM+ (+ SELECT+ team_id AS team_id,+ toStartOfInterval(original_expiry_timestamp, toIntervalMinute(10)) AS original_expiry_time_bucket,+ toStartOfInterval(timestamp, toIntervalMinute(10)) AS time_bucket,+ service_name AS service_name,+ resource_fingerprint,+ 'name' AS attribute_key,+ name AS attribute_value,+ sumSimpleState(1) AS attribute_count+ FROM posthog.trace_spans+ GROUP BY+ team_id, original_expiry_time_bucket, time_bucket, service_name, resource_fingerprint, name+ );+CREATE MATERIALIZED VIEW posthog.trace_spans_to_kafka_metrics_mv TO posthog.trace_spans_kafka_metrics (_partition UInt64, _topic LowCardinality(String), max_offset SimpleAggregateFunction(max, UInt64), max_observed_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_timestamp SimpleAggregateFunction(max, DateTime64(6)), max_created_at SimpleAggregateFunction(max, DateTime), max_lag SimpleAggregateFunction(max, Decimal(18, 6))) AS SELECT+ _partition,+ _topic,+ maxSimpleState(_offset) AS max_offset,+ maxSimpleState(observed_timestamp) AS max_observed_timestamp,+ maxSimpleState(timestamp) AS max_timestamp,+ maxSimpleState(now()) AS max_created_at,+ maxSimpleState(now() - observed_timestamp) AS max_lag+FROM posthog.trace_spans+GROUP BY+ _partition, _topic;+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE TABLE posthog.metrics (+ time_bucket DateTime MATERIALIZED toStartOfDay(timestamp),+ uuid String,+ team_id Int32,+ trace_id String,+ span_id String,+ trace_flags Int32,+ timestamp DateTime64(6),+ observed_timestamp DateTime64(6),+ created_at DateTime64(6) MATERIALIZED now(),+ service_name LowCardinality(String),+ metric_name LowCardinality(String),+ metric_type LowCardinality(String),+ value Float64 CODEC(Gorilla(8)),+ count UInt64 DEFAULT 1 CODEC(T64),+ histogram_bounds Array(Float64),+ histogram_counts Array(UInt64),+ unit LowCardinality(String),+ aggregation_temporality LowCardinality(String),+ is_monotonic Bool DEFAULT false,+ resource_attributes Map(LowCardinality(String), String),+ resource_fingerprint UInt64 MATERIALIZED cityHash64(resource_attributes),+ instrumentation_scope String,+ attributes_map_str Map(LowCardinality(String), String),+ attributes_map_float Map(LowCardinality(String), Float64),+ time_minute DateTime ALIAS toStartOfMinute(timestamp),+ attributes Map(String, String) ALIAS mapApply((k, v) -> (left(k, -5), v), attributes_map_str)+) ENGINE = Distributed('logs', 'posthog', 'metrics1');+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );diff --git a/posthog/clickhouse/hcl/sql/prod-us-ops.sql b/posthog/clickhouse/hcl/sql/prod-us-ops.sqlnew file mode 100644index 000000000000..daaef93c0e98--- /dev/null+++ b/posthog/clickhouse/hcl/sql/prod-us-ops.sql@@ -0,0 +1,628 @@+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.+-- Full CREATE schema for the prod-us/ops node. Apply to a fresh ClickHouse to build it.++CREATE TABLE posthog.events_main (+ uuid UUID,+ event String,+ properties String,+ timestamp DateTime64(6, 'UTC'),+ team_id Int64,+ distinct_id String,+ elements_chain String,+ created_at DateTime64(6, 'UTC'),+ person_id UUID,+ person_created_at DateTime64(3),+ person_properties String,+ group0_properties String,+ group1_properties String,+ group2_properties String,+ group3_properties String,+ group4_properties String,+ group0_created_at DateTime64(3),+ group1_created_at DateTime64(3),+ group2_created_at DateTime64(3),+ group3_created_at DateTime64(3),+ group4_created_at DateTime64(3),+ person_mode Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2),+ _timestamp DateTime,+ _offset UInt64,+ inserted_at DateTime64(6, 'UTC')+) ENGINE = Distributed('posthog', 'posthog', 'sharded_events', sipHash64(distinct_id));+CREATE TABLE posthog.events_recent (+ uuid UUID,+ event String,+ properties String,+ timestamp DateTime64(6, 'UTC'),+ team_id Int64,+ distinct_id String,+ elements_chain String,+ created_at DateTime64(6, 'UTC'),+ person_id UUID,+ person_created_at DateTime64(3),+ person_properties String,+ group0_properties String,+ group1_properties String,+ group2_properties String,+ group3_properties String,+ group4_properties String,+ group0_created_at DateTime64(3),+ group1_created_at DateTime64(3),+ group2_created_at DateTime64(3),+ group3_created_at DateTime64(3),+ group4_created_at DateTime64(3),+ person_mode Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2),+ _timestamp DateTime,+ _offset UInt64,+ inserted_at DateTime64(6, 'UTC')+) ENGINE = Distributed('batch_exports', 'posthog', 'sharded_events_recent', sipHash64(distinct_id));+CREATE TABLE posthog.events_team_daily_stats (+ analysis_date Date,+ team_id Int64,+ event String,+ event_count UInt64,+ total_event_bytes UInt64,+ min_event_bytes UInt64,+ max_event_bytes UInt64,+ avg_event_bytes Float64,+ p50_event_bytes Float64,+ p90_event_bytes Float64,+ p95_event_bytes Float64,+ p99_event_bytes Float64,+ event_size_histogram Array(Tuple(Float64, Float64, UInt64)),+ computed_at DateTime+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.events_team_daily_stats', '{replica}') ORDER BY (analysis_date, team_id, event) SETTINGS index_granularity = 8192;+CREATE TABLE posthog.metrics_exemplars (+ team_id UInt64,+ timestamp DateTime64(3, 'UTC'),+ id UInt64,+ value Float64,+ labels_json String+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_exemplars', '{replica}') ORDER BY (team_id, id, timestamp) PARTITION BY toYYYYMMDD(timestamp) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_histograms (+ team_id UInt64,+ metric_name LowCardinality(String),+ timestamp DateTime64(3, 'UTC'),+ id UInt64,+ histogram String,+ version UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_histograms', '{replica}', version) ORDER BY (team_id, id, timestamp) PARTITION BY toYYYYMMDD(timestamp) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_label_index (+ team_id UInt64,+ metric_name LowCardinality(String),+ label_name LowCardinality(String),+ label_value String,+ id UInt64+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_label_index', '{replica}') ORDER BY (team_id, metric_name, label_name, label_value, id) SETTINGS deduplicate_merge_projection_mode = 'rebuild', index_granularity = 1024;+CREATE TABLE posthog.metrics_metadata (+ team_id UInt64,+ metric_family_name LowCardinality(String),+ type LowCardinality(String),+ unit String,+ help String,+ updated_at DateTime64(3, 'UTC')+) ENGINE = ReplicatedReplacingMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_metadata', '{replica}', updated_at) ORDER BY (team_id, metric_family_name) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_samples (+ team_id UInt64,+ metric_name LowCardinality(String),+ timestamp DateTime64(3, 'UTC'),+ id UInt64,+ value Float64+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_samples', '{replica}') ORDER BY (team_id, metric_name, id, timestamp) PARTITION BY toYYYYMMDD(timestamp) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.metrics_series (+ team_id UInt64,+ id UInt64,+ metric_name LowCardinality(String),+ labels_json String,+ min_time DateTime64(3, 'UTC'),+ max_time DateTime64(3, 'UTC')+) ENGINE = ReplicatedMergeTree('/clickhouse/ops/tables/{shard}/posthog.metrics_series', '{replica}') ORDER BY (team_id, metric_name, id) SETTINGS index_granularity = 1024;+CREATE TABLE posthog.sharded_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), ''),+ ProfileEvents2 JSON(max_dynamic_paths=0, OSCPUVirtualTimeMicroseconds UInt64, ReadBufferFromS3Bytes UInt64, RealTimeMicroseconds UInt64, S3AbortMultipartUpload UInt64, S3Clients UInt64, S3CompleteMultipartUpload UInt64, S3CopyObject UInt64, S3CreateMultipartUpload UInt64, S3DeleteObjects UInt64, S3GetObject UInt64, S3GetObjectAttributes UInt64, S3HeadObject UInt64, S3ListObjects UInt64, S3PutObject UInt64, S3UploadPart UInt64, S3UploadPartCopy UInt64, WriteBufferFromS3Bytes UInt64)+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/noshard/posthog.sharded_query_log_archive', '{replica}-{shard}') ORDER BY (team_id, event_date, event_time, query_id) PARTITION BY toYYYYMM(event_date) SETTINGS index_granularity = 8192, object_serialization_version = 'v3', object_shared_data_serialization_version = 'map_with_buckets';+CREATE TABLE posthog.sharded_tophog (+ timestamp DateTime64(6, 'UTC'),+ metric LowCardinality(String),+ type LowCardinality(String) DEFAULT 'sum',+ key Map(LowCardinality(String), String),+ value Float64,+ count UInt64 DEFAULT 0,+ pipeline LowCardinality(String),+ lane LowCardinality(String),+ labels Map(LowCardinality(String), String)+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/ops/{shard}/posthog.tophog_new', '{replica}') ORDER BY (pipeline, lane, metric, timestamp, key) PARTITION BY toYYYYMMDD(timestamp) TTL toDate(timestamp) + toIntervalDay(30) SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;+CREATE MATERIALIZED VIEW posthog.metrics_label_index_from_series_mv TO posthog.metrics_label_index (team_id UInt64, metric_name LowCardinality(String), label_name LowCardinality(String), label_value String, id UInt64) AS SELECT+ team_id,+ metric_name,+ tupleElement(label_pair, 1) AS label_name,+ tupleElement(label_pair, 2) AS label_value,+ id+FROM+ posthog.metrics_series ARRAY JOIN JSONExtractKeysAndValues(labels_json, 'String') AS label_pair;+CREATE VIEW posthog.custom_metrics_backups AS WITH+ ['ClickHouseCustomMetric_BackupFailed', 'ClickHouseCustomMetric_BackupSuccess', 'ClickHouseCustomMetric_BackupCancelled', 'ClickHouseCustomMetric_BackupAttempts'] AS names,+ [toInt64(countIf(status = 'BACKUP_FAILED')), toInt64(countIf(status = 'BACKUP_CREATED')), toInt64(countIf(status = 'BACKUP_CANCELLED')), toInt64(countIf(status = 'CREATING_BACKUP'))] AS values,+ ['Number of failed backups', 'Number of successful backups', 'Number of cancelled backups', 'Number of backup attempts'] AS descriptions,+ ['gauge', 'gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.backup_log+WHERE event_date = today()+GROUP BY+ event_date;+CREATE VIEW posthog.custom_metrics_dictionaries AS SELECT+ 'ClickHouseCustomMetric_DictionariesFailed' AS name,+ map(+ 'instance',+ hostname(),+ 'database',+ d.database,+ 'dictionary',+ d.dict_name,+ 'uuid',+ toString(d.uuid),+ 'status',+ toString(d.status)+ ) AS labels,+ toUInt64(1) AS value,+ 'Dictionary is in FAILED or FAILED_AND_RELOADING status' AS help,+ 'gauge' AS type+FROM+ (+ SELECT name AS dict_name, database, uuid, status+ FROM system.dictionaries+ WHERE status IN ('FAILED', 'FAILED_AND_RELOADING')+ ) AS d;+CREATE VIEW posthog.custom_metrics_part_counts AS SELECT+ 'ClickHouseCustomMetric_MaxPartCountPerPartition' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`, 'partition', partition) AS labels,+ part_count AS value,+ 'Maximum number of active parts for any partition in a PostHog table' AS help,+ 'gauge' AS type+FROM+ (+ SELECT database, `table`, partition, count() AS part_count+ FROM system.parts+ WHERE+ active+ AND+ (database = 'posthog')+ GROUP BY+ database, `table`, partition+ ORDER BY database ASC, `table` ASC, part_count DESC, partition ASC+ LIMIT 1 BY database, `table`+ );+CREATE VIEW posthog.custom_metrics_replication_queue AS WITH+ ['ClickHouseCustomMetric_ReplicationQueueStuckEntries', 'ClickHouseCustomMetric_ReplicationQueueMaxPostponedEntrySeconds', 'ClickHouseCustomMetric_ReplicationQueueMaxErrorEntrySeconds'] AS names,+ [toInt64(countIf(create_time < (now() - toIntervalDay(15)))), maxIf(dateDiff('seconds', create_time, last_postpone_time), last_postpone_time != '1970-01-01'), maxIf(dateDiff('seconds', create_time, last_exception_time), (last_exception_time != '1970-01-01') AND (last_exception_time > (now() - toIntervalMinute(5))))] AS values,+ ['Number of entries that have been in the replication queue for more than 15 days', 'Maximum number of seconds that an entry has been postponed', 'Maximum number of seconds that an entry has been in error'] AS descriptions,+ ['gauge', 'gauge', 'gauge'] AS types,+ arrayJoin(arrayZip(names, values, descriptions, types)) AS tpl+SELECT+ tpl.1 AS name,+ map('table', `table`, 'instance', hostname()) AS labels,+ tpl.2 AS value,+ tpl.3 AS help,+ tpl.4 AS type+FROM system.replication_queue+GROUP BY+ `table`+HAVING+ value > 0;+CREATE VIEW posthog.custom_metrics_server_crash AS SELECT+ 'ClickHouseCustomMetric_ServerCrash' AS name,+ map('instance', hostname()) AS labels,+ count() AS value,+ 'Number of server crashes for current date' AS help,+ 'gauge' AS type+FROM system.crash_log+WHERE event_date = today()+GROUP BY+ hostname();+CREATE VIEW posthog.custom_metrics_table_sizes AS SELECT+ 'ClickHouseCustomMetric_TableTotalBytes' AS name,+ map('instance', hostname(), 'database', database, 'table', `table`) AS labels,+ CAST(total_bytes, 'Float64') AS value,+ 'Size of a database table on a given node (need a sum for sharded)' AS help,+ 'gauge' AS type+FROM system.tables+WHERE+ (database NOT IN ('INFORMATION_SCHEMA', 'information_schema'))+AND+ (total_bytes IS NOT NULL);+CREATE VIEW posthog.custom_metrics_test AS SELECT+ 'ClickHouseCustomMetric_Test' AS name,+ map('instance', hostname()) AS labels,+ 1 AS value,+ 'Test to check that the metric endpoint is working' AS help,+ 'gauge' AS type;+CREATE VIEW posthog.daily_aggregated_query_log_archive AS SELECT+ event_date AS day,+ team_id,+ user,+ current_database,+ query_kind,+ lc_kind,+ lc_access_method,+ lc_query_type,+ lc_product,+ lc_name,+ lc_feature,+ lc_query__kind,+ lc_api_key_label,+ count() AS query_count,+ sum(read_bytes) AS read_bytes,+ sum(read_rows) AS read_rows,+ sum(query_duration_ms) AS query_duration_ms,+ sum(ProfileEvents_OSCPUVirtualTimeMicroseconds) AS cpu_microseconds,+ countIf(exception_code != 0) AS error_count,+ countIf(exception_code IN (159, 160, 241)) AS timeout_oom_count+FROM posthog.sharded_query_log_archive+WHERE+ is_initial_query+AND+ (event_date < today())+GROUP BY+ day, team_id, user, current_database, query_kind, lc_kind, lc_access_method, lc_query_type, lc_product, lc_name, lc_feature, lc_query__kind, lc_api_key_label;+CREATE TABLE posthog.query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64),+ exception_name String ALIAS errorCodeToName(exception_code),+ ProfileEvents_RealTimeMicroseconds Int64 ALIAS ProfileEvents['RealTimeMicroseconds'],+ ProfileEvents_OSCPUVirtualTimeMicroseconds Int64 ALIAS ProfileEvents['OSCPUVirtualTimeMicroseconds'],+ ProfileEvents_S3Clients Int64 ALIAS ProfileEvents['S3Clients'],+ ProfileEvents_S3DeleteObjects Int64 ALIAS ProfileEvents['S3DeleteObjects'],+ ProfileEvents_S3CopyObject Int64 ALIAS ProfileEvents['S3CopyObject'],+ ProfileEvents_S3ListObjects Int64 ALIAS ProfileEvents['S3ListObjects'],+ ProfileEvents_S3HeadObject Int64 ALIAS ProfileEvents['S3HeadObject'],+ ProfileEvents_S3GetObjectAttributes Int64 ALIAS ProfileEvents['S3GetObjectAttributes'],+ ProfileEvents_S3CreateMultipartUpload Int64 ALIAS ProfileEvents['S3CreateMultipartUpload'],+ ProfileEvents_S3UploadPartCopy Int64 ALIAS ProfileEvents['S3UploadPartCopy'],+ ProfileEvents_S3UploadPart Int64 ALIAS ProfileEvents['S3UploadPart'],+ ProfileEvents_S3AbortMultipartUpload Int64 ALIAS ProfileEvents['S3AbortMultipartUpload'],+ ProfileEvents_S3CompleteMultipartUpload Int64 ALIAS ProfileEvents['S3CompleteMultipartUpload'],+ ProfileEvents_S3PutObject Int64 ALIAS ProfileEvents['S3PutObject'],+ ProfileEvents_S3GetObject Int64 ALIAS ProfileEvents['S3GetObject'],+ ProfileEvents_ReadBufferFromS3Bytes Int64 ALIAS ProfileEvents['ReadBufferFromS3Bytes'],+ ProfileEvents_WriteBufferFromS3Bytes Int64 ALIAS ProfileEvents['WriteBufferFromS3Bytes'],+ lc_workflow LowCardinality(String) ALIAS log_comment.workflow,+ lc_kind LowCardinality(String) ALIAS log_comment.kind,+ lc_id String ALIAS CAST(log_comment.id, 'String'),+ lc_route_id String ALIAS CAST(log_comment.route_id, 'String'),+ lc_access_method LowCardinality(String) ALIAS log_comment.access_method,+ lc_api_key_label String ALIAS CAST(log_comment.api_key_label, 'String'),+ lc_api_key_mask String ALIAS CAST(log_comment.api_key_mask, 'String'),+ lc_query_type LowCardinality(String) ALIAS log_comment.query_type,+ lc_product LowCardinality(String) ALIAS log_comment.product,+ lc_chargeable Bool ALIAS log_comment.chargeable,+ lc_name String ALIAS CAST(log_comment.name, 'String'),+ lc_request_name String ALIAS CAST(log_comment.request_name, 'String'),+ lc_client_query_id String ALIAS CAST(log_comment.client_query_id, 'String'),+ lc_org_id String ALIAS CAST(log_comment.org_id, 'String'),+ lc_user_id Int64 ALIAS log_comment.user_id,+ lc_is_impersonated Bool ALIAS log_comment.is_impersonated,+ lc_session_id String ALIAS CAST(log_comment.session_id, 'String'),+ lc_dashboard_id Int64 ALIAS log_comment.dashboard_id,+ lc_insight_id Int64 ALIAS log_comment.insight_id,+ lc_cohort_id Int64 ALIAS log_comment.cohort_id,+ lc_batch_export_id String ALIAS CAST(log_comment.batch_export_id, 'String'),+ lc_experiment_id Int64 ALIAS log_comment.experiment_id,+ lc_experiment_feature_flag_key String ALIAS CAST(log_comment.experiment_feature_flag_key, 'String'),+ lc_alert_config_id String ALIAS CAST(log_comment.alert_config_id, 'String'),+ lc_feature LowCardinality(String) ALIAS log_comment.feature,+ lc_table_id String ALIAS CAST(log_comment.table_id, 'String'),+ lc_warehouse_query Bool ALIAS log_comment.warehouse_query,+ lc_person_on_events_mode LowCardinality(String) ALIAS log_comment.person_on_events_mode,+ lc_service_name String ALIAS CAST(log_comment.service_name, 'String'),+ lc_workload LowCardinality(String) ALIAS log_comment.workload,+ lc_query__kind LowCardinality(String) ALIAS if(JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'kind'), JSONExtractString(toString(log_comment), 'query', 'kind')),+ lc_query__query String ALIAS multiIf(NOT is_initial_query, '', JSONHas(toString(log_comment), 'query', 'source'), JSONExtractString(toString(log_comment), 'query', 'source', 'query'), JSONExtractString(toString(log_comment), 'query', 'query')),+ lc_query String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'query'), ''),+ lc_temporal__workflow_namespace String ALIAS CAST(log_comment.`temporal.workflow_namespace`, 'String'),+ lc_temporal__workflow_type String ALIAS CAST(log_comment.`temporal.workflow_type`, 'String'),+ lc_temporal__workflow_id String ALIAS CAST(log_comment.`temporal.workflow_id`, 'String'),+ lc_temporal__workflow_run_id String ALIAS CAST(log_comment.`temporal.workflow_run_id`, 'String'),+ lc_temporal__activity_type String ALIAS CAST(log_comment.`temporal.activity_type`, 'String'),+ lc_temporal__activity_id String ALIAS CAST(log_comment.`temporal.activity_id`, 'String'),+ lc_temporal__attempt Int64 ALIAS log_comment.`temporal.attempt`,+ lc_dagster__job_name String ALIAS CAST(log_comment.`dagster.job_name`, 'String'),+ lc_dagster__run_id String ALIAS CAST(log_comment.`dagster.run_id`, 'String'),+ lc_dagster__owner String ALIAS CAST(log_comment.`dagster.tags.owner`, 'String'),+ lc_modifiers String ALIAS if(is_initial_query, JSONExtractRaw(toString(log_comment), 'modifiers'), '')+) ENGINE = Distributed('ops', 'posthog', 'sharded_query_log_archive');+CREATE TABLE posthog.query_log_archive_buffer (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Buffer('posthog', 'sharded_query_log_archive', 16, 10, 60, 10000, 1000000, 10000000, 100000000);+CREATE TABLE posthog.writable_query_log_archive (+ hostname LowCardinality(String),+ user LowCardinality(String),+ query_id String,+ initial_query_id String,+ is_initial_query UInt8,+ type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4),+ event_date Date,+ event_time DateTime,+ event_time_microseconds DateTime64(6),+ query_start_time DateTime,+ query_start_time_microseconds DateTime64(6),+ query_duration_ms UInt64,+ read_rows UInt64,+ read_bytes UInt64,+ written_rows UInt64,+ written_bytes UInt64,+ result_rows UInt64,+ result_bytes UInt64,+ memory_usage UInt64,+ peak_threads_usage UInt64,+ current_database LowCardinality(String),+ query String,+ formatted_query String,+ normalized_query_hash UInt64,+ query_kind LowCardinality(String),+ exception_code Int32,+ exception String,+ stack_trace String,+ team_id Int64,+ log_comment JSON(max_dynamic_paths=256, access_method LowCardinality(String), alert_config_id String, api_key_label String, api_key_mask String, batch_export_id String, chargeable Bool, client_query_id String, cohort_id Int64, `dagster.job_name` String, `dagster.run_id` String, `dagster.tags.owner` String, dashboard_id Int64, experiment_feature_flag_key String, experiment_id Int64, feature LowCardinality(String), id String, insight_id Int64, is_impersonated Bool, kind LowCardinality(String), name String, org_id String, person_on_events_mode LowCardinality(String), product LowCardinality(String), query_type LowCardinality(String), request_name String, route_id String, service_name String, session_id String, table_id String, team_id Int64, `temporal.activity_id` String, `temporal.activity_type` String, `temporal.attempt` Int64, `temporal.workflow_id` String, `temporal.workflow_namespace` String, `temporal.workflow_run_id` String, `temporal.workflow_type` String, user_id Int64, warehouse_query Bool, workflow LowCardinality(String), workload LowCardinality(String), SKIP cache_key, SKIP filter, SKIP hogql_features, SKIP http_referer, SKIP http_request_id, SKIP http_user_agent, SKIP query_settings, SKIP timings, SKIP user_email),+ ProfileEvents Map(String, UInt64)+) ENGINE = Distributed('ops', 'posthog', 'query_log_archive_buffer');+CREATE MATERIALIZED VIEW posthog.ops_query_log_archive_mv TO posthog.writable_query_log_archive (hostname LowCardinality(String), user LowCardinality(String), query_id String, initial_query_id String, is_initial_query UInt8, type Enum8('QueryStart'=1, 'QueryFinish'=2, 'ExceptionBeforeStart'=3, 'ExceptionWhileProcessing'=4), event_date Date, event_time DateTime, event_time_microseconds DateTime64(6), query_start_time DateTime, query_start_time_microseconds DateTime64(6), query_duration_ms UInt64, read_rows UInt64, read_bytes UInt64, written_rows UInt64, written_bytes UInt64, result_rows UInt64, result_bytes UInt64, memory_usage UInt64, peak_threads_usage UInt64, current_database LowCardinality(String), query String, formatted_query String, normalized_query_hash UInt64, query_kind LowCardinality(String), exception_code Int32, exception String, stack_trace String, team_id Int64, log_comment String, ProfileEvents Map(LowCardinality(String), UInt64)) AS SELECT+ hostname,+ user,+ query_id,+ initial_query_id,+ is_initial_query,+ type,+ event_date,+ event_time,+ event_time_microseconds,+ query_start_time,+ query_start_time_microseconds,+ query_duration_ms,+ read_rows,+ read_bytes,+ written_rows,+ written_bytes,+ result_rows,+ result_bytes,+ memory_usage,+ peak_threads_usage,+ current_database,+ query,+ formatted_query,+ normalized_query_hash,+ query_kind,+ exception_code,+ exception,+ stack_trace,+ JSONExtractInt(log_comment, 'team_id') AS team_id,+ if(isValidJSON(log_comment), log_comment, '{}') AS log_comment,+ ProfileEvents+FROM system.query_log+WHERE type != 'QueryStart';+CREATE VIEW posthog.custom_metrics AS SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_test+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_replication_queue+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_server_crash+UNION ALL+SELECT *+FROM posthog.custom_metrics_table_sizes+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_part_counts+UNION ALL+SELECT * REPLACE(toFloat64(value) AS value)+FROM posthog.custom_metrics_dictionaries+UNION ALL+SELECT+ 'ClickHouseCustomMetric_S3DiskBytesUsed' AS name,+ map('instance', hostname(), 'disk', disk_name) AS labels,+ toFloat64(sum(bytes_on_disk)) AS value,+ 'Bytes currently used by ClickHouse parts on S3-backed disks on this node' AS help,+ 'gauge' AS type+FROM system.parts+WHERE disk_name IN ('s3disk', 'cache')+GROUP BY+ disk_name+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeFailures15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(count()) AS value,+ 'Number of failed merge operations in the last 15 minutes' AS help,+ 'gauge' AS type+FROM system.part_log+WHERE+ (event_time >= (now() - toIntervalMinute(15)))+AND+ (event_type = 'MergeParts')+AND+ (error > 0)+AND+ (merge_reason != 'NotAMerge')+AND+ (error != 40)+UNION ALL+SELECT+ 'ClickHouseCustomMetric_MergeRetriesMaxPerTable15m' AS name,+ map('instance', hostname()) AS labels,+ toFloat64(max(cnt)) AS value,+ 'Max failed merge retries for any single table in the last 15 minutes' AS help,+ 'gauge' AS type+FROM+ (+ SELECT count() AS cnt+ FROM system.part_log+ WHERE+ (event_time >= (now() - toIntervalMinute(15)))+ AND+ (event_type = 'MergeParts')+ AND+ (error > 0)+ AND+ (merge_reason != 'NotAMerge')+ AND+ (error != 40)+ GROUP BY+ database, `table`, partition_id+ );