Skip to content

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

feat(cdp): add hog_invocation_results clickhouse table (1/3) (#58824)

Ben White7fd30daaefa2
diff --git a/docker/clickhouse/config.d/default.xml b/docker/clickhouse/config.d/default.xml
index ca7d469f4e36..d559675e86aa 100644
--- a/docker/clickhouse/config.d/default.xml
+++ b/docker/clickhouse/config.d/default.xml
@@ -90,6 +90,9 @@
<warpstream_replay>
<kafka_broker_list from_env="KAFKA_HOSTS"/>
</warpstream_replay>
+ <warpstream_shared>
+ <kafka_broker_list from_env="KAFKA_HOSTS"/>
+ </warpstream_shared>
</named_collections>
<macros>
diff --git a/docker/clickhouse/config.d/multinode/ai_events_node.xml b/docker/clickhouse/config.d/multinode/ai_events_node.xml
index 1e7792fa2e9e..c12a7aeff3b3 100644
--- a/docker/clickhouse/config.d/multinode/ai_events_node.xml
+++ b/docker/clickhouse/config.d/multinode/ai_events_node.xml
@@ -115,6 +115,9 @@
<warpstream_replay>
<kafka_broker_list from_env="KAFKA_HOSTS"/>
</warpstream_replay>
+ <warpstream_shared>
+ <kafka_broker_list from_env="KAFKA_HOSTS"/>
+ </warpstream_shared>
</named_collections>
<macros>
diff --git a/docker/clickhouse/config.d/multinode/aux_node.xml b/docker/clickhouse/config.d/multinode/aux_node.xml
index e81c680dfe7b..3c1290fd12c0 100644
--- a/docker/clickhouse/config.d/multinode/aux_node.xml
+++ b/docker/clickhouse/config.d/multinode/aux_node.xml
@@ -115,6 +115,9 @@
<warpstream_replay>
<kafka_broker_list from_env="KAFKA_HOSTS"/>
</warpstream_replay>
+ <warpstream_shared>
+ <kafka_broker_list from_env="KAFKA_HOSTS"/>
+ </warpstream_shared>
</named_collections>
<macros>
diff --git a/docker/clickhouse/config.d/multinode/data_node.xml b/docker/clickhouse/config.d/multinode/data_node.xml
index ee1a949e00ab..630522d2dca9 100644
--- a/docker/clickhouse/config.d/multinode/data_node.xml
+++ b/docker/clickhouse/config.d/multinode/data_node.xml
@@ -115,6 +115,9 @@
<warpstream_replay>
<kafka_broker_list from_env="KAFKA_HOSTS"/>
</warpstream_replay>
+ <warpstream_shared>
+ <kafka_broker_list from_env="KAFKA_HOSTS"/>
+ </warpstream_shared>
</named_collections>
<macros>
diff --git a/docker/clickhouse/config.d/multinode/ops_node.xml b/docker/clickhouse/config.d/multinode/ops_node.xml
index 4ee429f916eb..84e7652255bb 100644
--- a/docker/clickhouse/config.d/multinode/ops_node.xml
+++ b/docker/clickhouse/config.d/multinode/ops_node.xml
@@ -115,6 +115,9 @@
<warpstream_replay>
<kafka_broker_list from_env="KAFKA_HOSTS"/>
</warpstream_replay>
+ <warpstream_shared>
+ <kafka_broker_list from_env="KAFKA_HOSTS"/>
+ </warpstream_shared>
</named_collections>
<macros>
diff --git a/docker/clickhouse/config.d/multinode/sessions_node.xml b/docker/clickhouse/config.d/multinode/sessions_node.xml
index b216c7103614..800a8a14dbbc 100644
--- a/docker/clickhouse/config.d/multinode/sessions_node.xml
+++ b/docker/clickhouse/config.d/multinode/sessions_node.xml
@@ -115,6 +115,9 @@
<warpstream_replay>
<kafka_broker_list from_env="KAFKA_HOSTS"/>
</warpstream_replay>
+ <warpstream_shared>
+ <kafka_broker_list from_env="KAFKA_HOSTS"/>
+ </warpstream_shared>
</named_collections>
<macros>
diff --git a/posthog/clickhouse/kafka_engine.py b/posthog/clickhouse/kafka_engine.py
index b15bb8f7626a..a813f8038051 100644
--- a/posthog/clickhouse/kafka_engine.py
+++ b/posthog/clickhouse/kafka_engine.py
@@ -16,6 +16,7 @@ CONSUMER_GROUP_INGESTION_WARNINGS = "clickhouse_ingestion_warnings" if _US else
CONSUMER_GROUP_SESSION_REPLAY_EVENTS = "clickhouse_session_replay_events" if _US else "group1"
CONSUMER_GROUP_SESSION_REPLAY_FEATURES = "clickhouse_session_replay_features" if _US else "group1"
CONSUMER_GROUP_LOG_ENTRIES = "clickhouse_log_entries_v3" if _US else "clickhouse_log_entries"
+CONSUMER_GROUP_HOG_INVOCATION_RESULTS = "clickhouse_hog_invocation_results"
CONSUMER_GROUP_DOCUMENT_EMBEDDINGS = "clickhouse_document_embeddings2" if _US else "clickhouse_document_embeddings"
CONSUMER_GROUP_HEATMAPS = "clickhouse_heatmaps" if _US else "group1"
CONSUMER_GROUP_PRECALCULATED_EVENTS = "clickhouse_precalculated_events2" if _US else "clickhouse_prefiltered_events"
diff --git a/posthog/clickhouse/migrations/0254_hog_invocation_results.py b/posthog/clickhouse/migrations/0254_hog_invocation_results.py
new file mode 100644
index 000000000000..ef8ce3ed9c28
--- /dev/null
+++ b/posthog/clickhouse/migrations/0254_hog_invocation_results.py
@@ -0,0 +1,39 @@
+from posthog.clickhouse.client.connection import NodeRole
+from posthog.clickhouse.client.migration_tools import run_sql_with_exceptions
+from posthog.models.hog_invocation_results.sql import (
+ DISTRIBUTED_HOG_INVOCATION_RESULTS_TABLE_SQL,
+ HOG_INVOCATION_RESULTS_DATA_TABLE_SQL,
+ HOG_INVOCATION_RESULTS_MV_SQL,
+ KAFKA_HOG_INVOCATION_RESULTS_TABLE_SQL,
+)
+
+# Layout (mirrors `property_values`):
+# * Local replicated data table on the AUX cluster (1 shard, 2 replicas).
+# * Single Kafka engine table on AUX, backed by the warpstream-shared named
+# collection — one topic, one consumer group. No MSK pair.
+# * MV on AUX, kafka → local data table.
+# * Distributed read alias on AUX + DATA (replay and HogQL queries hit this).
+operations = [
+ # 1. Local replicated data table on AUX.
+ run_sql_with_exceptions(
+ HOG_INVOCATION_RESULTS_DATA_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+ # 2. Kafka engine table on AUX (warpstream-shared).
+ run_sql_with_exceptions(
+ KAFKA_HOG_INVOCATION_RESULTS_TABLE_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+ # 3. MV on AUX (kafka -> data table).
+ run_sql_with_exceptions(
+ HOG_INVOCATION_RESULTS_MV_SQL(),
+ node_roles=[NodeRole.AUX],
+ ),
+ # 4. Distributed read alias on AUX and DATA so both cluster's queries reach
+ # the data. HogQL emits the bare name `hog_invocation_results`; this
+ # alias is what resolves it.
+ run_sql_with_exceptions(
+ DISTRIBUTED_HOG_INVOCATION_RESULTS_TABLE_SQL(),
+ node_roles=[NodeRole.AUX, NodeRole.DATA],
+ ),
+]
diff --git a/posthog/clickhouse/migrations/max_migration.txt b/posthog/clickhouse/migrations/max_migration.txt
index 9f0f72385bb4..f34c53584d5f 100644
--- a/posthog/clickhouse/migrations/max_migration.txt
+++ b/posthog/clickhouse/migrations/max_migration.txt
@@ -1 +1 @@
-0253_drop_dead_msk_kafka_tables
+0254_hog_invocation_results
diff --git a/posthog/clickhouse/schema.py b/posthog/clickhouse/schema.py
index 71bcfdd5fc6f..69e556469312 100644
--- a/posthog/clickhouse/schema.py
+++ b/posthog/clickhouse/schema.py
@@ -132,6 +132,12 @@ from posthog.models.group.sql import (
GROUPS_WRITABLE_TABLE_SQL,
KAFKA_GROUPS_TABLE_SQL,
)
+from posthog.models.hog_invocation_results.sql import (
+ DISTRIBUTED_HOG_INVOCATION_RESULTS_TABLE_SQL,
+ HOG_INVOCATION_RESULTS_DATA_TABLE_SQL,
+ HOG_INVOCATION_RESULTS_MV_SQL,
+ KAFKA_HOG_INVOCATION_RESULTS_TABLE_SQL,
+)
from posthog.models.ingestion_warnings.sql import (
DISTRIBUTED_INGESTION_WARNINGS_TABLE_SQL,
INGESTION_WARNINGS_DATA_TABLE_SQL,
@@ -269,6 +275,7 @@ CREATE_MERGETREE_TABLE_QUERIES = (
INGESTION_WARNINGS_DATA_TABLE_SQL,
APP_METRICS_DATA_TABLE_SQL,
APP_METRICS2_DATA_TABLE_SQL,
+ HOG_INVOCATION_RESULTS_DATA_TABLE_SQL,
PERFORMANCE_EVENTS_TABLE_SQL,
SESSION_REPLAY_EVENTS_TABLE_SQL,
WRITABLE_SESSION_REPLAY_EVENTS_TABLE_SQL,
@@ -312,6 +319,7 @@ CREATE_DISTRIBUTED_TABLE_QUERIES = (
DISTRIBUTED_INGESTION_WARNINGS_TABLE_SQL,
DISTRIBUTED_APP_METRICS_TABLE_SQL,
DISTRIBUTED_APP_METRICS2_TABLE_SQL,
+ DISTRIBUTED_HOG_INVOCATION_RESULTS_TABLE_SQL,
WRITABLE_PERFORMANCE_EVENTS_TABLE_SQL,
DISTRIBUTED_PERFORMANCE_EVENTS_TABLE_SQL,
DISTRIBUTED_SESSION_REPLAY_EVENTS_TABLE_SQL,
@@ -378,6 +386,7 @@ CREATE_KAFKA_TABLE_QUERIES = (
KAFKA_INGESTION_WARNINGS_TABLE_SQL,
KAFKA_APP_METRICS_TABLE_SQL,
KAFKA_APP_METRICS2_TABLE_SQL,
+ KAFKA_HOG_INVOCATION_RESULTS_TABLE_SQL,
KAFKA_PERFORMANCE_EVENTS_TABLE_SQL,
KAFKA_SESSION_REPLAY_EVENTS_TABLE_SQL,
KAFKA_SESSION_REPLAY_FEATURES_TABLE_SQL,
@@ -407,6 +416,7 @@ CREATE_MV_TABLE_QUERIES = (
INGESTION_WARNINGS_MV_TABLE_SQL,
APP_METRICS_MV_TABLE_SQL,
APP_METRICS2_MV_TABLE_SQL,
+ HOG_INVOCATION_RESULTS_MV_SQL,
PERFORMANCE_EVENTS_TABLE_MV_SQL,
SESSION_REPLAY_EVENTS_TABLE_MV_SQL,
SESSION_REPLAY_FEATURES_TABLE_MV_SQL,
diff --git a/posthog/clickhouse/test/__snapshots__/test_schema.ambr b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
index 7ff3b4ff1596..d2b373f92f42 100644
--- a/posthog/clickhouse/test/__snapshots__/test_schema.ambr
+++ b/posthog/clickhouse/test/__snapshots__/test_schema.ambr
@@ -282,6 +282,38 @@
'''
# ---
+# name: test_create_kafka_table_with_different_kafka_host[kafka_hog_invocation_results]
+ '''
+
+ CREATE TABLE IF NOT EXISTS kafka_hog_invocation_results
+ (
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC'),
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8
+ )
+ ENGINE = Kafka(warpstream_shared, kafka_topic_list = 'clickhouse_hog_invocation_results_test', kafka_group_name = 'clickhouse_hog_invocation_results', kafka_format = 'JSONEachRow')
+ SETTINGS kafka_skip_broken_messages = 100
+
+ '''
+# ---
# name: test_create_kafka_table_with_different_kafka_host[kafka_ingestion_warnings]
'''
@@ -1684,6 +1716,125 @@
'''
# ---
+# name: test_create_table_query[hog_invocation_results]
+ '''
+
+ CREATE TABLE IF NOT EXISTS hog_invocation_results
+ (
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC'),
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = Distributed('aux', 'posthog_test', 'hog_invocation_results_data')
+
+ '''
+# ---
+# name: test_create_table_query[hog_invocation_results_data]
+ '''
+
+ CREATE TABLE IF NOT EXISTS hog_invocation_results_data
+ (
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC') DEFAULT scheduled_at,
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8 DEFAULT 0,
+ INDEX status_idx status TYPE set(8) GRANULARITY 1,
+ INDEX function_idx function_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX event_uuid_idx event_uuid TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX is_retry_idx is_retry TYPE set(2) GRANULARITY 1
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.hog_invocation_results_data', '{replica}-{shard}', version)
+ PARTITION BY toYYYYMMDD(scheduled_at)
+ ORDER BY (team_id, function_kind, function_id, invocation_id)
+
+ SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1
+
+ '''
+# ---
+# name: test_create_table_query[hog_invocation_results_mv]
+ '''
+
+ CREATE MATERIALIZED VIEW IF NOT EXISTS hog_invocation_results_mv
+ TO hog_invocation_results_data
+ AS SELECT
+ team_id,
+ function_kind,
+ function_id,
+ invocation_id,
+ parent_run_id,
+ status,
+ attempts,
+ is_retry,
+ scheduled_at,
+ -- Defensive fallback: if the producer omits the field (e.g. an older build
+ -- still in rollout), the Kafka JSONEachRow parser populates the column
+ -- with epoch 0. Substitute `scheduled_at` in that case so the column reads
+ -- sensibly. Once every producer carries the field, this resolves to a
+ -- straight passthrough.
+ if(first_scheduled_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), scheduled_at, first_scheduled_at) AS first_scheduled_at,
+ started_at,
+ finished_at,
+ duration_ms,
+ error_kind,
+ error_message,
+ event_uuid,
+ distinct_id,
+ person_id,
+ invocation_globals,
+ version,
+ is_deleted,
+ _timestamp,
+ _offset,
+ _partition
+ FROM kafka_hog_invocation_results
+
+ '''
+# ---
# name: test_create_table_query[ingestion_warnings]
'''
@@ -1957,6 +2108,38 @@
'''
# ---
+# name: test_create_table_query[kafka_hog_invocation_results]
+ '''
+
+ CREATE TABLE IF NOT EXISTS kafka_hog_invocation_results
+ (
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC'),
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8
+ )
+ ENGINE = Kafka(warpstream_shared, kafka_topic_list = 'clickhouse_hog_invocation_results_test', kafka_group_name = 'clickhouse_hog_invocation_results', kafka_format = 'JSONEachRow')
+ SETTINGS kafka_skip_broken_messages = 100
+
+ '''
+# ---
# name: test_create_table_query[kafka_ingestion_warnings]
'''
@@ -7255,6 +7438,50 @@
'''
# ---
+# name: test_create_table_query_replicated_and_storage[hog_invocation_results_data]
+ '''
+
+ CREATE TABLE IF NOT EXISTS hog_invocation_results_data
+ (
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC') DEFAULT scheduled_at,
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8 DEFAULT 0,
+ INDEX status_idx status TYPE set(8) GRANULARITY 1,
+ INDEX function_idx function_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX event_uuid_idx event_uuid TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX is_retry_idx is_retry TYPE set(2) GRANULARITY 1
+
+ , _timestamp DateTime
+ , _offset UInt64
+ , _partition UInt64
+
+ )
+ ENGINE = ReplicatedReplacingMergeTree('/clickhouse/tables/77f1df52-4b43-11e9-910f-b8ca3a9b9f3e_noshard/posthog.hog_invocation_results_data', '{replica}-{shard}', version)
+ PARTITION BY toYYYYMMDD(scheduled_at)
+ ORDER BY (team_id, function_kind, function_id, invocation_id)
+
+ SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1
+
+ '''
+# ---
# name: test_create_table_query_replicated_and_storage[log_attributes]
'''
diff --git a/posthog/kafka_client/topics.py b/posthog/kafka_client/topics.py
index b4408387d465..9d0c0f30e577 100644
--- a/posthog/kafka_client/topics.py
+++ b/posthog/kafka_client/topics.py
@@ -33,6 +33,7 @@ KAFKA_METRICS_TIME_TO_SEE_DATA = f"{KAFKA_PREFIX}clickhouse_metrics_time_to_see_
KAFKA_PERSON_OVERRIDE = f"{KAFKA_PREFIX}clickhouse_person_override{SUFFIX}"
KAFKA_LOG_ENTRIES = f"{KAFKA_PREFIX}log_entries{SUFFIX}"
KAFKA_LOG_ENTRIES_V2_TEST = f"{KAFKA_PREFIX}log_entries_v2_test{SUFFIX}"
+KAFKA_HOG_INVOCATION_RESULTS = f"{KAFKA_PREFIX}clickhouse_hog_invocation_results{SUFFIX}"
KAFKA_CLICKHOUSE_HEATMAP_EVENTS = f"{KAFKA_PREFIX}clickhouse_heatmap_events{SUFFIX}"
KAFKA_CLICKHOUSE_AI_EVENTS_JSON = f"{KAFKA_PREFIX}clickhouse_ai_events_json{SUFFIX}"
diff --git a/posthog/models/hog_invocation_results/sql.py b/posthog/models/hog_invocation_results/sql.py
new file mode 100644
index 000000000000..dbff2d09d2e6
--- /dev/null
+++ b/posthog/models/hog_invocation_results/sql.py
@@ -0,0 +1,263 @@
+from django.conf import settings
+
+from posthog.clickhouse.kafka_engine import (
+ CONSUMER_GROUP_HOG_INVOCATION_RESULTS,
+ KAFKA_COLUMNS_WITH_PARTITION,
+ kafka_engine,
+ ttl_period,
+)
+from posthog.clickhouse.table_engines import Distributed, ReplacingMergeTree, ReplicationScheme
+from posthog.kafka_client.topics import KAFKA_HOG_INVOCATION_RESULTS
+
+HOG_INVOCATION_RESULTS_TTL_DAYS = 30
+
+# Naming convention mirrors `property_values` — the AUX-resident, non-sharded,
+# WarpStream-shared-consumed table family:
+# * `hog_invocation_results_data` — local replicated table on AUX. Writes flow
+# in via the Kafka MV; replay reads happen against the distributed alias.
+# * `kafka_hog_invocation_results` — single Kafka engine table on AUX backed
+# by the warpstream-shared named collection.
+# * `hog_invocation_results_mv` — MV on AUX, kafka → data table.
+# * `hog_invocation_results` — distributed read alias on AUX + DATA. This is
+# the name HogQL emits and the name the replay paginator queries.
+HOG_INVOCATION_RESULTS_TABLE = "hog_invocation_results"
+HOG_INVOCATION_RESULTS_DATA_TABLE = f"{HOG_INVOCATION_RESULTS_TABLE}_data"
+KAFKA_HOG_INVOCATION_RESULTS_TABLE = f"kafka_{HOG_INVOCATION_RESULTS_TABLE}"
+HOG_INVOCATION_RESULTS_MV_TABLE = f"{HOG_INVOCATION_RESULTS_TABLE}_mv"
+
+
+def DROP_HOG_INVOCATION_RESULTS_MV_SQL() -> str:
+ return f"DROP TABLE IF EXISTS {HOG_INVOCATION_RESULTS_MV_TABLE}"
+
+
+def DROP_KAFKA_HOG_INVOCATION_RESULTS_TABLE_SQL() -> str:
+ return f"DROP TABLE IF EXISTS {KAFKA_HOG_INVOCATION_RESULTS_TABLE}"
+
+
+def HOG_INVOCATION_RESULTS_ENGINE() -> ReplacingMergeTree:
+ # ReplicatedReplacingMergeTree on the AUX cluster — single shard, two
+ # replicas. The `version` column tie-breaks: lifecycle rows for the same
+ # invocation_id (start + finish, plus any replay attempts) collapse to the
+ # latest version at merge time.
+ return ReplacingMergeTree(
+ HOG_INVOCATION_RESULTS_DATA_TABLE,
+ ver="version",
+ replication_scheme=ReplicationScheme.REPLICATED,
+ )
+
+
+# Kafka payload column list (no CODEC clauses — ZSTD applies on the storage
+# side only). Reused between the Kafka engine table, the MV projection, and
+# the distributed read alias.
+#
+# `first_scheduled_at` is set by the producer to the *original* cyclotron-
+# scheduled time and carried unchanged through retries. The ReplacingMergeTree
+# collapses rows per `invocation_id`, so we couldn't recover the original
+# scheduled time with `min(scheduled_at)` post-merge — every lifecycle row
+# for a given invocation carries this column verbatim so `argMax(..., version)`
+# returns it correctly regardless of merge state.
+HOG_INVOCATION_RESULTS_KAFKA_COLUMNS = """
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC'),
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8
+""".strip()
+
+
+# The actual data lives on AUX. ZSTD on the two large String columns. Skipping
+# indexes match the listing/replay query shape — see the runs-v2 logic for
+# the canonical select.
+HOG_INVOCATION_RESULTS_DATA_TABLE_SQL = lambda: (
+ f"""
+CREATE TABLE IF NOT EXISTS {HOG_INVOCATION_RESULTS_DATA_TABLE}
+(
+ team_id Int64,
+ function_kind LowCardinality(String),
+ function_id String,
+ invocation_id String,
+ parent_run_id String,
+ status LowCardinality(String),
+ attempts UInt8,
+ is_retry UInt8,
+ scheduled_at DateTime64(6, 'UTC'),
+ first_scheduled_at DateTime64(6, 'UTC') DEFAULT scheduled_at,
+ started_at Nullable(DateTime64(6, 'UTC')),
+ finished_at Nullable(DateTime64(6, 'UTC')),
+ duration_ms Nullable(UInt32),
+ error_kind LowCardinality(String),
+ error_message String,
+ event_uuid String,
+ distinct_id String,
+ person_id String,
+ invocation_globals String,
+ version UInt64,
+ is_deleted UInt8 DEFAULT 0,
+ INDEX status_idx status TYPE set(8) GRANULARITY 1,
+ INDEX function_idx function_id TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX event_uuid_idx event_uuid TYPE bloom_filter(0.01) GRANULARITY 1,
+ INDEX is_retry_idx is_retry TYPE set(2) GRANULARITY 1
+ {KAFKA_COLUMNS_WITH_PARTITION}
+)
+ENGINE = {HOG_INVOCATION_RESULTS_ENGINE()}
+PARTITION BY toYYYYMMDD(scheduled_at)
+ORDER BY (team_id, function_kind, function_id, invocation_id)
+{ttl_period("scheduled_at", HOG_INVOCATION_RESULTS_TTL_DAYS, unit="DAY")}
+SETTINGS index_granularity = 1024, ttl_only_drop_parts = 1
+"""
+)
+
+
+# Distributed read alias. Created on both AUX (so AUX-local queries work) and
+# DATA (so HogQL queries from the main cluster reach the data). Replay paginator
+# also queries this. cluster=settings.CLICKHOUSE_AUX_CLUSTER so the Distributed
+# engine routes lookups to the AUX replicas.
+DISTRIBUTED_HOG_INVOCATION_RESULTS_TABLE_SQL = lambda: (
+ f"""
+CREATE TABLE IF NOT EXISTS {HOG_INVOCATION_RESULTS_TABLE}
+(
+ {HOG_INVOCATION_RESULTS_KAFKA_COLUMNS}
+ {KAFKA_COLUMNS_WITH_PARTITION}
+)
+ENGINE = {Distributed(data_table=HOG_INVOCATION_RESULTS_DATA_TABLE, cluster=settings.CLICKHOUSE_AUX_CLUSTER)}
+"""
+)
+
+
+# Single Kafka pair, backed by the warpstream-shared named collection. We
+# previously also created an MSK-backed pair alongside this; that's gone — the
+# producer writes to one topic and one consumer drains it.
+KAFKA_HOG_INVOCATION_RESULTS_TABLE_SQL = lambda: (
+ f"""
+CREATE TABLE IF NOT EXISTS {KAFKA_HOG_INVOCATION_RESULTS_TABLE}
+(
+ {HOG_INVOCATION_RESULTS_KAFKA_COLUMNS}
+)
+ENGINE = {
+ kafka_engine(
+ topic=KAFKA_HOG_INVOCATION_RESULTS,
+ group=CONSUMER_GROUP_HOG_INVOCATION_RESULTS,
+ named_collection=settings.CLICKHOUSE_KAFKA_WARPSTREAM_SHARED_NAMED_COLLECTION,
+ )
+ }
+SETTINGS kafka_skip_broken_messages = 100
+"""
+)
+
+
+# MV runs on AUX, writes straight into the local data table. No writable
+# distributed wrapper needed — single-shard cluster means there's nothing to
+# fan out to.
+HOG_INVOCATION_RESULTS_MV_SQL = lambda target_table=HOG_INVOCATION_RESULTS_DATA_TABLE: (
+ f"""
+CREATE MATERIALIZED VIEW IF NOT EXISTS {HOG_INVOCATION_RESULTS_MV_TABLE}
+TO {target_table}
+AS SELECT
+ team_id,
+ function_kind,
+ function_id,
+ invocation_id,
+ parent_run_id,
+ status,
+ attempts,
+ is_retry,
+ scheduled_at,
+ -- Defensive fallback: if the producer omits the field (e.g. an older build
+ -- still in rollout), the Kafka JSONEachRow parser populates the column
+ -- with epoch 0. Substitute `scheduled_at` in that case so the column reads
+ -- sensibly. Once every producer carries the field, this resolves to a
+ -- straight passthrough.
+ if(first_scheduled_at = toDateTime64('1970-01-01 00:00:00', 6, 'UTC'), scheduled_at, first_scheduled_at) AS first_scheduled_at,
+ started_at,
+ finished_at,
+ duration_ms,
+ error_kind,
+ error_message,
+ event_uuid,
+ distinct_id,
+ person_id,
+ invocation_globals,
+ version,
+ is_deleted,
+ _timestamp,
+ _offset,
+ _partition
+FROM {KAFKA_HOG_INVOCATION_RESULTS_TABLE}
+"""
+)
+
+
+TRUNCATE_HOG_INVOCATION_RESULTS_TABLE_SQL = f"TRUNCATE TABLE IF EXISTS {HOG_INVOCATION_RESULTS_DATA_TABLE}"
+
+
+# Direct insert used by tests / any bypass-Kafka producer. Writes go to the
+# local data table (the distributed read alias isn't writable).
+INSERT_HOG_INVOCATION_RESULT_SQL = f"""
+INSERT INTO {HOG_INVOCATION_RESULTS_DATA_TABLE} (
+ team_id,
+ function_kind,
+ function_id,
+ invocation_id,
+ parent_run_id,
+ status,
+ attempts,
+ is_retry,
+ scheduled_at,
+ first_scheduled_at,
+ started_at,
+ finished_at,
+ duration_ms,
+ error_kind,
+ error_message,
+ event_uuid,
+ distinct_id,
+ person_id,
+ invocation_globals,
+ version,
+ is_deleted,
+ _timestamp,
+ _offset,
+ _partition
+)
+SELECT
+ %(team_id)s,
+ %(function_kind)s,
+ %(function_id)s,
+ %(invocation_id)s,
+ %(parent_run_id)s,
+ %(status)s,
+ %(attempts)s,
+ %(is_retry)s,
+ %(scheduled_at)s,
+ %(first_scheduled_at)s,
+ %(started_at)s,
+ %(finished_at)s,
+ %(duration_ms)s,
+ %(error_kind)s,
+ %(error_message)s,
+ %(event_uuid)s,
+ %(distinct_id)s,
+ %(person_id)s,
+ %(invocation_globals)s,
+ %(version)s,
+ %(is_deleted)s,
+ now(),
+ 0,
+ 0
+"""