Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(clickhouse): bring the ai_events satellite under declarative HCL (#67281)

Paweł Szczurdb5ec71f8830
diff --git a/posthog/clickhouse/hcl/check-live.sh b/posthog/clickhouse/hcl/check-live.sh
index c1ec296174d2..09963991a0da 100755
--- a/posthog/clickhouse/hcl/check-live.sh
+++ b/posthog/clickhouse/hcl/check-live.sh
@@ -26,7 +26,7 @@ ENV="${VERIFY_LIVE_ENV:-local}"
WARN="${VERIFY_LIVE_WARN:-0}"
DUMPDIR="${1:-${LIVE_DUMP_DIR:?dump dir required (pass as arg1 or set LIVE_DUMP_DIR); run dump-live.sh first}}"
-ROLES=(ops logs)
+ROLES=(ops logs ai_events)
# Object-name globs the gate ignores, parsed from exclude.hcl (the quoted glob
# strings) — the same list dump-live.sh feeds hclexp -exclude, applied here to
@@ -86,5 +86,5 @@ if [ "$rc" -ne 0 ] && [ "$WARN" = "1" ]; then
echo "check-live: drift detected (warn mode — not failing). Reconcile before enforcing."
exit 0
fi
-[ "$rc" -eq 0 ] && echo "check-live: OPS/LOGS live schema matches the HCL golden"
+[ "$rc" -eq 0 ] && echo "check-live: live schema matches the HCL golden for all managed roles"
exit $rc
diff --git a/posthog/clickhouse/hcl/check.sh b/posthog/clickhouse/hcl/check.sh
index 1833ee219c1b..e57800cf1571 100755
--- a/posthog/clickhouse/hcl/check.sh
+++ b/posthog/clickhouse/hcl/check.sh
@@ -26,7 +26,7 @@ MANIFEST="$HCL/nodes"
# - 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'
+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,person,person_distinct_id2'
rc=0
while read -r env role layers; do
diff --git a/posthog/clickhouse/hcl/dump-live.sh b/posthog/clickhouse/hcl/dump-live.sh
index c5f2f5efe791..c95d919f753e 100755
--- a/posthog/clickhouse/hcl/dump-live.sh
+++ b/posthog/clickhouse/hcl/dump-live.sh
@@ -35,8 +35,9 @@ chmod 0755 "$OUTDIR" 2>/dev/null || true
# Match the published ports in docker-compose.multinode-clickhouse.yml.
# role default-host default-port default-db
ROLES=(
- "ops localhost 9300 posthog"
- "logs localhost 9500 posthog"
+ "ops localhost 9300 posthog"
+ "logs localhost 9500 posthog"
+ "ai_events localhost 9100 posthog"
)
# Pin to the same chschema build as bin/hclexp; override via repo variable.
diff --git a/posthog/clickhouse/hcl/golden/dev-ai_events.hcl b/posthog/clickhouse/hcl/golden/dev-ai_events.hcl
new file mode 100644
index 000000000000..659228d54d89
--- /dev/null
+++ b/posthog/clickhouse/hcl/golden/dev-ai_events.hcl
@@ -0,0 +1,729 @@
+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 = <<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_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/golden/local-ai_events.hcl b/posthog/clickhouse/hcl/golden/local-ai_events.hcl
new file mode 100644
index 000000000000..12cd9835cb41
--- /dev/null
+++ b/posthog/clickhouse/hcl/golden/local-ai_events.hcl
@@ -0,0 +1,1520 @@
+database "posthog" {
+ table "ai_events" {
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "retention_days" {
+ type = "Int16"
+ default = "30"
+ }
+ column "drop_date" {
+ type = "Date"
+ materialized = "toDate(timestamp) + toIntervalDay(retention_days)"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "provider" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "framework" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ engine "distributed" {
+ cluster_name = "ai_events"
+ remote_database = "posthog"
+ remote_table = "sharded_ai_events"
+ sharding_key = "cityHash64(concat(toString(team_id), '-', trace_id, '-', toString(toDate(timestamp))))"
+ }
+ }
+
+ table "kafka_ai_events_json" {
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "elements_chain" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "person_properties" {
+ type = "String"
+ }
+ column "person_created_at" {
+ type = "DateTime64(3)"
+ }
+ column "person_mode" {
+ type = "Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)"
+ }
+ engine "kafka" {
+ broker_list = "msk_cluster"
+ topic_list = "kafka_topic_list = 'clickhouse_ai_events_json'"
+ group_name = "kafka_group_name = 'group1'"
+ format = "kafka_format = 'JSONEachRow'"
+ }
+ }
+
+ table "person" {
+ column "id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(3)"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "is_identified" {
+ type = "Int8"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "UInt64"
+ }
+ column "last_seen_at" {
+ type = "Nullable(DateTime64(3))"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person"
+ }
+ }
+
+ table "person_distinct_id2" {
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "Int64"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person_distinct_id2"
+ }
+ }
+
+ 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 "sharded_ai_events" {
+ order_by = ["team_id", "trace_id", "timestamp"]
+ partition_by = "toYYYYMM(drop_date)"
+ ttl = "drop_date"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "retention_days" {
+ type = "Int16"
+ default = "30"
+ }
+ column "drop_date" {
+ type = "Date"
+ materialized = "toDate(timestamp) + toIntervalDay(retention_days)"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "provider" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "framework" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ index "idx_trace_id" {
+ expr = "trace_id"
+ type = "bloom_filter(0.001)"
+ granularity = 1
+ }
+ index "idx_session_id" {
+ expr = "session_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_parent_id" {
+ expr = "parent_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_span_id" {
+ expr = "span_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_prompt_name" {
+ expr = "prompt_name"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_model" {
+ expr = "model"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_experiment_id" {
+ expr = "experiment_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_event" {
+ expr = "event"
+ type = "set(20)"
+ granularity = 1
+ }
+ index "idx_is_error" {
+ expr = "is_error"
+ type = "set(2)"
+ granularity = 1
+ }
+ index "idx_provider" {
+ expr = "provider"
+ type = "set(50)"
+ granularity = 1
+ }
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/tables/{shard}/posthog.ai_events"
+ 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 "ai_events_json_mv" {
+ to_table = "posthog.ai_events"
+ query = <<SQL
+SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json AS src
+SQL
+
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "Nullable(String)"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "Nullable(String)"
+ }
+ column "provider" {
+ type = "Nullable(String)"
+ }
+ column "framework" {
+ type = "Nullable(String)"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "Nullable(String)"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "Nullable(DateTime)"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "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_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/golden/prod-eu-ai_events.hcl b/posthog/clickhouse/hcl/golden/prod-eu-ai_events.hcl
new file mode 100644
index 000000000000..0973b776f2fd
--- /dev/null
+++ b/posthog/clickhouse/hcl/golden/prod-eu-ai_events.hcl
@@ -0,0 +1,1334 @@
+database "posthog" {
+ table "ai_events" {
+ order_by = ["team_id", "trace_id", "timestamp"]
+ partition_by = "toYYYYMM(drop_date)"
+ ttl = "drop_date"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "retention_days" {
+ type = "Int16"
+ default = "30"
+ }
+ column "drop_date" {
+ type = "Date"
+ materialized = "toDate(timestamp) + toIntervalDay(retention_days)"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "provider" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "framework" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ index "idx_trace_id" {
+ expr = "trace_id"
+ type = "bloom_filter(0.001)"
+ granularity = 1
+ }
+ index "idx_session_id" {
+ expr = "session_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_parent_id" {
+ expr = "parent_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_span_id" {
+ expr = "span_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_prompt_name" {
+ expr = "prompt_name"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_model" {
+ expr = "model"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_experiment_id" {
+ expr = "experiment_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_event" {
+ expr = "event"
+ type = "set(20)"
+ granularity = 1
+ }
+ index "idx_is_error" {
+ expr = "is_error"
+ type = "set(2)"
+ granularity = 1
+ }
+ index "idx_provider" {
+ expr = "provider"
+ type = "set(50)"
+ granularity = 1
+ }
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/ai_events/tables/{shard}/posthog.ai_events"
+ replica_name = "{replica}"
+ }
+ }
+
+ table "kafka_ai_events_json_ws" {
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "elements_chain" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "person_properties" {
+ type = "String"
+ }
+ column "person_created_at" {
+ type = "DateTime64(3)"
+ }
+ column "person_mode" {
+ type = "Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)"
+ }
+ engine "kafka" {
+ broker_list = "warpstream_ingestion"
+ topic_list = "kafka_topic_list = 'clickhouse_ai_events_json'"
+ group_name = "kafka_group_name = 'clickhouse_ai_events_ws'"
+ format = "kafka_format = 'JSONEachRow'"
+ num_consumers = 16
+ max_block_size = 5000
+ skip_broken_messages = 100
+ poll_timeout_ms = 10000
+ thread_per_consumer = true
+ }
+ }
+
+ table "person" {
+ column "id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(3)"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "is_identified" {
+ type = "Int8"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "UInt64"
+ }
+ column "last_seen_at" {
+ type = "Nullable(DateTime64(3))"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person"
+ }
+ }
+
+ table "person_distinct_id2" {
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "Int64"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person_distinct_id2"
+ }
+ }
+
+ 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 "ai_events_json_ws_mv" {
+ to_table = "posthog.ai_events"
+ query = <<SQL
+SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json_ws AS src
+SQL
+
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "Nullable(String)"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "Nullable(String)"
+ }
+ column "provider" {
+ type = "Nullable(String)"
+ }
+ column "framework" {
+ type = "Nullable(String)"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "Nullable(String)"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "Nullable(DateTime)"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "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_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/golden/prod-us-ai_events.hcl b/posthog/clickhouse/hcl/golden/prod-us-ai_events.hcl
new file mode 100644
index 000000000000..0973b776f2fd
--- /dev/null
+++ b/posthog/clickhouse/hcl/golden/prod-us-ai_events.hcl
@@ -0,0 +1,1334 @@
+database "posthog" {
+ table "ai_events" {
+ order_by = ["team_id", "trace_id", "timestamp"]
+ partition_by = "toYYYYMM(drop_date)"
+ ttl = "drop_date"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "retention_days" {
+ type = "Int16"
+ default = "30"
+ }
+ column "drop_date" {
+ type = "Date"
+ materialized = "toDate(timestamp) + toIntervalDay(retention_days)"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "provider" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "framework" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ index "idx_trace_id" {
+ expr = "trace_id"
+ type = "bloom_filter(0.001)"
+ granularity = 1
+ }
+ index "idx_session_id" {
+ expr = "session_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_parent_id" {
+ expr = "parent_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_span_id" {
+ expr = "span_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_prompt_name" {
+ expr = "prompt_name"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_model" {
+ expr = "model"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_experiment_id" {
+ expr = "experiment_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_event" {
+ expr = "event"
+ type = "set(20)"
+ granularity = 1
+ }
+ index "idx_is_error" {
+ expr = "is_error"
+ type = "set(2)"
+ granularity = 1
+ }
+ index "idx_provider" {
+ expr = "provider"
+ type = "set(50)"
+ granularity = 1
+ }
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/ai_events/tables/{shard}/posthog.ai_events"
+ replica_name = "{replica}"
+ }
+ }
+
+ table "kafka_ai_events_json_ws" {
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "elements_chain" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "person_properties" {
+ type = "String"
+ }
+ column "person_created_at" {
+ type = "DateTime64(3)"
+ }
+ column "person_mode" {
+ type = "Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)"
+ }
+ engine "kafka" {
+ broker_list = "warpstream_ingestion"
+ topic_list = "kafka_topic_list = 'clickhouse_ai_events_json'"
+ group_name = "kafka_group_name = 'clickhouse_ai_events_ws'"
+ format = "kafka_format = 'JSONEachRow'"
+ num_consumers = 16
+ max_block_size = 5000
+ skip_broken_messages = 100
+ poll_timeout_ms = 10000
+ thread_per_consumer = true
+ }
+ }
+
+ table "person" {
+ column "id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(3)"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "is_identified" {
+ type = "Int8"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "UInt64"
+ }
+ column "last_seen_at" {
+ type = "Nullable(DateTime64(3))"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person"
+ }
+ }
+
+ table "person_distinct_id2" {
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "Int64"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person_distinct_id2"
+ }
+ }
+
+ 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 "ai_events_json_ws_mv" {
+ to_table = "posthog.ai_events"
+ query = <<SQL
+SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json_ws AS src
+SQL
+
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "Nullable(String)"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "Nullable(String)"
+ }
+ column "provider" {
+ type = "Nullable(String)"
+ }
+ column "framework" {
+ type = "Nullable(String)"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "Nullable(String)"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "Nullable(DateTime)"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "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_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/nodes b/posthog/clickhouse/hcl/nodes
index 34f8d41571bc..34bcd82cf542 100644
--- a/posthog/clickhouse/hcl/nodes
+++ b/posthog/clickhouse/hcl/nodes
@@ -33,8 +33,19 @@ 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
+# AI_EVENTS satellite (LLM analytics). local/hobby run the MSK variant
+# (kafka_ai_events_json + ai_events_json_mv) with a sharded_ai_events data table
+# + distributed ai_events reader; US/EU run the WarpStream variant
+# (kafka_ai_events_json_ws + ai_events_json_ws_mv, MSK dropped by migration 0248)
+# writing into a single ai_events data table. roles/ai_events/shared holds the
+# env-uniform person / person_distinct_id2 Distributed shims (0240). dev currently
+# has only the top-level shared objects (per the latest dump).
+local ai_events roles/shared roles/ai_events/shared roles/ai_events/local
+dev ai_events roles/shared
+prod-us ai_events roles/shared roles/ai_events/shared roles/ai_events/prod
+prod-eu ai_events roles/shared roles/ai_events/shared roles/ai_events/prod
+
# 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/shared
diff --git a/posthog/clickhouse/hcl/roles/ai_events/local/tables.hcl b/posthog/clickhouse/hcl/roles/ai_events/local/tables.hcl
new file mode 100644
index 000000000000..1771e4d9d442
--- /dev/null
+++ b/posthog/clickhouse/hcl/roles/ai_events/local/tables.hcl
@@ -0,0 +1,315 @@
+database "posthog" {
+ table "ai_events" {
+ extend = "_ai_events_columns"
+ engine "distributed" {
+ cluster_name = "ai_events"
+ remote_database = "posthog"
+ remote_table = "sharded_ai_events"
+ sharding_key = "cityHash64(concat(toString(team_id), '-', trace_id, '-', toString(toDate(timestamp))))"
+ }
+ }
+ table "kafka_ai_events_json" {
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "elements_chain" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "person_properties" {
+ type = "String"
+ }
+ column "person_created_at" {
+ type = "DateTime64(3)"
+ }
+ column "person_mode" {
+ type = "Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)"
+ }
+ engine "kafka" {
+ broker_list = "msk_cluster"
+ topic_list = "kafka_topic_list = 'clickhouse_ai_events_json'"
+ group_name = "kafka_group_name = 'group1'"
+ format = "kafka_format = 'JSONEachRow'"
+ }
+ }
+ table "sharded_ai_events" {
+ extend = "_ai_events_data"
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/tables/{shard}/posthog.ai_events"
+ replica_name = "{replica}"
+ }
+ }
+ materialized_view "ai_events_json_mv" {
+ to_table = "posthog.ai_events"
+ query = <<SQL
+SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json AS src
+SQL
+
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "Nullable(String)"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "Nullable(String)"
+ }
+ column "provider" {
+ type = "Nullable(String)"
+ }
+ column "framework" {
+ type = "Nullable(String)"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "Nullable(String)"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "Nullable(DateTime)"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ }
+}
diff --git a/posthog/clickhouse/hcl/roles/ai_events/prod/tables.hcl b/posthog/clickhouse/hcl/roles/ai_events/prod/tables.hcl
new file mode 100644
index 000000000000..d5d47c3eb4d9
--- /dev/null
+++ b/posthog/clickhouse/hcl/roles/ai_events/prod/tables.hcl
@@ -0,0 +1,311 @@
+database "posthog" {
+ table "ai_events" {
+ extend = "_ai_events_data"
+ engine "replicated_merge_tree" {
+ zoo_path = "/clickhouse/ai_events/tables/{shard}/posthog.ai_events"
+ replica_name = "{replica}"
+ }
+ }
+ table "kafka_ai_events_json_ws" {
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "elements_chain" {
+ type = "String"
+ }
+ column "created_at" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "person_properties" {
+ type = "String"
+ }
+ column "person_created_at" {
+ type = "DateTime64(3)"
+ }
+ column "person_mode" {
+ type = "Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)"
+ }
+ engine "kafka" {
+ broker_list = "warpstream_ingestion"
+ topic_list = "kafka_topic_list = 'clickhouse_ai_events_json'"
+ group_name = "kafka_group_name = 'clickhouse_ai_events_ws'"
+ format = "kafka_format = 'JSONEachRow'"
+ num_consumers = 16
+ max_block_size = 5000
+ skip_broken_messages = 100
+ poll_timeout_ms = 10000
+ thread_per_consumer = true
+ }
+ }
+ materialized_view "ai_events_json_ws_mv" {
+ to_table = "posthog.ai_events"
+ query = <<SQL
+SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json_ws AS src
+SQL
+
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "String"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "Nullable(String)"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "Nullable(String)"
+ }
+ column "provider" {
+ type = "Nullable(String)"
+ }
+ column "framework" {
+ type = "Nullable(String)"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "Nullable(String)"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "Nullable(DateTime)"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ }
+}
diff --git a/posthog/clickhouse/hcl/roles/ai_events/shared/tables.hcl b/posthog/clickhouse/hcl/roles/ai_events/shared/tables.hcl
new file mode 100644
index 000000000000..c94e1bc66266
--- /dev/null
+++ b/posthog/clickhouse/hcl/roles/ai_events/shared/tables.hcl
@@ -0,0 +1,301 @@
+database "posthog" {
+ table "person" {
+ column "id" {
+ type = "UUID"
+ }
+ column "created_at" {
+ type = "DateTime64(3)"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "is_identified" {
+ type = "Int8"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "UInt64"
+ }
+ column "last_seen_at" {
+ type = "Nullable(DateTime64(3))"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person"
+ }
+ }
+ table "person_distinct_id2" {
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "is_deleted" {
+ type = "Int8"
+ }
+ column "version" {
+ type = "Int64"
+ }
+ engine "distributed" {
+ cluster_name = "posthog"
+ remote_database = "posthog"
+ remote_table = "person_distinct_id2"
+ }
+ }
+ table "_ai_events_columns" {
+ abstract = true
+ column "uuid" {
+ type = "UUID"
+ }
+ column "event" {
+ type = "LowCardinality(String)"
+ }
+ column "timestamp" {
+ type = "DateTime64(6, 'UTC')"
+ }
+ column "team_id" {
+ type = "Int64"
+ }
+ column "distinct_id" {
+ type = "String"
+ }
+ column "person_id" {
+ type = "UUID"
+ }
+ column "properties" {
+ type = "String"
+ }
+ column "retention_days" {
+ type = "Int16"
+ default = "30"
+ }
+ column "drop_date" {
+ type = "Date"
+ materialized = "toDate(timestamp) + toIntervalDay(retention_days)"
+ }
+ column "trace_id" {
+ type = "String"
+ }
+ column "session_id" {
+ type = "Nullable(String)"
+ }
+ column "parent_id" {
+ type = "Nullable(String)"
+ }
+ column "span_id" {
+ type = "Nullable(String)"
+ }
+ column "span_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "generation_id" {
+ type = "Nullable(String)"
+ }
+ column "experiment_id" {
+ type = "Nullable(String)"
+ }
+ column "span_name" {
+ type = "Nullable(String)"
+ }
+ column "trace_name" {
+ type = "Nullable(String)"
+ }
+ column "prompt_name" {
+ type = "Nullable(String)"
+ }
+ column "model" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "provider" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "framework" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "total_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "text_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "image_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "audio_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "video_output_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "reasoning_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_read_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "cache_creation_input_tokens" {
+ type = "Nullable(Int64)"
+ }
+ column "web_search_count" {
+ type = "Nullable(Int64)"
+ }
+ column "input_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "output_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "total_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "request_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "web_search_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "audio_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "image_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "video_cost_usd" {
+ type = "Nullable(Float64)"
+ }
+ column "latency" {
+ type = "Nullable(Float64)"
+ }
+ column "time_to_first_token" {
+ type = "Nullable(Float64)"
+ }
+ column "is_error" {
+ type = "UInt8"
+ }
+ column "error" {
+ type = "Nullable(String)"
+ }
+ column "error_type" {
+ type = "LowCardinality(Nullable(String))"
+ }
+ column "error_normalized" {
+ type = "Nullable(String)"
+ }
+ column "input" {
+ type = "Nullable(String)"
+ }
+ column "output" {
+ type = "Nullable(String)"
+ }
+ column "output_choices" {
+ type = "Nullable(String)"
+ }
+ column "input_state" {
+ type = "Nullable(String)"
+ }
+ column "output_state" {
+ type = "Nullable(String)"
+ }
+ column "tools" {
+ type = "Nullable(String)"
+ }
+ column "_timestamp" {
+ type = "DateTime"
+ }
+ column "_offset" {
+ type = "UInt64"
+ }
+ column "_partition" {
+ type = "UInt64"
+ }
+ }
+ table "_ai_events_data" {
+ abstract = true
+ extend = "_ai_events_columns"
+ order_by = ["team_id", "trace_id", "timestamp"]
+ partition_by = "toYYYYMM(drop_date)"
+ ttl = "drop_date"
+ settings = {
+ index_granularity = "8192"
+ ttl_only_drop_parts = "1"
+ }
+ index "idx_trace_id" {
+ expr = "trace_id"
+ type = "bloom_filter(0.001)"
+ granularity = 1
+ }
+ index "idx_session_id" {
+ expr = "session_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_parent_id" {
+ expr = "parent_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_span_id" {
+ expr = "span_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_prompt_name" {
+ expr = "prompt_name"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_model" {
+ expr = "model"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_experiment_id" {
+ expr = "experiment_id"
+ type = "bloom_filter(0.01)"
+ granularity = 1
+ }
+ index "idx_event" {
+ expr = "event"
+ type = "set(20)"
+ granularity = 1
+ }
+ index "idx_is_error" {
+ expr = "is_error"
+ type = "set(2)"
+ granularity = 1
+ }
+ index "idx_provider" {
+ expr = "provider"
+ type = "set(50)"
+ granularity = 1
+ }
+ }
+}
diff --git a/posthog/clickhouse/hcl/sql/dev-ai_events.sql b/posthog/clickhouse/hcl/sql/dev-ai_events.sql
new file mode 100644
index 000000000000..d1d0138ac723
--- /dev/null
+++ b/posthog/clickhouse/hcl/sql/dev-ai_events.sql
@@ -0,0 +1,267 @@
+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.
+-- Full CREATE schema for the dev/ai_events node. Apply to a fresh ClickHouse to build it.
+
+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.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;
diff --git a/posthog/clickhouse/hcl/sql/local-ai_events.sql b/posthog/clickhouse/hcl/sql/local-ai_events.sql
new file mode 100644
index 000000000000..96f016ddcbf0
--- /dev/null
+++ b/posthog/clickhouse/hcl/sql/local-ai_events.sql
@@ -0,0 +1,505 @@
+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.
+-- Full CREATE schema for the local/ai_events node. Apply to a fresh ClickHouse to build it.
+
+CREATE TABLE posthog.kafka_ai_events_json (
+ 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_properties String,
+ person_created_at DateTime64(3),
+ person_mode Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)
+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'msk_cluster', kafka_format = 'kafka_format = \'JSONEachRow\'', kafka_group_name = 'kafka_group_name = \'group1\'', kafka_topic_list = 'kafka_topic_list = \'clickhouse_ai_events_json\'';
+CREATE TABLE posthog.person (
+ id UUID,
+ created_at DateTime64(3),
+ team_id Int64,
+ properties String,
+ is_identified Int8,
+ is_deleted Int8,
+ version UInt64,
+ last_seen_at Nullable(DateTime64(3))
+) ENGINE = Distributed('posthog', 'posthog', 'person');
+CREATE TABLE posthog.person_distinct_id2 (
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ is_deleted Int8,
+ version Int64
+) ENGINE = Distributed('posthog', 'posthog', 'person_distinct_id2');
+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.sharded_ai_events (
+ uuid UUID,
+ event LowCardinality(String),
+ timestamp DateTime64(6, 'UTC'),
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ properties String,
+ retention_days Int16 DEFAULT 30,
+ drop_date Date MATERIALIZED toDate(timestamp) + toIntervalDay(retention_days),
+ trace_id String,
+ session_id Nullable(String),
+ parent_id Nullable(String),
+ span_id Nullable(String),
+ span_type LowCardinality(Nullable(String)),
+ generation_id Nullable(String),
+ experiment_id Nullable(String),
+ span_name Nullable(String),
+ trace_name Nullable(String),
+ prompt_name Nullable(String),
+ model LowCardinality(Nullable(String)),
+ provider LowCardinality(Nullable(String)),
+ framework LowCardinality(Nullable(String)),
+ total_tokens Nullable(Int64),
+ input_tokens Nullable(Int64),
+ output_tokens Nullable(Int64),
+ text_input_tokens Nullable(Int64),
+ text_output_tokens Nullable(Int64),
+ image_input_tokens Nullable(Int64),
+ image_output_tokens Nullable(Int64),
+ audio_input_tokens Nullable(Int64),
+ audio_output_tokens Nullable(Int64),
+ video_input_tokens Nullable(Int64),
+ video_output_tokens Nullable(Int64),
+ reasoning_tokens Nullable(Int64),
+ cache_read_input_tokens Nullable(Int64),
+ cache_creation_input_tokens Nullable(Int64),
+ web_search_count Nullable(Int64),
+ input_cost_usd Nullable(Float64),
+ output_cost_usd Nullable(Float64),
+ total_cost_usd Nullable(Float64),
+ request_cost_usd Nullable(Float64),
+ web_search_cost_usd Nullable(Float64),
+ audio_cost_usd Nullable(Float64),
+ image_cost_usd Nullable(Float64),
+ video_cost_usd Nullable(Float64),
+ latency Nullable(Float64),
+ time_to_first_token Nullable(Float64),
+ is_error UInt8,
+ error Nullable(String),
+ error_type LowCardinality(Nullable(String)),
+ error_normalized Nullable(String),
+ input Nullable(String),
+ output Nullable(String),
+ output_choices Nullable(String),
+ input_state Nullable(String),
+ output_state Nullable(String),
+ tools Nullable(String),
+ _timestamp DateTime,
+ _offset UInt64,
+ _partition UInt64,
+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_parent_id parent_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_prompt_name prompt_name TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_model model TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_event event TYPE set(20) GRANULARITY 1,
+ INDEX idx_is_error is_error TYPE set(2) GRANULARITY 1,
+ INDEX idx_provider provider TYPE set(50) GRANULARITY 1
+) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/posthog.ai_events', '{replica}') ORDER BY (team_id, trace_id, timestamp) PARTITION BY toYYYYMM(drop_date) TTL drop_date SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+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_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.ai_events (
+ uuid UUID,
+ event LowCardinality(String),
+ timestamp DateTime64(6, 'UTC'),
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ properties String,
+ retention_days Int16 DEFAULT 30,
+ drop_date Date MATERIALIZED toDate(timestamp) + toIntervalDay(retention_days),
+ trace_id String,
+ session_id Nullable(String),
+ parent_id Nullable(String),
+ span_id Nullable(String),
+ span_type LowCardinality(Nullable(String)),
+ generation_id Nullable(String),
+ experiment_id Nullable(String),
+ span_name Nullable(String),
+ trace_name Nullable(String),
+ prompt_name Nullable(String),
+ model LowCardinality(Nullable(String)),
+ provider LowCardinality(Nullable(String)),
+ framework LowCardinality(Nullable(String)),
+ total_tokens Nullable(Int64),
+ input_tokens Nullable(Int64),
+ output_tokens Nullable(Int64),
+ text_input_tokens Nullable(Int64),
+ text_output_tokens Nullable(Int64),
+ image_input_tokens Nullable(Int64),
+ image_output_tokens Nullable(Int64),
+ audio_input_tokens Nullable(Int64),
+ audio_output_tokens Nullable(Int64),
+ video_input_tokens Nullable(Int64),
+ video_output_tokens Nullable(Int64),
+ reasoning_tokens Nullable(Int64),
+ cache_read_input_tokens Nullable(Int64),
+ cache_creation_input_tokens Nullable(Int64),
+ web_search_count Nullable(Int64),
+ input_cost_usd Nullable(Float64),
+ output_cost_usd Nullable(Float64),
+ total_cost_usd Nullable(Float64),
+ request_cost_usd Nullable(Float64),
+ web_search_cost_usd Nullable(Float64),
+ audio_cost_usd Nullable(Float64),
+ image_cost_usd Nullable(Float64),
+ video_cost_usd Nullable(Float64),
+ latency Nullable(Float64),
+ time_to_first_token Nullable(Float64),
+ is_error UInt8,
+ error Nullable(String),
+ error_type LowCardinality(Nullable(String)),
+ error_normalized Nullable(String),
+ input Nullable(String),
+ output Nullable(String),
+ output_choices Nullable(String),
+ input_state Nullable(String),
+ output_state Nullable(String),
+ tools Nullable(String),
+ _timestamp DateTime,
+ _offset UInt64,
+ _partition UInt64
+) ENGINE = Distributed('ai_events', 'posthog', 'sharded_ai_events', cityHash64(concat(toString(team_id), '-', trace_id, '-', toString(toDate(timestamp)))));
+CREATE MATERIALIZED VIEW posthog.ai_events_json_mv TO posthog.ai_events (uuid UUID, event String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, person_id UUID, properties String, trace_id String, session_id Nullable(String), parent_id Nullable(String), span_id Nullable(String), span_type Nullable(String), generation_id Nullable(String), experiment_id Nullable(String), span_name Nullable(String), trace_name Nullable(String), prompt_name Nullable(String), model Nullable(String), provider Nullable(String), framework Nullable(String), total_tokens Nullable(Int64), input_tokens Nullable(Int64), output_tokens Nullable(Int64), text_input_tokens Nullable(Int64), text_output_tokens Nullable(Int64), image_input_tokens Nullable(Int64), image_output_tokens Nullable(Int64), audio_input_tokens Nullable(Int64), audio_output_tokens Nullable(Int64), video_input_tokens Nullable(Int64), video_output_tokens Nullable(Int64), reasoning_tokens Nullable(Int64), cache_read_input_tokens Nullable(Int64), cache_creation_input_tokens Nullable(Int64), web_search_count Nullable(Int64), input_cost_usd Nullable(Float64), output_cost_usd Nullable(Float64), total_cost_usd Nullable(Float64), request_cost_usd Nullable(Float64), web_search_cost_usd Nullable(Float64), audio_cost_usd Nullable(Float64), image_cost_usd Nullable(Float64), video_cost_usd Nullable(Float64), latency Nullable(Float64), time_to_first_token Nullable(Float64), is_error UInt8, error Nullable(String), error_type Nullable(String), error_normalized Nullable(String), input Nullable(String), output Nullable(String), output_choices Nullable(String), input_state Nullable(String), output_state Nullable(String), tools Nullable(String), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json AS src;
diff --git a/posthog/clickhouse/hcl/sql/prod-eu-ai_events.sql b/posthog/clickhouse/hcl/sql/prod-eu-ai_events.sql
new file mode 100644
index 000000000000..9f419a68eac2
--- /dev/null
+++ b/posthog/clickhouse/hcl/sql/prod-eu-ai_events.sql
@@ -0,0 +1,443 @@
+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.
+-- Full CREATE schema for the prod-eu/ai_events node. Apply to a fresh ClickHouse to build it.
+
+CREATE TABLE posthog.ai_events (
+ uuid UUID,
+ event LowCardinality(String),
+ timestamp DateTime64(6, 'UTC'),
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ properties String,
+ retention_days Int16 DEFAULT 30,
+ drop_date Date MATERIALIZED toDate(timestamp) + toIntervalDay(retention_days),
+ trace_id String,
+ session_id Nullable(String),
+ parent_id Nullable(String),
+ span_id Nullable(String),
+ span_type LowCardinality(Nullable(String)),
+ generation_id Nullable(String),
+ experiment_id Nullable(String),
+ span_name Nullable(String),
+ trace_name Nullable(String),
+ prompt_name Nullable(String),
+ model LowCardinality(Nullable(String)),
+ provider LowCardinality(Nullable(String)),
+ framework LowCardinality(Nullable(String)),
+ total_tokens Nullable(Int64),
+ input_tokens Nullable(Int64),
+ output_tokens Nullable(Int64),
+ text_input_tokens Nullable(Int64),
+ text_output_tokens Nullable(Int64),
+ image_input_tokens Nullable(Int64),
+ image_output_tokens Nullable(Int64),
+ audio_input_tokens Nullable(Int64),
+ audio_output_tokens Nullable(Int64),
+ video_input_tokens Nullable(Int64),
+ video_output_tokens Nullable(Int64),
+ reasoning_tokens Nullable(Int64),
+ cache_read_input_tokens Nullable(Int64),
+ cache_creation_input_tokens Nullable(Int64),
+ web_search_count Nullable(Int64),
+ input_cost_usd Nullable(Float64),
+ output_cost_usd Nullable(Float64),
+ total_cost_usd Nullable(Float64),
+ request_cost_usd Nullable(Float64),
+ web_search_cost_usd Nullable(Float64),
+ audio_cost_usd Nullable(Float64),
+ image_cost_usd Nullable(Float64),
+ video_cost_usd Nullable(Float64),
+ latency Nullable(Float64),
+ time_to_first_token Nullable(Float64),
+ is_error UInt8,
+ error Nullable(String),
+ error_type LowCardinality(Nullable(String)),
+ error_normalized Nullable(String),
+ input Nullable(String),
+ output Nullable(String),
+ output_choices Nullable(String),
+ input_state Nullable(String),
+ output_state Nullable(String),
+ tools Nullable(String),
+ _timestamp DateTime,
+ _offset UInt64,
+ _partition UInt64,
+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_parent_id parent_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_prompt_name prompt_name TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_model model TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_event event TYPE set(20) GRANULARITY 1,
+ INDEX idx_is_error is_error TYPE set(2) GRANULARITY 1,
+ INDEX idx_provider provider TYPE set(50) GRANULARITY 1
+) ENGINE = ReplicatedMergeTree('/clickhouse/ai_events/tables/{shard}/posthog.ai_events', '{replica}') ORDER BY (team_id, trace_id, timestamp) PARTITION BY toYYYYMM(drop_date) TTL drop_date SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.kafka_ai_events_json_ws (
+ 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_properties String,
+ person_created_at DateTime64(3),
+ person_mode Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)
+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_ingestion', kafka_format = 'kafka_format = \'JSONEachRow\'', kafka_group_name = 'kafka_group_name = \'clickhouse_ai_events_ws\'', kafka_max_block_size = 5000, kafka_num_consumers = 16, kafka_poll_timeout_ms = 10000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_ai_events_json\'';
+CREATE TABLE posthog.person (
+ id UUID,
+ created_at DateTime64(3),
+ team_id Int64,
+ properties String,
+ is_identified Int8,
+ is_deleted Int8,
+ version UInt64,
+ last_seen_at Nullable(DateTime64(3))
+) ENGINE = Distributed('posthog', 'posthog', 'person');
+CREATE TABLE posthog.person_distinct_id2 (
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ is_deleted Int8,
+ version Int64
+) ENGINE = Distributed('posthog', 'posthog', 'person_distinct_id2');
+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.ai_events_json_ws_mv TO posthog.ai_events (uuid UUID, event String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, person_id UUID, properties String, trace_id String, session_id Nullable(String), parent_id Nullable(String), span_id Nullable(String), span_type Nullable(String), generation_id Nullable(String), experiment_id Nullable(String), span_name Nullable(String), trace_name Nullable(String), prompt_name Nullable(String), model Nullable(String), provider Nullable(String), framework Nullable(String), total_tokens Nullable(Int64), input_tokens Nullable(Int64), output_tokens Nullable(Int64), text_input_tokens Nullable(Int64), text_output_tokens Nullable(Int64), image_input_tokens Nullable(Int64), image_output_tokens Nullable(Int64), audio_input_tokens Nullable(Int64), audio_output_tokens Nullable(Int64), video_input_tokens Nullable(Int64), video_output_tokens Nullable(Int64), reasoning_tokens Nullable(Int64), cache_read_input_tokens Nullable(Int64), cache_creation_input_tokens Nullable(Int64), web_search_count Nullable(Int64), input_cost_usd Nullable(Float64), output_cost_usd Nullable(Float64), total_cost_usd Nullable(Float64), request_cost_usd Nullable(Float64), web_search_cost_usd Nullable(Float64), audio_cost_usd Nullable(Float64), image_cost_usd Nullable(Float64), video_cost_usd Nullable(Float64), latency Nullable(Float64), time_to_first_token Nullable(Float64), is_error UInt8, error Nullable(String), error_type Nullable(String), error_normalized Nullable(String), input Nullable(String), output Nullable(String), output_choices Nullable(String), input_state Nullable(String), output_state Nullable(String), tools Nullable(String), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json_ws AS src;
+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;
diff --git a/posthog/clickhouse/hcl/sql/prod-us-ai_events.sql b/posthog/clickhouse/hcl/sql/prod-us-ai_events.sql
new file mode 100644
index 000000000000..b20f1776ab1e
--- /dev/null
+++ b/posthog/clickhouse/hcl/sql/prod-us-ai_events.sql
@@ -0,0 +1,443 @@
+-- AUTO-GENERATED from the declarative HCL by ops/gen-sql.sh — do not edit.
+-- Full CREATE schema for the prod-us/ai_events node. Apply to a fresh ClickHouse to build it.
+
+CREATE TABLE posthog.ai_events (
+ uuid UUID,
+ event LowCardinality(String),
+ timestamp DateTime64(6, 'UTC'),
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ properties String,
+ retention_days Int16 DEFAULT 30,
+ drop_date Date MATERIALIZED toDate(timestamp) + toIntervalDay(retention_days),
+ trace_id String,
+ session_id Nullable(String),
+ parent_id Nullable(String),
+ span_id Nullable(String),
+ span_type LowCardinality(Nullable(String)),
+ generation_id Nullable(String),
+ experiment_id Nullable(String),
+ span_name Nullable(String),
+ trace_name Nullable(String),
+ prompt_name Nullable(String),
+ model LowCardinality(Nullable(String)),
+ provider LowCardinality(Nullable(String)),
+ framework LowCardinality(Nullable(String)),
+ total_tokens Nullable(Int64),
+ input_tokens Nullable(Int64),
+ output_tokens Nullable(Int64),
+ text_input_tokens Nullable(Int64),
+ text_output_tokens Nullable(Int64),
+ image_input_tokens Nullable(Int64),
+ image_output_tokens Nullable(Int64),
+ audio_input_tokens Nullable(Int64),
+ audio_output_tokens Nullable(Int64),
+ video_input_tokens Nullable(Int64),
+ video_output_tokens Nullable(Int64),
+ reasoning_tokens Nullable(Int64),
+ cache_read_input_tokens Nullable(Int64),
+ cache_creation_input_tokens Nullable(Int64),
+ web_search_count Nullable(Int64),
+ input_cost_usd Nullable(Float64),
+ output_cost_usd Nullable(Float64),
+ total_cost_usd Nullable(Float64),
+ request_cost_usd Nullable(Float64),
+ web_search_cost_usd Nullable(Float64),
+ audio_cost_usd Nullable(Float64),
+ image_cost_usd Nullable(Float64),
+ video_cost_usd Nullable(Float64),
+ latency Nullable(Float64),
+ time_to_first_token Nullable(Float64),
+ is_error UInt8,
+ error Nullable(String),
+ error_type LowCardinality(Nullable(String)),
+ error_normalized Nullable(String),
+ input Nullable(String),
+ output Nullable(String),
+ output_choices Nullable(String),
+ input_state Nullable(String),
+ output_state Nullable(String),
+ tools Nullable(String),
+ _timestamp DateTime,
+ _offset UInt64,
+ _partition UInt64,
+ INDEX idx_trace_id trace_id TYPE bloom_filter(0.001) GRANULARITY 1,
+ INDEX idx_session_id session_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_parent_id parent_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_span_id span_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_prompt_name prompt_name TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_model model TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_experiment_id experiment_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX idx_event event TYPE set(20) GRANULARITY 1,
+ INDEX idx_is_error is_error TYPE set(2) GRANULARITY 1,
+ INDEX idx_provider provider TYPE set(50) GRANULARITY 1
+) ENGINE = ReplicatedMergeTree('/clickhouse/ai_events/tables/{shard}/posthog.ai_events', '{replica}') ORDER BY (team_id, trace_id, timestamp) PARTITION BY toYYYYMM(drop_date) TTL drop_date SETTINGS index_granularity = 8192, ttl_only_drop_parts = 1;
+CREATE TABLE posthog.kafka_ai_events_json_ws (
+ 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_properties String,
+ person_created_at DateTime64(3),
+ person_mode Enum8('full'=0, 'propertyless'=1, 'force_upgrade'=2)
+) ENGINE = Kafka() SETTINGS kafka_broker_list = 'warpstream_ingestion', kafka_format = 'kafka_format = \'JSONEachRow\'', kafka_group_name = 'kafka_group_name = \'clickhouse_ai_events_ws\'', kafka_max_block_size = 5000, kafka_num_consumers = 16, kafka_poll_timeout_ms = 10000, kafka_skip_broken_messages = 100, kafka_thread_per_consumer = 1, kafka_topic_list = 'kafka_topic_list = \'clickhouse_ai_events_json\'';
+CREATE TABLE posthog.person (
+ id UUID,
+ created_at DateTime64(3),
+ team_id Int64,
+ properties String,
+ is_identified Int8,
+ is_deleted Int8,
+ version UInt64,
+ last_seen_at Nullable(DateTime64(3))
+) ENGINE = Distributed('posthog', 'posthog', 'person');
+CREATE TABLE posthog.person_distinct_id2 (
+ team_id Int64,
+ distinct_id String,
+ person_id UUID,
+ is_deleted Int8,
+ version Int64
+) ENGINE = Distributed('posthog', 'posthog', 'person_distinct_id2');
+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.ai_events_json_ws_mv TO posthog.ai_events (uuid UUID, event String, timestamp DateTime64(6, 'UTC'), team_id Int64, distinct_id String, person_id UUID, properties String, trace_id String, session_id Nullable(String), parent_id Nullable(String), span_id Nullable(String), span_type Nullable(String), generation_id Nullable(String), experiment_id Nullable(String), span_name Nullable(String), trace_name Nullable(String), prompt_name Nullable(String), model Nullable(String), provider Nullable(String), framework Nullable(String), total_tokens Nullable(Int64), input_tokens Nullable(Int64), output_tokens Nullable(Int64), text_input_tokens Nullable(Int64), text_output_tokens Nullable(Int64), image_input_tokens Nullable(Int64), image_output_tokens Nullable(Int64), audio_input_tokens Nullable(Int64), audio_output_tokens Nullable(Int64), video_input_tokens Nullable(Int64), video_output_tokens Nullable(Int64), reasoning_tokens Nullable(Int64), cache_read_input_tokens Nullable(Int64), cache_creation_input_tokens Nullable(Int64), web_search_count Nullable(Int64), input_cost_usd Nullable(Float64), output_cost_usd Nullable(Float64), total_cost_usd Nullable(Float64), request_cost_usd Nullable(Float64), web_search_cost_usd Nullable(Float64), audio_cost_usd Nullable(Float64), image_cost_usd Nullable(Float64), video_cost_usd Nullable(Float64), latency Nullable(Float64), time_to_first_token Nullable(Float64), is_error UInt8, error Nullable(String), error_type Nullable(String), error_normalized Nullable(String), input Nullable(String), output Nullable(String), output_choices Nullable(String), input_state Nullable(String), output_state Nullable(String), tools Nullable(String), _timestamp Nullable(DateTime), _offset UInt64, _partition UInt64) AS SELECT
+ uuid,
+ event,
+ timestamp,
+ team_id,
+ distinct_id,
+ person_id,
+ concat(
+ '{',
+ arrayStringConcat(
+ arrayMap(
+ x -> concat('"', x.1, '":', x.2),
+ arrayFilter(
+ x -> ((x.1) NOT IN ('$ai_input', '$ai_output', '$ai_output_choices', '$ai_input_state', '$ai_output_state', '$ai_tools')),
+ JSONExtractKeysAndValuesRaw(src.properties)
+ )
+ ),
+ ','
+ ),
+ '}'
+ ) AS properties,
+ JSONExtractString(src.properties, '$ai_trace_id') AS trace_id,
+ JSONExtract(src.properties, '$ai_session_id', 'Nullable(String)') AS session_id,
+ JSONExtract(src.properties, '$ai_parent_id', 'Nullable(String)') AS parent_id,
+ JSONExtract(src.properties, '$ai_span_id', 'Nullable(String)') AS span_id,
+ JSONExtract(src.properties, '$ai_span_type', 'Nullable(String)') AS span_type,
+ JSONExtract(src.properties, '$ai_generation_id', 'Nullable(String)') AS generation_id,
+ JSONExtract(src.properties, '$ai_experiment_id', 'Nullable(String)') AS experiment_id,
+ JSONExtract(src.properties, '$ai_span_name', 'Nullable(String)') AS span_name,
+ JSONExtract(src.properties, '$ai_trace_name', 'Nullable(String)') AS trace_name,
+ JSONExtract(src.properties, '$ai_prompt_name', 'Nullable(String)') AS prompt_name,
+ JSONExtract(src.properties, '$ai_model', 'Nullable(String)') AS model,
+ JSONExtract(src.properties, '$ai_provider', 'Nullable(String)') AS provider,
+ JSONExtract(src.properties, '$ai_framework', 'Nullable(String)') AS framework,
+ JSONExtract(src.properties, '$ai_total_tokens', 'Nullable(Int64)') AS total_tokens,
+ JSONExtract(src.properties, '$ai_input_tokens', 'Nullable(Int64)') AS input_tokens,
+ JSONExtract(src.properties, '$ai_output_tokens', 'Nullable(Int64)') AS output_tokens,
+ JSONExtract(src.properties, '$ai_text_input_tokens', 'Nullable(Int64)') AS text_input_tokens,
+ JSONExtract(src.properties, '$ai_text_output_tokens', 'Nullable(Int64)') AS text_output_tokens,
+ JSONExtract(src.properties, '$ai_image_input_tokens', 'Nullable(Int64)') AS image_input_tokens,
+ JSONExtract(src.properties, '$ai_image_output_tokens', 'Nullable(Int64)') AS image_output_tokens,
+ JSONExtract(src.properties, '$ai_audio_input_tokens', 'Nullable(Int64)') AS audio_input_tokens,
+ JSONExtract(src.properties, '$ai_audio_output_tokens', 'Nullable(Int64)') AS audio_output_tokens,
+ JSONExtract(src.properties, '$ai_video_input_tokens', 'Nullable(Int64)') AS video_input_tokens,
+ JSONExtract(src.properties, '$ai_video_output_tokens', 'Nullable(Int64)') AS video_output_tokens,
+ JSONExtract(src.properties, '$ai_reasoning_tokens', 'Nullable(Int64)') AS reasoning_tokens,
+ JSONExtract(src.properties, '$ai_cache_read_input_tokens', 'Nullable(Int64)') AS cache_read_input_tokens,
+ JSONExtract(src.properties, '$ai_cache_creation_input_tokens', 'Nullable(Int64)') AS cache_creation_input_tokens,
+ JSONExtract(src.properties, '$ai_web_search_count', 'Nullable(Int64)') AS web_search_count,
+ JSONExtract(src.properties, '$ai_input_cost_usd', 'Nullable(Float64)') AS input_cost_usd,
+ JSONExtract(src.properties, '$ai_output_cost_usd', 'Nullable(Float64)') AS output_cost_usd,
+ JSONExtract(src.properties, '$ai_total_cost_usd', 'Nullable(Float64)') AS total_cost_usd,
+ JSONExtract(src.properties, '$ai_request_cost_usd', 'Nullable(Float64)') AS request_cost_usd,
+ JSONExtract(src.properties, '$ai_web_search_cost_usd', 'Nullable(Float64)') AS web_search_cost_usd,
+ JSONExtract(src.properties, '$ai_audio_cost_usd', 'Nullable(Float64)') AS audio_cost_usd,
+ JSONExtract(src.properties, '$ai_image_cost_usd', 'Nullable(Float64)') AS image_cost_usd,
+ JSONExtract(src.properties, '$ai_video_cost_usd', 'Nullable(Float64)') AS video_cost_usd,
+ JSONExtract(src.properties, '$ai_latency', 'Nullable(Float64)') AS latency,
+ JSONExtract(src.properties, '$ai_time_to_first_token', 'Nullable(Float64)') AS time_to_first_token,
+ if((JSONExtractRaw(src.properties, '$ai_is_error') IN ('true', '"true"')), 1, 0) AS is_error,
+ JSONExtract(src.properties, '$ai_error', 'Nullable(String)') AS error,
+ JSONExtract(src.properties, '$ai_error_type', 'Nullable(String)') AS error_type,
+ JSONExtract(src.properties, '$ai_error_normalized', 'Nullable(String)') AS error_normalized,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input'), '') AS input,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output'), '') AS output,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_choices'), '') AS output_choices,
+ nullIf(JSONExtractRaw(src.properties, '$ai_input_state'), '') AS input_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_output_state'), '') AS output_state,
+ nullIf(JSONExtractRaw(src.properties, '$ai_tools'), '') AS tools,
+ _timestamp,
+ _offset,
+ _partition
+FROM posthog.kafka_ai_events_json_ws AS src;
+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;