:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(signals): emit warehouse signals for any table or repo name (#95358)
posthog[bot]a35f5b2242ef
diff --git a/products/signals/backend/emission/fetchers/data_warehouse.py b/products/signals/backend/emission/fetchers/data_warehouse.pyindex b7d251be736a..c85a7d54c154 100644--- a/products/signals/backend/emission/fetchers/data_warehouse.py+++ b/products/signals/backend/emission/fetchers/data_warehouse.py@@ -4,6 +4,7 @@ from typing import Anyimport structlogfrom posthog.hogql import ast+from posthog.hogql.escape_sql import escape_hogql_identifierfrom posthog.hogql.parser import parse_selectfrom posthog.hogql.query import execute_hogql_query@@ -14,6 +15,17 @@ from products.signals.backend.emission.registry import SignalSourceTableConfiglogger = structlog.get_logger(__name__)+def escape_table_name(table_name: str) -> str:+ """Quote each segment of a warehouse table name for use in a HogQL FROM clause.++ Some sources put customer text in the table key. A GitHub source keys its table on the+ repository name, so a hyphen or another character that is not valid in a bare identifier+ reaches HogQL and breaks the parse. The HogQL database registers the table under the same+ dot-split chain, so keep the dots and escape only the segments between them.+ """+ return ".".join(escape_hogql_identifier(part) for part in table_name.split("."))++def data_warehouse_record_fetcher(team: Team,config: SignalSourceTableConfig,@@ -40,12 +52,11 @@ def data_warehouse_record_fetcher(if config.where_clause:where_parts.append(config.where_clause)where_sql = " AND ".join(where_parts)- # None of the data comes externally (neither limits of table name), so it's safe to use f-string interpolationfields_sql = ", ".join(config.fields)# Limiting can cause a data loss, as the missed records won't be picked in the next sync, but it's acceptable for the current use casequery = f"""SELECT {fields_sql}- FROM {table_name}+ FROM {escape_table_name(table_name)}WHERE {where_sql}LIMIT {config.max_records}"""@@ -60,8 +71,10 @@ def data_warehouse_record_fetcher(signals_type="data-import-signals",**extra,)- parsed = parse_select(query, placeholders=placeholders) if placeholders else parse_select(query)try:+ # Parsing is inside the try so a query we cannot even parse is logged and re-raised like a+ # query that fails at execution, instead of dying before the first log line.+ parsed = parse_select(query, placeholders=placeholders) if placeholders else parse_select(query)# Internal data-import signal fetcher (no user); bypass warehouse HogQL access control so it# can read the source warehouse table.result = execute_hogql_query(diff --git a/products/signals/backend/emission/front_conversations.py b/products/signals/backend/emission/front_conversations.pyindex 577560f1e950..26ea8591c141 100644--- a/products/signals/backend/emission/front_conversations.py+++ b/products/signals/backend/emission/front_conversations.py@@ -22,7 +22,10 @@ FRONT_CONFIG = SignalSourceTableConfig(json_list_fields=("tags",),),record_fetcher=data_warehouse_record_fetcher,- partition_field="fromUnixTimestamp(toUInt32(created_at))",+ # Front sends fractional epoch seconds (for example 1453770984.123). toInt prints as an+ # accurate cast, which returns NULL for a fractional value, so truncate before the cast.+ # Without floor, every conversation resolves to NULL and drops out of the time filter.+ partition_field="fromUnixTimestamp(toInt(floor(created_at)))",fields=FRONT_FIELDS,where_clause="status NOT IN ('archived', 'deleted')",max_records=200,diff --git a/products/signals/backend/emission/google_search_console_opportunities.py b/products/signals/backend/emission/google_search_console_opportunities.pyindex bb5ca1891422..457290130756 100644--- a/products/signals/backend/emission/google_search_console_opportunities.py+++ b/products/signals/backend/emission/google_search_console_opportunities.py@@ -33,6 +33,7 @@ from posthog.hogql.query import execute_hogql_queryfrom posthog.models import Team+from products.signals.backend.emission.fetchers.data_warehouse import escape_table_namefrom products.signals.backend.emission.registry import SignalEmitterOutput, SignalSourceTableConfigfrom products.signals.backend.models import SignalEmissionRecord@@ -152,12 +153,10 @@ def google_search_console_record_fetcher("""Fetch recent opportunity rows via HogQL and dedupe against already-emitted signals."""table_name: str = context["table_name"]extra: dict[str, Any] = context.get("extra", {})- # No external input here — the where clause and table name are internal constants — so f-string- # interpolation is safe (matches data_warehouse_record_fetcher's rationale).fields_sql = ", ".join(config.fields)query = f"""SELECT {fields_sql}- FROM {table_name}+ FROM {escape_table_name(table_name)}WHERE date > now() - interval {GSC_LOOKBACK_DAYS} day AND {config.where_clause}ORDER BY date DESC, impressions DESCLIMIT {config.max_records}diff --git a/products/signals/backend/emission/intercom_conversations.py b/products/signals/backend/emission/intercom_conversations.pyindex fefb518936e0..414a25afa25c 100644--- a/products/signals/backend/emission/intercom_conversations.py+++ b/products/signals/backend/emission/intercom_conversations.py@@ -6,7 +6,7 @@ emitter (like Jira's):(`source.body`, HTML). `title` is often null, so we fall back to the stripped source body.The rest of the thread is in `conversation_parts` (a separate table we don't sync).- `created_at` is a Unix epoch (seconds), so the partition cursor wraps it in- `fromUnixTimestamp(...)`. Verify the stored type on the first real sync.+ `fromUnixTimestamp(toInt(...))`. Verify the stored type on the first real sync."""import re@@ -92,7 +92,7 @@ INTERCOM_CONFIG = SignalSourceTableConfig(record_fetcher=data_warehouse_record_fetcher,# created_at is a Unix epoch (seconds). Wrap so the cursor compares as a datetime; verify the# stored column type on the first real sync (it may already be a DateTime).- partition_field="fromUnixTimestamp(toUInt32(created_at))",+ partition_field="fromUnixTimestamp(toInt(created_at))",fields=FIELDS,where_clause=f"state NOT IN ({', '.join(repr(s) for s in INTERCOM_IGNORED_STATES)})",max_records=200,diff --git a/products/signals/backend/emission/rollbar_items.py b/products/signals/backend/emission/rollbar_items.pyindex f7d32d47dd3a..9ac0061b9eb0 100644--- a/products/signals/backend/emission/rollbar_items.py+++ b/products/signals/backend/emission/rollbar_items.py@@ -21,7 +21,7 @@ ROLLBAR_CONFIG = SignalSourceTableConfig(extra_fields=("level", "status", "environment", "framework", "last_occurrence_timestamp"),),record_fetcher=data_warehouse_record_fetcher,- partition_field="fromUnixTimestamp(toUInt32(first_occurrence_timestamp))",+ partition_field="fromUnixTimestamp(toInt(first_occurrence_timestamp))",fields=ROLLBAR_FIELDS,where_clause="status != 'resolved'",max_records=500,diff --git a/products/signals/backend/emission/tests/test_emit_signals.py b/products/signals/backend/emission/tests/test_emit_signals.pyindex 93d1aa06139c..38f07c015704 100644--- a/products/signals/backend/emission/tests/test_emit_signals.py+++ b/products/signals/backend/emission/tests/test_emit_signals.py@@ -165,6 +165,48 @@ class TestQueryNewRecords:query_arg = mock_parse.call_args[0][0]assert "parseDateTimeBestEffort(time) > now() - interval 14 day" in query_arg+ @pytest.mark.parametrize(+ "table_name,expected_chain",+ [+ ("test_table", ["test_table"]),+ # A GitHub source keys its table on the repository name, so a hyphen reaches HogQL.+ ("github.owner_my-repo__issues", ["github", "owner_my-repo__issues"]),+ ("github.owner_my.repo__issues", ["github", "owner_my", "repo__issues"]),+ ],+ )+ def test_query_parses_for_any_table_name(self, table_name, expected_chain):+ config = _make_config()+ mock_result = MagicMock()+ mock_result.columns = []+ mock_result.results = []++ with patch(f"{FETCHER_MODULE_PATH}.execute_hogql_query", return_value=mock_result) as mock_execute:+ data_warehouse_record_fetcher(+ team=MagicMock(),+ config=config,+ context={"table_name": table_name, "last_synced_at": "2025-01-01T00:00:00Z", "extra": {}},+ )++ assert mock_execute.call_args.kwargs["query"].select_from.table.chain == expected_chain++ def test_logs_and_reraises_when_the_query_cannot_be_parsed(self):+ # A parse failure used to escape before the first log line, so a broken query looked like silence.+ config = _make_config()++ with (+ patch(f"{FETCHER_MODULE_PATH}.parse_select", side_effect=Exception("cannot parse")),+ patch(f"{FETCHER_MODULE_PATH}.logger") as mock_logger,+ ):+ with pytest.raises(Exception, match="cannot parse"):+ data_warehouse_record_fetcher(+ team=MagicMock(),+ config=config,+ context={"table_name": "test_table", "last_synced_at": None, "extra": {"team_id": 7}},+ )++ assert "Error querying new records" in mock_logger.exception.call_args[0][0]+ assert mock_logger.exception.call_args.kwargs["team_id"] == 7+def test_reraises_on_query_error(self):# Must NOT swallow: silenced failures advance last_synced_at and permanently skip records.# Re-raising lets the activity's retry policy handle transient HogQL/ClickHouse failures.diff --git a/products/signals/backend/emission/tests/test_front_conversations.py b/products/signals/backend/emission/tests/test_front_conversations.pynew file mode 100644index 000000000000..253e790796f6--- /dev/null+++ b/products/signals/backend/emission/tests/test_front_conversations.py@@ -0,0 +1,21 @@+from datetime import datetime++import pytest+from posthog.test.base import BaseTest, ClickhouseTestMixin++from posthog.hogql.query import execute_hogql_query++from products.signals.backend.emission.front_conversations import FRONT_CONFIG+++class TestFrontPartitionField(ClickhouseTestMixin, BaseTest):+ def test_a_fractional_epoch_resolves_to_a_datetime(self):+ # Only ClickHouse shows this one. The query parses and names known functions either way,+ # but an accurate cast of a fractional epoch returns NULL, which drops every Front+ # conversation out of the time filter and emits nothing.+ expression = FRONT_CONFIG.partition_field.replace("created_at", "1701292649.333")++ result = execute_hogql_query(f"SELECT {expression}", team=self.team)++ assert result.results[0][0] == datetime(2023, 11, 29, 21, 17, 29)diff --git a/products/signals/backend/emission/tests/test_registry.py b/products/signals/backend/emission/tests/test_registry.pyindex cade28f266d8..95261747cc05 100644--- a/products/signals/backend/emission/tests/test_registry.py+++ b/products/signals/backend/emission/tests/test_registry.py@@ -1,10 +1,16 @@import pytest+from unittest.mock import MagicMock, patchfrom django.db.models import Fieldfrom pydantic import ValidationError+from posthog.hogql import ast+from posthog.hogql.functions.mapping import find_hogql_aggregation, find_hogql_function, find_hogql_posthog_function+from posthog.hogql.visitor import TraversingVisitor+from products.signals.backend.emission.fetchers.data_warehouse import data_warehouse_record_fetcher+from products.signals.backend.emission.google_search_console_opportunities import google_search_console_record_fetcherfrom products.signals.backend.emission.registry import (_SIGNAL_TABLE_CONFIGS,SignalSourceTableConfig,@@ -26,6 +32,50 @@ _BASE_FIELDS = {}+_HOGQL_RECORD_FETCHERS = (data_warehouse_record_fetcher, google_search_console_record_fetcher)+++class _CallNameCollector(TraversingVisitor):+ def __init__(self) -> None:+ self.names: list[str] = []++ def visit_call(self, node: ast.Call) -> None:+ self.names.append(node.name)+ super().visit_call(node)+++def _build_fetcher_query(config: SignalSourceTableConfig, last_synced_at: str | None) -> ast.SelectQuery:+ """Run the real fetcher against a stubbed executor and return the AST it built."""+ captured: dict[str, ast.SelectQuery] = {}++ def fake_execute(query, **kwargs):+ captured["query"] = query+ result = MagicMock()+ result.results = []+ result.columns = []+ return result++ with patch(+ "products.signals.backend.emission.fetchers.data_warehouse.execute_hogql_query", side_effect=fake_execute+ ):+ data_warehouse_record_fetcher(+ team=MagicMock(),+ config=config,+ context={"table_name": "source.table", "last_synced_at": last_synced_at, "extra": {}},+ )+ return captured["query"]+++def _unknown_function_names(query: ast.SelectQuery) -> list[str]:+ collector = _CallNameCollector()+ collector.visit(query)+ return [+ name+ for name in collector.names+ if not (find_hogql_function(name) or find_hogql_aggregation(name) or find_hogql_posthog_function(name))+ ]++@pytest.fixture(autouse=True)def _clean_registry():original = dict(_SIGNAL_TABLE_CONFIGS)@@ -198,3 +248,25 @@ class TestAutoRegistered:def test_registered_identity_is_an_enableable_config_choice(self, source_product: str, source_type: str) -> None:assert source_product in _field_choices("source_product")assert source_type in _field_choices("source_type")+++class TestRegisteredConfigsBuildValidHogQL:+ """Guard the whole registry: a source whose query cannot parse or names an unknown function+ fails here instead of failing silently on every sync in production."""++ @staticmethod+ def _hogql_configs() -> list[tuple[tuple[str, str], SignalSourceTableConfig]]:+ return [+ (key, config)+ for key, config in sorted(_SIGNAL_TABLE_CONFIGS.items())+ if config.record_fetcher in _HOGQL_RECORD_FETCHERS+ ]++ @pytest.mark.parametrize("last_synced_at", [None, "2025-01-01T00:00:00Z"])+ def test_every_source_query_parses_and_uses_known_functions(self, last_synced_at):+ configs = self._hogql_configs()+ assert len(configs) > 1, "the registry sweep matched no warehouse-backed source"+ unknown = {+ key: _unknown_function_names(_build_fetcher_query(config, last_synced_at)) for key, config in configs+ }+ assert {key: names for key, names in unknown.items() if names} == {}