:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(conversations): expose ticket tags in the SQL editor (#74757)
Abigail501ddad5b884
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.pyindex 1202335bcf51..52e9d0f5d095 100644--- a/posthog/hogql/database/lazy_join_registry.py+++ b/posthog/hogql/database/lazy_join_registry.py@@ -25,6 +25,7 @@ from posthog.hogql.database.schema.session_replay_events import (from posthog.hogql.database.schema.sessions_v1 import join_events_table_to_sessions_tablefrom posthog.hogql.database.schema.sessions_v2 import join_events_table_to_sessions_table_v2from posthog.hogql.database.schema.sessions_v3 import join_events_table_to_sessions_table_v3+from posthog.hogql.database.schema.system import ticket_tags_joinfrom posthog.hogql.database.warehouse_join_resolvers import (resolve_data_warehouse_experiments_join,resolve_data_warehouse_join,@@ -76,6 +77,7 @@ RESOLVERS: dict[str, LazyJoinResolver] = {tags.REPLAY_TO_CONSOLE_LOGS: join_with_console_logs_log_entries_table,tags.ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES: join_with_error_tracking_issue_fingerprint_overrides_table,tags.ERROR_TRACKING_FINGERPRINT_ISSUE_STATE: join_with_error_tracking_fingerprint_issue_state_table,+ tags.TICKET_TAGS: ticket_tags_join,tags.ACCOUNT_TAGS: account_tags_join,tags.ACCOUNT_NOTEBOOKS: account_notebooks_join,tags.ACCOUNT_CUSTOM_PROPERTIES: account_custom_properties_join,diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.pyindex 8b1b5db67e5a..76344c3e5fb8 100644--- a/posthog/hogql/database/lazy_join_tags.py+++ b/posthog/hogql/database/lazy_join_tags.py@@ -23,6 +23,7 @@ REPLAY_TO_EVENTS = "replay_to_events"REPLAY_TO_CONSOLE_LOGS = "replay_to_console_logs"ERROR_TRACKING_ISSUE_FINGERPRINT_OVERRIDES = "error_tracking_issue_fingerprint_overrides"ERROR_TRACKING_FINGERPRINT_ISSUE_STATE = "error_tracking_fingerprint_issue_state"+TICKET_TAGS = "ticket_tags"ACCOUNT_TAGS = "account_tags"ACCOUNT_NOTEBOOKS = "account_notebooks"ACCOUNT_CUSTOM_PROPERTIES = "account_custom_properties"diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 561c112b009c..8bada7bdc488 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -1,14 +1,22 @@from functools import lru_cachefrom posthog.hogql import ast+from posthog.hogql.base import Expr+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.lazy_join_tags import TICKET_TAGSfrom posthog.hogql.database.models import (BooleanDatabaseField,+ DANGEROUS_NoTeamIdCheckTable,DateTimeDatabaseField,DecimalDatabaseField,ExpressionField,FieldOrTable,FloatDatabaseField,IntegerDatabaseField,+ LazyJoin,+ LazyJoinToAdd,+ LazyTable,+ LazyTableToAdd,StringArrayDatabaseField,StringDatabaseField,StringJSONDatabaseField,@@ -18,7 +26,8 @@ from posthog.hogql.database.models import ()from posthog.hogql.database.postgres_table import PostgresTablefrom posthog.hogql.database.schema.information_schema import information_schema_node-from posthog.hogql.parser import parse_expr+from posthog.hogql.errors import ResolutionError+from posthog.hogql.parser import parse_expr, parse_selectfrom posthog.scopes import APIScopeObject@@ -1490,6 +1499,99 @@ logs_alerts: PostgresTable = PostgresTable(},)++class _TicketScopedPostgresTable(PostgresTable, DANGEROUS_NoTeamIdCheckTable):+ """PostgresTable variant for the tag junction, which has no `team_id` column of its own.++ The framework's auto-injected `team_id = X` guard is skipped (the column doesn't exist);+ isolation instead flows from the predicate scoping through `system.support_tickets`, whose+ own team_id guard the framework re-applies to the inner reference. The same predicate prunes+ non-ticket `posthog_taggeditem` rows (tags on insights, dashboards, accounts, ...), which+ carry a NULL `ticket_id` and so never match a ticket id.+ """++ predicates: list[Expr] = [parse_expr("ticket_id IN (SELECT id FROM system.support_tickets)")]+++ticket_tagged_items: _TicketScopedPostgresTable = _TicketScopedPostgresTable(+ name="_ticket_tagged_items",+ postgres_table_name="posthog_taggeditem",+ description="Internal junction table (PostgreSQL `posthog_taggeditem`) of tag-to-ticket links; not for direct querying — use `system.support_tickets.tags`.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Primary key of the tagged-item junction row."),+ "tag_id": UUIDDatabaseField(name="tag_id", description="Tag applied to the ticket; join to `system.tags.id`."),+ "ticket_id": StringDatabaseField(+ name="ticket_id",+ nullable=True,+ description="Ticket the tag is applied to; join to `system.support_tickets.id`.",+ ),+ },+)+++def _ticket_tags_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ tti.ticket_id AS ticket_id,+ arraySort(arrayDistinct(groupArray(t.name))) AS names+ FROM system._ticket_tagged_items AS tti+ INNER JOIN system.tags AS t ON t.id = tti.tag_id+ GROUP BY tti.ticket_id+ """+ )+++class _TicketTagsTable(LazyTable):+ description: str = (+ "Internal aggregating table backing `system.support_tickets.tags`: the distinct, sorted tag names per ticket."+ )+ fields: dict[str, FieldOrTable] = {+ "ticket_id": StringDatabaseField(+ name="ticket_id", description="Ticket these tags belong to; join to `system.support_tickets.id`."+ ),+ "names": StringArrayDatabaseField(+ name="names", description="Distinct, sorted tag names applied to the ticket."+ ),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ return _ticket_tags_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "ticket_tags"++ def to_printed_hogql(self) -> str:+ return "ticket_tags"+++def ticket_tags_join(join_to_add: LazyJoinToAdd, context: HogQLContext, node: ast.SelectQuery) -> ast.JoinExpr:+ if not join_to_add.fields_accessed:+ raise ResolutionError("No fields requested from `support_tickets.tags`")+ return ast.JoinExpr(+ alias=join_to_add.to_table,+ table=_ticket_tags_select(),+ join_type="LEFT JOIN",+ constraint=ast.JoinConstraint(+ constraint_type="ON",+ expr=ast.CompareOperation(+ op=ast.CompareOperationOp.Eq,+ left=ast.Field(chain=[join_to_add.from_table, "id"]),+ right=ast.Field(chain=[join_to_add.to_table, "ticket_id"]),+ ),+ ),+ )+++ticket_tags_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_TicketTagsTable(),+ resolver=TICKET_TAGS,+)++support_tickets: PostgresTable = PostgresTable(name="support_tickets",postgres_table_name="posthog_conversations_ticket",@@ -1558,6 +1660,7 @@ support_tickets: PostgresTable = PostgresTable(),"created_at": DateTimeDatabaseField(name="created_at", description="When the ticket was opened."),"updated_at": DateTimeDatabaseField(name="updated_at", description="When the ticket was last updated."),+ "tags": ticket_tags_lazy_join,},)@@ -2098,6 +2201,7 @@ class SystemTables(TableNode):"session_recordings": TableNode(name="session_recordings", table=session_recordings),"source_schemas": TableNode(name="source_schemas", table=source_schemas),"source_sync_jobs": TableNode(name="source_sync_jobs", table=source_sync_jobs),+ "_ticket_tagged_items": TableNode(name="_ticket_tagged_items", table=ticket_tagged_items, hidden=True),"support_tickets": TableNode(name="support_tickets", table=support_tickets),"surveys": TableNode(name="surveys", table=surveys),"task_runs": TableNode(name="task_runs", table=task_runs),diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex cfc6d1d60ce5..29cf2dbaa7b4 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -103,6 +103,8 @@ TEAM_ID_FILTER_PATTERNS = {"_account_tagged_items": "system__accounts.team_id","_account_custom_property_values": "system__accounts.team_id","_account_custom_property_values_history": "system__accounts.team_id",+ # Same shape, scoped through system.support_tickets instead+ "_ticket_tagged_items": "system__support_tickets.team_id",}@@ -137,6 +139,8 @@ class TestSystemTablesTeamScoping(BaseTest):"_account_tagged_items","_account_custom_property_values","_account_custom_property_values_history",+ # Hidden junction backing system.support_tickets.tags; covered by TestSystemTicketTagsLazyJoin.+ "_ticket_tagged_items",# information_schema is a namespace of virtual catalog tables (tables/columns/# relationships/data_types) computed per-query from the caller's own Database object,# so it has no team_id column to isolate; behaviour is covered by TestInformationSchema.@@ -895,6 +899,62 @@ class TestSystemTablesNotebookMarkdown(NonAtomicBaseTest):assert rows == {"mdnote": markdown_source, "legacy": None, "empty": None}+class TestSystemTicketTagsLazyJoin(NonAtomicBaseTest):+ """Verify the `support_tickets.tags` lazy join returns per-ticket tag names and stays team-isolated."""++ CLASS_DATA_LEVEL_SETUP = False++ def setUp(self):+ super().setUp()+ other_org = Organization.objects.create(name="other_org")+ other_project = Project.objects.create(id=Team.objects.increment_id_sequence(), organization=other_org)+ self.other_team = Team.objects.create(id=other_project.id, project=other_project, organization=other_org)++ def test_tags_lazy_join_returns_tag_names_array(self):+ ticket = _create_support_ticket(self.team, "tagged")+ ticket.tagged_items.create(tag=Tag.objects.create(name="billing", team=self.team))+ ticket.tagged_items.create(tag=Tag.objects.create(name="urgent", team=self.team))+ _create_support_ticket(self.team, "untagged")++ response = execute_hogql_query(+ "SELECT id, tags.names FROM system.support_tickets ORDER BY ticket_number",+ team=self.team,+ user=self.user,+ )+ tags_by_id = {str(row[0]): row[1] for row in response.results}++ assert sorted(tags_by_id[str(ticket.id)]) == ["billing", "urgent"]+ # The untagged ticket resolves to an empty array, not a dropped row.+ assert len(tags_by_id) == 2++ def test_not_tagged_filter(self):+ # The reporting use case: tickets that are not tagged with a given tag.+ kept = _create_support_ticket(self.team, "kept")+ excluded = _create_support_ticket(self.team, "excluded")+ excluded.tagged_items.create(tag=Tag.objects.create(name="exclude_from_reporting", team=self.team))++ response = execute_hogql_query(+ "SELECT id FROM system.support_tickets WHERE NOT has(tags.names, 'exclude_from_reporting')",+ team=self.team,+ user=self.user,+ )+ ids = {str(row[0]) for row in response.results}++ assert str(kept.id) in ids+ assert str(excluded.id) not in ids++ def test_tags_lazy_join_isolated_per_team(self):+ other_ticket = _create_support_ticket(self.other_team, "theirs")+ other_ticket.tagged_items.create(tag=Tag.objects.create(name="billing", team=self.other_team))++ response = execute_hogql_query(+ "SELECT id, tags.names FROM system.support_tickets",+ team=self.team,+ user=self.user,+ )+ assert response.results == []++class TestSystemAccountsLazyJoins(NonAtomicBaseTest):"""Verify the `accounts.tags.names` and `accounts.notebooks.count` lazy joins."""diff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 33d34fb4e5a2..650734402857 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -8763,6 +8763,19 @@"schema_valid": true,"table": null,"type": "datetime"+ },+ "tags": {+ "chain": null,+ "fields": [+ "ticket_id",+ "names"+ ],+ "hogql_value": "tags",+ "id": "tags",+ "name": "tags",+ "schema_valid": true,+ "table": "ticket_tags",+ "type": "lazy_table"}},"id": "system.support_tickets",@@ -17551,6 +17564,19 @@"schema_valid": true,"table": null,"type": "datetime"+ },+ "tags": {+ "chain": null,+ "fields": [+ "ticket_id",+ "names"+ ],+ "hogql_value": "tags",+ "id": "tags",+ "name": "tags",+ "schema_valid": true,+ "table": "ticket_tags",+ "type": "lazy_table"}},"id": "system.support_tickets",diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.pyindex 6c3678d1a3aa..154ce53ff46f 100644--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py@@ -207,4 +207,5 @@ class TestLazyJoinManifest(SimpleTestCase):"replay_to_sessions_v1","replay_to_sessions_v2","replay_to_sessions_v3",+ "ticket_tags",]