: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(support): expose ticket assignee in support_tickets HogQL table (#75648)
posthog[bot]f0cdfa57a6d2
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.pyindex 52e9d0f5d095..5304a1331d26 100644--- a/posthog/hogql/database/lazy_join_registry.py+++ b/posthog/hogql/database/lazy_join_registry.py@@ -25,7 +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_join+from posthog.hogql.database.schema.system import ticket_assignment_join, ticket_tags_joinfrom posthog.hogql.database.warehouse_join_resolvers import (resolve_data_warehouse_experiments_join,resolve_data_warehouse_join,@@ -78,6 +78,7 @@ RESOLVERS: dict[str, LazyJoinResolver] = {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.TICKET_ASSIGNMENT: ticket_assignment_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 76344c3e5fb8..647a1094a79e 100644--- a/posthog/hogql/database/lazy_join_tags.py+++ b/posthog/hogql/database/lazy_join_tags.py@@ -24,6 +24,7 @@ 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"+TICKET_ASSIGNMENT = "ticket_assignment"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 8bada7bdc488..710f73df4d5b 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -3,7 +3,7 @@ from functools import lru_cachefrom posthog.hogql import astfrom posthog.hogql.base import Exprfrom posthog.hogql.context import HogQLContext-from posthog.hogql.database.lazy_join_tags import TICKET_TAGS+from posthog.hogql.database.lazy_join_tags import TICKET_ASSIGNMENT, TICKET_TAGSfrom posthog.hogql.database.models import (BooleanDatabaseField,DANGEROUS_NoTeamIdCheckTable,@@ -1501,13 +1501,13 @@ logs_alerts: PostgresTable = PostgresTable(class _TicketScopedPostgresTable(PostgresTable, DANGEROUS_NoTeamIdCheckTable):- """PostgresTable variant for the tag junction, which has no `team_id` column of its own.+ """PostgresTable variant for ticket-side tables that have no `team_id` column of their 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.+ own team_id guard the framework re-applies to the inner reference. For the tag junction,+ the same predicate also 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)")]@@ -1592,6 +1592,88 @@ ticket_tags_lazy_join: LazyJoin = LazyJoin()+ticket_assignments: _TicketScopedPostgresTable = _TicketScopedPostgresTable(+ name="_ticket_assignments",+ postgres_table_name="posthog_conversations_ticket_assignment",+ description="Internal junction table (PostgreSQL `posthog_conversations_ticket_assignment`) of the current assignee per ticket; not for direct querying — use `system.support_tickets.assignee`.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Primary key of the assignment row."),+ "ticket_id": StringDatabaseField(+ name="ticket_id", description="Ticket this assignment is for; join to `system.support_tickets.id`."+ ),+ "user_id": IntegerDatabaseField(+ name="user_id", nullable=True, description="User the ticket is assigned to, if assigned to a user."+ ),+ "role_id": UUIDDatabaseField(+ name="role_id", nullable=True, description="Role the ticket is assigned to, if assigned to a role."+ ),+ },+)+++def _ticket_assignment_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ ticket_id AS ticket_id,+ user_id AS user_id,+ role_id AS role_id+ FROM system._ticket_assignments+ """+ )+++class _TicketAssignmentTable(LazyTable):+ description: str = "Internal table backing `system.support_tickets.assignee`: the current assignee (user or role), if any, per ticket."+ fields: dict[str, FieldOrTable] = {+ "ticket_id": StringDatabaseField(+ name="ticket_id", description="Ticket this assignment belongs to; join to `system.support_tickets.id`."+ ),+ "user_id": IntegerDatabaseField(+ name="user_id", nullable=True, description="User the ticket is assigned to, if assigned to a user."+ ),+ "role_id": UUIDDatabaseField(+ name="role_id", nullable=True, description="Role the ticket is assigned to, if assigned to a role."+ ),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ return _ticket_assignment_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "ticket_assignment"++ def to_printed_hogql(self) -> str:+ return "ticket_assignment"+++def ticket_assignment_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.assignee`")+ return ast.JoinExpr(+ alias=join_to_add.to_table,+ table=_ticket_assignment_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_assignment_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_TicketAssignmentTable(),+ resolver=TICKET_ASSIGNMENT,+)++support_tickets: PostgresTable = PostgresTable(name="support_tickets",postgres_table_name="posthog_conversations_ticket",@@ -1661,6 +1743,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,+ "assignee": ticket_assignment_lazy_join,},)@@ -2202,6 +2285,7 @@ class SystemTables(TableNode):"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),+ "_ticket_assignments": TableNode(name="_ticket_assignments", table=ticket_assignments, 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 29cf2dbaa7b4..58e9bcd20dc2 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -34,7 +34,7 @@ from products.business_knowledge.backend.models.constants import SourceStatus, Sfrom products.cdp.backend.models.hog_functions.hog_function import HogFunctionfrom products.cohorts.backend.models.calculation_history import CohortCalculationHistoryfrom products.cohorts.backend.models.cohort import Cohort-from products.conversations.backend.models import Ticket+from products.conversations.backend.models import Ticket, TicketAssignmentfrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTilefrom products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery@@ -56,6 +56,8 @@ from products.warehouse_sources.backend.facade.models import ()from products.workflows.backend.models.hog_flow.hog_flow import HogFlow+from ee.models.rbac.role import Role+if TYPE_CHECKING:from products.customer_analytics.backend.models.account import Accountfrom products.customer_analytics.backend.models.custom_property_definition import CustomPropertyDefinition@@ -105,6 +107,7 @@ TEAM_ID_FILTER_PATTERNS = {"_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",+ "_ticket_assignments": "system__support_tickets.team_id",}@@ -141,6 +144,8 @@ class TestSystemTablesTeamScoping(BaseTest):"_account_custom_property_values_history",# Hidden junction backing system.support_tickets.tags; covered by TestSystemTicketTagsLazyJoin."_ticket_tagged_items",+ # Hidden table backing system.support_tickets.assignee; covered by TestSystemTicketAssignmentLazyJoin.+ "_ticket_assignments",# 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.@@ -955,6 +960,60 @@ class TestSystemTicketTagsLazyJoin(NonAtomicBaseTest):assert response.results == []+class TestSystemTicketAssignmentLazyJoin(NonAtomicBaseTest):+ """Verify the `support_tickets.assignee` lazy join resolves the current user/role assignee+ 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)++ @parameterized.expand(+ [+ ("user", "user_id", lambda self: self.user.pk),+ ("role", "role_id", lambda self: self.role.pk),+ ]+ )+ def test_assignee_lazy_join_resolves_current_assignee(self, assignee_type, id_field, get_expected_id):+ self.role = Role.objects.create(name="Support Team", organization=self.organization)+ ticket = _create_support_ticket(self.team, assignee_type)+ TicketAssignment.objects.create(ticket=ticket, **{assignee_type: getattr(self, assignee_type)})++ response = execute_hogql_query(+ f"SELECT assignee.{id_field} FROM system.support_tickets WHERE id = '{ticket.id}'",+ team=self.team,+ user=self.user,+ )++ assert str(response.results[0][0]) == str(get_expected_id(self))++ def test_unassigned_ticket_resolves_to_null(self):+ ticket = _create_support_ticket(self.team, "unassigned")++ response = execute_hogql_query(+ f"SELECT assignee.user_id, assignee.role_id FROM system.support_tickets WHERE id = '{ticket.id}'",+ team=self.team,+ user=self.user,+ )++ assert response.results == [(None, None)]++ def test_assignee_lazy_join_isolated_per_team(self):+ other_ticket = _create_support_ticket(self.other_team, "theirs")+ TicketAssignment.objects.create(ticket=other_ticket, user=self.user)++ response = execute_hogql_query(+ "SELECT id, assignee.user_id 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 c8df2ba36a67..35a63323cd34 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -8819,6 +8819,20 @@"schema_valid": true,"table": "ticket_tags","type": "lazy_table"+ },+ "assignee": {+ "chain": null,+ "fields": [+ "ticket_id",+ "user_id",+ "role_id"+ ],+ "hogql_value": "assignee",+ "id": "assignee",+ "name": "assignee",+ "schema_valid": true,+ "table": "ticket_assignment",+ "type": "lazy_table"}},"id": "system.support_tickets",@@ -17695,6 +17709,20 @@"schema_valid": true,"table": "ticket_tags","type": "lazy_table"+ },+ "assignee": {+ "chain": null,+ "fields": [+ "ticket_id",+ "user_id",+ "role_id"+ ],+ "hogql_value": "assignee",+ "id": "assignee",+ "name": "assignee",+ "schema_valid": true,+ "table": "ticket_assignment",+ "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 154ce53ff46f..8d6d881ab467 100644--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py@@ -207,5 +207,6 @@ class TestLazyJoinManifest(SimpleTestCase):"replay_to_sessions_v1","replay_to_sessions_v2","replay_to_sessions_v3",+ "ticket_assignment","ticket_tags",]