: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(customer-analytics): add account context joins to HogQL (#88914)
Arthur Moreira de Deuscfa1abf19bfd
diff --git a/posthog/hogql/database/lazy_join_registry.py b/posthog/hogql/database/lazy_join_registry.pyindex 5304a1331d26..39eab247c305 100644--- a/posthog/hogql/database/lazy_join_registry.py+++ b/posthog/hogql/database/lazy_join_registry.py@@ -35,8 +35,13 @@ from posthog.hogql.database.warehouse_join_resolvers import (from products.customer_analytics.backend.facade.hogql import (account_custom_properties_history_join,account_custom_properties_join,+ account_email_threads_join,+ account_feature_requests_join,+ account_meetings_join,account_notebooks_join,account_relationships_join,+ account_slack_summaries_join,+ account_support_tickets_join,account_tags_join,)@@ -83,7 +88,12 @@ RESOLVERS: dict[str, LazyJoinResolver] = {tags.ACCOUNT_NOTEBOOKS: account_notebooks_join,tags.ACCOUNT_CUSTOM_PROPERTIES: account_custom_properties_join,tags.ACCOUNT_CUSTOM_PROPERTIES_HISTORY: account_custom_properties_history_join,+ tags.ACCOUNT_EMAIL_THREADS: account_email_threads_join,+ tags.ACCOUNT_FEATURE_REQUESTS: account_feature_requests_join,+ tags.ACCOUNT_MEETINGS: account_meetings_join,tags.ACCOUNT_RELATIONSHIPS: account_relationships_join,+ tags.ACCOUNT_SLACK_SUMMARIES: account_slack_summaries_join,+ tags.ACCOUNT_SUPPORT_TICKETS: account_support_tickets_join,}diff --git a/posthog/hogql/database/lazy_join_tags.py b/posthog/hogql/database/lazy_join_tags.pyindex 647a1094a79e..4a6b6af64b5c 100644--- a/posthog/hogql/database/lazy_join_tags.py+++ b/posthog/hogql/database/lazy_join_tags.py@@ -29,4 +29,9 @@ ACCOUNT_TAGS = "account_tags"ACCOUNT_NOTEBOOKS = "account_notebooks"ACCOUNT_CUSTOM_PROPERTIES = "account_custom_properties"ACCOUNT_CUSTOM_PROPERTIES_HISTORY = "account_custom_properties_history"+ACCOUNT_EMAIL_THREADS = "account_email_threads"+ACCOUNT_FEATURE_REQUESTS = "account_feature_requests"+ACCOUNT_MEETINGS = "account_meetings"ACCOUNT_RELATIONSHIPS = "account_relationships"+ACCOUNT_SLACK_SUMMARIES = "account_slack_summaries"+ACCOUNT_SUPPORT_TICKETS = "account_support_tickets"diff --git a/posthog/hogql/database/schema/system.py b/posthog/hogql/database/schema/system.pyindex 8ae6402aaf17..352895d5e65e 100644--- a/posthog/hogql/database/schema/system.py+++ b/posthog/hogql/database/schema/system.py@@ -33,8 +33,12 @@ from posthog.constants import AvailableFeaturefrom posthog.scopes import APIScopeObjectfrom products.customer_analytics.backend.facade.hogql import (+ account_channel_summaries,account_custom_property_values,account_custom_property_values_history,+ account_email_thread_links,+ account_email_threads,+ account_meetings,account_relationship_definitions,account_relationships,account_resource_notebooks,@@ -2154,6 +2158,11 @@ support_tickets: PostgresTable = PostgresTable("ticket_number": IntegerDatabaseField(name="ticket_number", description="Human-friendly sequential ticket number."),+ "organization_id": StringDatabaseField(+ name="organization_id",+ nullable=True,+ description="Customer organization key. This matches a customer analytics account's external_id.",+ ),"channel_source": StringDatabaseField(name="channel_source", description="Channel the ticket came in on, e.g. 'email', 'widget'."),@@ -2828,6 +2837,14 @@ class SystemTables(TableNode):"_account_resource_notebooks": TableNode(name="_account_resource_notebooks", table=account_resource_notebooks, hidden=True),+ "_account_meetings": TableNode(name="_account_meetings", table=account_meetings, hidden=True),+ "_account_channel_summaries": TableNode(+ name="_account_channel_summaries", table=account_channel_summaries, hidden=True+ ),+ "_account_email_threads": TableNode(name="_account_email_threads", table=account_email_threads, hidden=True),+ "_account_email_thread_links": TableNode(+ name="_account_email_thread_links", table=account_email_thread_links, hidden=True+ ),"_account_custom_property_values": TableNode(name="_account_custom_property_values", table=account_custom_property_values, hidden=True),diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.pyindex 9c2b6b71811d..525646679171 100644--- a/posthog/hogql/database/schema/test/test_system_tables.py+++ b/posthog/hogql/database/schema/test/test_system_tables.py@@ -1,3 +1,4 @@+import jsonimport uuidfrom typing import TYPE_CHECKING@@ -732,6 +733,71 @@ def _create_support_ticket(team: Team, label: str) -> Ticket:widget_session_id=f"session_{label}",distinct_id=f"user_{label}",status="new",+ organization_id=f"organization_{label}",+ )+++def _create_account_meeting(team: Team, label: str):+ Account = apps.get_model("customer_analytics", "Account")+ Meeting = apps.get_model("customer_analytics", "Meeting")+ account = Account.objects.unscoped().create(team=team, name=f"account_{label}")+ return Meeting.objects.unscoped().create(+ team=team,+ account=account,+ ical_uid=f"meeting_{label}",+ start_time=timezone.now(),+ )+++def _create_account_channel_summary(team: Team, label: str):+ Account = apps.get_model("customer_analytics", "Account")+ AccountChannelSummary = apps.get_model("customer_analytics", "AccountChannelSummary")+ account = Account.objects.unscoped().create(team=team, name=f"account_{label}")+ return AccountChannelSummary.objects.unscoped().create(+ team=team,+ account=account,+ slack_channel_id=f"channel_{label}",+ cadence="daily",+ period_start=timezone.now(),+ period_end=timezone.now(),+ content=f"summary_{label}",+ )+++def _create_account_email_thread(team: Team, label: str):+ Account = apps.get_model("customer_analytics", "Account")+ EmailThread = apps.get_model("conversations", "EmailThread")+ EmailThreadAccountLink = apps.get_model("conversations", "EmailThreadAccountLink")+ account = Account.objects.unscoped().create(team=team, name=f"account_{label}")+ thread = EmailThread.objects.for_team(team.id).create(+ team=team,+ canonical_thread_key=f"thread_{label}",+ subject=f"subject_{label}",+ )+ EmailThreadAccountLink.objects.for_team(team.id).create(+ team=team,+ thread=thread,+ account_id=str(account.id),+ match_source="known_email",+ )+ return thread+++def _create_account_email_thread_link(team: Team, label: str):+ Account = apps.get_model("customer_analytics", "Account")+ EmailThread = apps.get_model("conversations", "EmailThread")+ EmailThreadAccountLink = apps.get_model("conversations", "EmailThreadAccountLink")+ account = Account.objects.unscoped().create(team=team, name=f"account_{label}")+ thread = EmailThread.objects.for_team(team.id).create(+ team=team,+ canonical_thread_key=f"thread_{label}",+ subject=f"subject_{label}",+ )+ return EmailThreadAccountLink.objects.for_team(team.id).create(+ team=team,+ thread=thread,+ account_id=str(account.id),+ match_source="known_email",)@@ -883,6 +949,10 @@ SYSTEM_TABLE_FACTORIES = [("cohorts", _create_cohort),("cohort_calculation_history", _create_cohort_calculation_history),("custom_property_definitions", _create_custom_property_definition),+ ("_account_meetings", _create_account_meeting),+ ("_account_channel_summaries", _create_account_channel_summary),+ ("_account_email_threads", _create_account_email_thread),+ ("_account_email_thread_links", _create_account_email_thread_link),("dashboards", _create_dashboard),("dashboard_tiles", _create_dashboard_tile),("dataset_item_versions", _create_dataset_item_version),@@ -1272,6 +1342,17 @@ class TestSystemTicketTagsLazyJoin(NonAtomicBaseTest):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_organization_id_is_queryable(self):+ ticket = _create_support_ticket(self.team, "organization")++ response = execute_hogql_query(+ f"SELECT organization_id FROM system.support_tickets WHERE id = '{ticket.id}'",+ team=self.team,+ user=self.user,+ )++ assert response.results == [("organization_organization",)]+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))@@ -1452,6 +1533,86 @@ class TestSystemAccountsLazyJoins(NonAtomicBaseTest):assert rows_by_id[str(account.id)] == 3+ def test_customer_context_lazy_joins_return_recent_account_records(self):+ account = Account.objects.unscoped().create(team=self.team, name="Acme", external_id="acme-org")+ Meeting = apps.get_model("customer_analytics", "Meeting")+ AccountChannelSummary = apps.get_model("customer_analytics", "AccountChannelSummary")+ EmailThread = apps.get_model("conversations", "EmailThread")+ EmailThreadAccountLink = apps.get_model("conversations", "EmailThreadAccountLink")++ Meeting.objects.unscoped().create(+ team=self.team,+ account=account,+ ical_uid="acme-meeting",+ start_time=timezone.now(),+ title="Account review",+ )+ AccountChannelSummary.objects.unscoped().create(+ team=self.team,+ account=account,+ slack_channel_id="C123",+ cadence="weekly",+ period_start=timezone.now(),+ period_end=timezone.now(),+ content="Account is healthy",+ )+ request = FeatureRequest.objects.unscoped().create(team=self.team, title="Export reports")+ FeatureRequestAccountLink.objects.unscoped().create(team=self.team, feature_request=request, account=account)+ ticket = Ticket.objects.create_with_number(+ team=self.team,+ channel_source="widget",+ widget_session_id="acme-ticket-session",+ distinct_id="acme-customer",+ status="open",+ organization_id=account.external_id,+ )+ thread = EmailThread.objects.for_team(self.team.id).create(+ team=self.team,+ canonical_thread_key="acme-thread",+ subject="Quarterly review",+ preview="Customer update",+ message_count=2,+ last_message_at=timezone.now(),+ )+ EmailThreadAccountLink.objects.for_team(self.team.id).create(+ team=self.team,+ thread=thread,+ account_id=str(account.id),+ match_source="known_email",+ )++ response = execute_hogql_query(+ f"""+ SELECT+ meetings.count,+ meetings.recent,+ slack_summaries.count,+ slack_summaries.recent,+ feature_requests.count,+ feature_requests.recent,+ support_tickets.count,+ support_tickets.recent,+ email_threads.count,+ email_threads.recent+ FROM system.accounts+ WHERE id = '{account.id}'+ """,+ team=self.team,+ user=self.user,+ )++ row = response.results[0]+ assert row[0] == 1+ assert json.loads(row[1])[0]["title"] == "Account review"+ assert row[2] == 1+ assert json.loads(row[3])[0]["content"] == "Account is healthy"+ assert row[4] == 1+ assert json.loads(row[5])[0]["title"] == "Export reports"+ assert row[6] == 1+ assert json.loads(row[7])[0]["id"] == str(ticket.id)+ assert row[8] == 1+ assert json.loads(row[9])[0]["subject"] == "Quarterly review"+def _custom_property_value(self, account, definition, **value_kwargs):return CustomPropertyValue.objects.unscoped().create(team=self.team, account=account, definition=definition, **value_kwargsdiff --git a/posthog/hogql/database/test/__snapshots__/test_database.ambr b/posthog/hogql/database/test/__snapshots__/test_database.ambrindex 301f1f76630c..c3dc17602991 100644--- a/posthog/hogql/database/test/__snapshots__/test_database.ambr+++ b/posthog/hogql/database/test/__snapshots__/test_database.ambr@@ -2837,6 +2837,81 @@"schema_valid": true,"table": "account_relationships","type": "lazy_table"+ },+ "meetings": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "latest_start_time",+ "recent"+ ],+ "hogql_value": "meetings",+ "id": "meetings",+ "name": "meetings",+ "schema_valid": true,+ "table": "account_meetings",+ "type": "lazy_table"+ },+ "slack_summaries": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "latest_generated_at",+ "recent"+ ],+ "hogql_value": "slack_summaries",+ "id": "slack_summaries",+ "name": "slack_summaries",+ "schema_valid": true,+ "table": "account_slack_summaries",+ "type": "lazy_table"+ },+ "feature_requests": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "last_updated_at",+ "recent"+ ],+ "hogql_value": "feature_requests",+ "id": "feature_requests",+ "name": "feature_requests",+ "schema_valid": true,+ "table": "account_feature_requests",+ "type": "lazy_table"+ },+ "support_tickets": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "last_message_at",+ "recent"+ ],+ "hogql_value": "support_tickets",+ "id": "support_tickets",+ "name": "support_tickets",+ "schema_valid": true,+ "table": "account_support_tickets",+ "type": "lazy_table"+ },+ "email_threads": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "last_message_at",+ "recent"+ ],+ "hogql_value": "email_threads",+ "id": "email_threads",+ "name": "email_threads",+ "schema_valid": true,+ "table": "account_email_threads",+ "type": "lazy_table"}},"id": "system.accounts",@@ -11027,6 +11102,16 @@"table": null,"type": "integer"},+ "organization_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "organization_id",+ "id": null,+ "name": "organization_id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },"channel_source": {"chain": null,"fields": null,@@ -14182,6 +14267,81 @@"schema_valid": true,"table": "account_relationships","type": "lazy_table"+ },+ "meetings": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "latest_start_time",+ "recent"+ ],+ "hogql_value": "meetings",+ "id": "meetings",+ "name": "meetings",+ "schema_valid": true,+ "table": "account_meetings",+ "type": "lazy_table"+ },+ "slack_summaries": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "latest_generated_at",+ "recent"+ ],+ "hogql_value": "slack_summaries",+ "id": "slack_summaries",+ "name": "slack_summaries",+ "schema_valid": true,+ "table": "account_slack_summaries",+ "type": "lazy_table"+ },+ "feature_requests": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "last_updated_at",+ "recent"+ ],+ "hogql_value": "feature_requests",+ "id": "feature_requests",+ "name": "feature_requests",+ "schema_valid": true,+ "table": "account_feature_requests",+ "type": "lazy_table"+ },+ "support_tickets": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "last_message_at",+ "recent"+ ],+ "hogql_value": "support_tickets",+ "id": "support_tickets",+ "name": "support_tickets",+ "schema_valid": true,+ "table": "account_support_tickets",+ "type": "lazy_table"+ },+ "email_threads": {+ "chain": null,+ "fields": [+ "account_id",+ "count",+ "last_message_at",+ "recent"+ ],+ "hogql_value": "email_threads",+ "id": "email_threads",+ "name": "email_threads",+ "schema_valid": true,+ "table": "account_email_threads",+ "type": "lazy_table"}},"id": "system.accounts",@@ -22372,6 +22532,16 @@"table": null,"type": "integer"},+ "organization_id": {+ "chain": null,+ "fields": null,+ "hogql_value": "organization_id",+ "id": null,+ "name": "organization_id",+ "schema_valid": true,+ "table": null,+ "type": "string"+ },"channel_source": {"chain": null,"fields": null,diff --git a/posthog/hogql/database/test/test_lazy_join_resolvers.py b/posthog/hogql/database/test/test_lazy_join_resolvers.pyindex 61061c0c3986..521b9286dee7 100644--- a/posthog/hogql/database/test/test_lazy_join_resolvers.py+++ b/posthog/hogql/database/test/test_lazy_join_resolvers.py@@ -214,8 +214,13 @@ class TestLazyJoinManifest(SimpleTestCase):assert sorted(RESOLVERS) == ["account_custom_properties","account_custom_properties_history",+ "account_email_threads",+ "account_feature_requests",+ "account_meetings","account_notebooks","account_relationships",+ "account_slack_summaries",+ "account_support_tickets","account_tags","data_warehouse","data_warehouse_experiments",diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.pyindex b376c4a2b6c2..e86a68468d2b 100644--- a/posthog/hogql_queries/access_controlled_resources.py+++ b/posthog/hogql_queries/access_controlled_resources.py@@ -44,6 +44,8 @@ _DATA_QUALITY_INFORMATION_SCHEMA_TABLES = frozenset(})+_ACCOUNT_COMMUNICATION_LAZY_FIELDS = frozenset({"email_threads", "support_tickets"})+def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str]]:"""The set of access-control scope names a query reads, e.g. "notebook", "warehouse_table".@@ -59,7 +61,8 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strfrom posthog.hogql.database.schema.system import access_controlled_system_tables # noqa: PLC0415from posthog.hogql.errors import BaseHogQLError # noqa: PLC0415from posthog.hogql.metadata import get_table_names # noqa: PLC0415- from posthog.hogql.parser import parse_select # noqa: PLC0415+ from posthog.hogql.parser import parse_expr, parse_select # noqa: PLC0415+ from posthog.hogql.visitor import GetFieldsTraverser # noqa: PLC0415from products.data_modeling.backend.facade.models import DataWarehouseSavedQueryfrom products.warehouse_sources.backend.facade.models import DataWarehouseTable # noqa: PLC0415@@ -67,6 +70,26 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strif getattr(query, "kind", None) == "AccountsTableQuery":return _with_fallback_parents({"account"})+ if getattr(query, "kind", None) == "AccountsQuery":+ expressions = [+ *(getattr(query, "select", None) or []),+ *(getattr(query, "metrics", None) or []),+ *(getattr(query, "orderBy", None) or []),+ ]+ filter_expression = getattr(query, "filterExpression", None)+ if filter_expression:+ expressions.append(filter_expression)+ try:+ fields = [+ field for expression in expressions for field in GetFieldsTraverser(parse_expr(expression)).fields+ ]+ except BaseHogQLError:+ return None+ account_scopes = {"account"}+ if any(any(str(segment) in _ACCOUNT_COMMUNICATION_LAZY_FIELDS for segment in field.chain) for field in fields):+ account_scopes.add("ticket")+ return _with_fallback_parents(account_scopes)+# Raw HogQL is the only query that references system.* and warehouse tables by nameif getattr(query, "kind", None) == "HogQLQuery":sql = getattr(query, "query", None)@@ -81,6 +104,13 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[strsystem_scopes = {f"system.{name}": scope for name, scope in access_controlled_system_tables().items()}scopes: set[str] = {system_scopes[name] for name in table_names if name in system_scopes}+ # Cache partitioning runs before lazy joins resolve, so their resource scopes do not appear as table names yet.+ if "system.accounts" in table_names and any(+ any(str(segment) in _ACCOUNT_COMMUNICATION_LAZY_FIELDS for segment in field.chain)+ for field in GetFieldsTraverser(select).fields+ ):+ scopes.add("ticket")+# The catalog-enriched information_schema tables aren't PostgresTables, so they're absent from# `access_controlled_system_tables()`; gate them explicitly on `data_catalog` read access.if table_names & _DATA_CATALOG_INFORMATION_SCHEMA_TABLES:diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.pyindex c105d247e8a0..227e85314742 100644--- a/posthog/hogql_queries/test/test_access_controlled_resources.py+++ b/posthog/hogql_queries/test/test_access_controlled_resources.py@@ -3,6 +3,7 @@ from posthog.test.base import BaseTestfrom parameterized import parameterizedfrom posthog.schema import (+ AccountsQuery,AccountsTableQuery,DataWarehouseNode,EntityType,@@ -65,6 +66,17 @@ class TestQueriedAccessControlledResources(BaseTest):("through_subquery", "select * from (select * from system.notebooks)", {"notebook"}),("through_cte_body", "with n as (select 1 from system.notebooks) select * from n", {"notebook"}),("multiple", "select 1 from system.notebooks, system.surveys", {"notebook", "survey"}),+ (+ "account_email_threads_lazy_join",+ "select accounts.email_threads.count from system.accounts as accounts",+ {"account", "ticket"},+ ),+ (+ "account_support_tickets_lazy_join",+ "select support_tickets.recent from system.accounts",+ {"account", "ticket"},+ ),+ ("account_non_communication_lazy_join", "select meetings.count from system.accounts", {"account"}),("no_access_controlled_table", "select 1", set()),("events_table", "select * from events", set()),# Catalog-enriched information_schema tables partition the cache by data_catalog access AND@@ -139,6 +151,17 @@ class TestQueriedAccessControlledResources(BaseTest):def test_accounts_table_query_partitions_on_account_access(self):assert queried_access_controlled_resources(AccountsTableQuery(columns=[], filters=[]), self.team) == {"account"}+ @parameterized.expand(+ [+ ("select", {"select": ["email_threads.count"]}),+ ("metric", {"metrics": ["sum(support_tickets.count)"]}),+ ("filter", {"filterExpression": "email_threads.count > 0"}),+ ("order", {"orderBy": ["support_tickets.count"]}),+ ]+ )+ def test_accounts_query_communication_fields_require_ticket_access(self, _name, query_kwargs):+ assert queried_access_controlled_resources(AccountsQuery(**query_kwargs), self.team) == {"account", "ticket"}+def test_structured_query_with_data_warehouse_series(self):query = TrendsQuery(series=[EventsNode(event="$pageview"), self._dw_node()])assert queried_access_controlled_resources(query, self.team) == {diff --git a/products/customer_analytics/backend/facade/hogql.py b/products/customer_analytics/backend/facade/hogql.pyindex 0d385f62337a..b369b83e1ebf 100644--- a/products/customer_analytics/backend/facade/hogql.py+++ b/products/customer_analytics/backend/facade/hogql.py@@ -20,8 +20,13 @@ from posthog.hogql.context import HogQLContextfrom posthog.hogql.database.lazy_join_tags import (ACCOUNT_CUSTOM_PROPERTIES,ACCOUNT_CUSTOM_PROPERTIES_HISTORY,+ ACCOUNT_EMAIL_THREADS,+ ACCOUNT_FEATURE_REQUESTS,+ ACCOUNT_MEETINGS,ACCOUNT_NOTEBOOKS,ACCOUNT_RELATIONSHIPS,+ ACCOUNT_SLACK_SUMMARIES,+ ACCOUNT_SUPPORT_TICKETS,ACCOUNT_TAGS,)from posthog.hogql.database.models import (@@ -43,7 +48,7 @@ from posthog.hogql.database.models import (UUIDDatabaseField,)from posthog.hogql.database.postgres_table import PostgresTable-from posthog.hogql.errors import ResolutionError+from posthog.hogql.errors import ResolutionError, TableAccessDeniedErrorfrom posthog.hogql.parser import parse_expr, parse_select@@ -91,6 +96,82 @@ account_resource_notebooks: _AccountScopedPostgresTable = _AccountScopedPostgres)+account_meetings: PostgresTable = PostgresTable(+ name="_account_meetings",+ postgres_table_name="customer_analytics_meeting",+ access_scope="account",+ access_control_id_field="account_id",+ description="Internal table of account meetings. Use `system.accounts.meetings` instead.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Meeting UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "account_id": UUIDDatabaseField(name="account_id", nullable=True),+ "title": StringDatabaseField(name="title"),+ "start_time": DateTimeDatabaseField(name="start_time"),+ "end_time": DateTimeDatabaseField(name="end_time", nullable=True),+ "organizer_email": StringDatabaseField(name="organizer_email"),+ "status": StringDatabaseField(name="status"),+ },+)+++account_channel_summaries: PostgresTable = PostgresTable(+ name="_account_channel_summaries",+ postgres_table_name="customer_analytics_accountchannelsummary",+ access_scope="account",+ access_control_id_field="account_id",+ description="Internal table of account Slack summaries. Use `system.accounts.slack_summaries` instead.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Summary UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "account_id": UUIDDatabaseField(name="account_id"),+ "slack_channel_id": StringDatabaseField(name="slack_channel_id"),+ "cadence": StringDatabaseField(name="cadence"),+ "period_start": DateTimeDatabaseField(name="period_start"),+ "period_end": DateTimeDatabaseField(name="period_end"),+ "content": StringDatabaseField(name="content"),+ "message_count": IntegerDatabaseField(name="message_count"),+ "generated_at": DateTimeDatabaseField(name="generated_at"),+ },+)+++account_email_threads: PostgresTable = PostgresTable(+ name="_account_email_threads",+ postgres_table_name="posthog_conversations_email_thread",+ access_scope="ticket",+ resource_level_access_only=True,+ predicates=[parse_expr("id IN (SELECT thread_id FROM system._account_email_thread_links)")],+ description="Internal table of customer email threads. Use `system.accounts.email_threads` instead.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Email thread UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "subject": StringDatabaseField(name="subject"),+ "first_message_at": DateTimeDatabaseField(name="first_message_at", nullable=True),+ "last_message_at": DateTimeDatabaseField(name="last_message_at", nullable=True),+ "message_count": IntegerDatabaseField(name="message_count"),+ "preview": StringDatabaseField(name="preview"),+ "created_at": DateTimeDatabaseField(name="created_at"),+ },+)+++account_email_thread_links: PostgresTable = PostgresTable(+ name="_account_email_thread_links",+ postgres_table_name="posthog_conversations_email_thread_account_link",+ access_scope="ticket",+ resource_level_access_only=True,+ predicates=[parse_expr("account_id IN (SELECT toString(id) FROM system.accounts)")],+ description="Internal table linking customer email threads to accounts. Use `system.accounts.email_threads` instead.",+ fields={+ "id": UUIDDatabaseField(name="id", description="Email thread account link UUID."),+ "team_id": IntegerDatabaseField(name="team_id"),+ "thread_id": UUIDDatabaseField(name="thread_id"),+ "account_id": StringDatabaseField(name="account_id"),+ },+)++account_custom_property_values: PostgresTable = PostgresTable(name="_account_custom_property_values",postgres_table_name="customer_analytics_custompropertyvalue",@@ -329,6 +410,164 @@ def _account_relationships_select(fields_accessed: dict[str, list[str | int]]) -)+def _account_meetings_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ account_id,+ count() AS count,+ max(start_time) AS latest_start_time,+ toJSONString(arrayMap(row -> map(+ 'id', row.2,+ 'title', row.3,+ 'start_time', row.1,+ 'end_time', row.4,+ 'status', row.5,+ 'organizer_email', row.6+ ), arraySlice(arrayReverseSort(groupArray(tuple(+ toString(start_time),+ toString(id),+ title,+ ifNull(toString(end_time), ''),+ status,+ organizer_email+ ))), 1, 10))) AS recent+ FROM system._account_meetings+ WHERE isNotNull(account_id)+ GROUP BY account_id+ """+ )+++def _account_slack_summaries_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ account_id,+ count() AS count,+ max(generated_at) AS latest_generated_at,+ toJSONString(arrayMap(row -> map(+ 'id', row.2,+ 'slack_channel_id', row.3,+ 'cadence', row.4,+ 'period_start', row.5,+ 'period_end', row.1,+ 'content', row.6,+ 'message_count', row.7,+ 'generated_at', row.8+ ), arraySlice(arrayReverseSort(groupArray(tuple(+ toString(period_end),+ toString(id),+ slack_channel_id,+ cadence,+ toString(period_start),+ content,+ toString(message_count),+ toString(generated_at)+ ))), 1, 10))) AS recent+ FROM system._account_channel_summaries+ GROUP BY account_id+ """+ )+++def _account_feature_requests_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ link.account_id AS account_id,+ count() AS count,+ max(request.updated_at) AS last_updated_at,+ toJSONString(arrayMap(row -> map(+ 'id', row.2,+ 'title', row.3,+ 'status', row.4,+ 'priority', row.5,+ 'updated_at', row.1+ ), arraySlice(arrayReverseSort(groupArray(tuple(+ toString(request.updated_at),+ toString(request.id),+ request.title,+ request.status,+ ifNull(request.priority, '')+ ))), 1, 10))) AS recent+ FROM system.feature_request_account_links AS link+ INNER JOIN system.feature_requests AS request ON request.id = link.feature_request_id+ WHERE isNull(request.archived_at)+ GROUP BY link.account_id+ """+ )+++def _account_support_tickets_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ account.id AS account_id,+ count() AS count,+ max(ticket.last_message_at) AS last_message_at,+ toJSONString(arrayMap(row -> map(+ 'id', row.2,+ 'ticket_number', row.3,+ 'channel_source', row.4,+ 'status', row.5,+ 'priority', row.6,+ 'last_message_at', row.1+ ), arraySlice(arrayReverseSort(groupArray(tuple(+ toString(ifNull(ticket.last_message_at, ticket.created_at)),+ ticket.id,+ toString(ticket.ticket_number),+ ticket.channel_source,+ ticket.status,+ ifNull(ticket.priority, '')+ ))), 1, 10))) AS recent+ FROM system.accounts AS account+ INNER JOIN system.support_tickets AS ticket ON ticket.organization_id = account.external_id+ WHERE isNotNull(account.external_id)+ GROUP BY account.id+ """+ )+++def _account_email_threads_select() -> ast.SelectQuery | ast.SelectSetQuery:+ return parse_select(+ """+ SELECT+ toUUID(link.account_id) AS account_id,+ count() AS count,+ max(thread.last_message_at) AS last_message_at,+ toJSONString(arrayMap(row -> map(+ 'id', row.2,+ 'subject', row.3,+ 'preview', row.4,+ 'first_message_at', row.5,+ 'last_message_at', row.1,+ 'message_count', row.6+ ), arraySlice(arrayReverseSort(groupArray(tuple(+ toString(ifNull(thread.last_message_at, thread.created_at)),+ toString(thread.id),+ thread.subject,+ thread.preview,+ ifNull(toString(thread.first_message_at), ''),+ toString(thread.message_count)+ ))), 1, 10))) AS recent+ FROM system._account_email_thread_links AS link+ INNER JOIN system._account_email_threads AS thread ON thread.id = link.thread_id+ GROUP BY link.account_id+ """+ )+++def _require_ticket_access(context: HogQLContext, table_name: str) -> None:+ database = context.database+ if database is None or database.is_table_access_denied("system.support_tickets"):+ raise TableAccessDeniedError(table_name)+ if database.user_access_control and not database.user_access_control.check_access_level_for_resource(+ "ticket", "viewer"+ ):+ raise TableAccessDeniedError(table_name)++class _AccountTagsTable(LazyTable):description: str = ("Internal aggregating table backing `system.accounts.tags`: the distinct, sorted tag names per account."@@ -475,6 +714,125 @@ class _AccountRelationshipsTable(LazyTable):return "account_relationships"+class _AccountMeetingsTable(LazyTable):+ description: str = "Meeting summaries for each account. `recent` contains the newest 10 meetings."+ fields: dict[str, FieldOrTable] = {+ "account_id": UUIDDatabaseField(name="account_id", description="Account the meetings belong to."),+ "count": IntegerDatabaseField(name="count", description="Number of meetings linked to the account."),+ "latest_start_time": DateTimeDatabaseField(+ name="latest_start_time", nullable=True, description="Start time of the latest meeting."+ ),+ "recent": StringJSONDatabaseField(name="recent", description="Newest 10 meeting summaries."),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ return _account_meetings_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "account_meetings"++ def to_printed_hogql(self) -> str:+ return "account_meetings"+++class _AccountSlackSummariesTable(LazyTable):+ description: str = "Slack summaries for each account. `recent` contains the newest 10 summaries."+ fields: dict[str, FieldOrTable] = {+ "account_id": UUIDDatabaseField(name="account_id", description="Account the Slack summaries belong to."),+ "count": IntegerDatabaseField(name="count", description="Number of Slack summaries for the account."),+ "latest_generated_at": DateTimeDatabaseField(+ name="latest_generated_at", nullable=True, description="When the latest Slack summary was generated."+ ),+ "recent": StringJSONDatabaseField(name="recent", description="Newest 10 Slack summaries."),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ return _account_slack_summaries_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "account_slack_summaries"++ def to_printed_hogql(self) -> str:+ return "account_slack_summaries"+++class _AccountFeatureRequestsTable(LazyTable):+ description: str = "Active feature requests linked to each account. `recent` contains the newest 10 requests."+ fields: dict[str, FieldOrTable] = {+ "account_id": UUIDDatabaseField(name="account_id", description="Account the feature requests are linked to."),+ "count": IntegerDatabaseField(+ name="count", description="Number of active feature requests linked to the account."+ ),+ "last_updated_at": DateTimeDatabaseField(+ name="last_updated_at", nullable=True, description="When the latest linked feature request was updated."+ ),+ "recent": StringJSONDatabaseField(name="recent", description="Newest 10 active feature requests."),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ return _account_feature_requests_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "account_feature_requests"++ def to_printed_hogql(self) -> str:+ return "account_feature_requests"+++class _AccountSupportTicketsTable(LazyTable):+ description: str = "Support tickets linked to each account. `recent` contains the newest 10 tickets."+ fields: dict[str, FieldOrTable] = {+ "account_id": UUIDDatabaseField(name="account_id", description="Account the support tickets belong to."),+ "count": IntegerDatabaseField(name="count", description="Number of support tickets linked to the account."),+ "last_message_at": DateTimeDatabaseField(+ name="last_message_at", nullable=True, description="When the latest support ticket message was sent."+ ),+ "recent": StringJSONDatabaseField(name="recent", description="Newest 10 support tickets."),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ _require_ticket_access(context, "system.support_tickets")+ return _account_support_tickets_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "account_support_tickets"++ def to_printed_hogql(self) -> str:+ return "account_support_tickets"+++class _AccountEmailThreadsTable(LazyTable):+ description: str = "Email threads linked to each account. `recent` contains the newest 10 threads."+ fields: dict[str, FieldOrTable] = {+ "account_id": UUIDDatabaseField(name="account_id", description="Account the email threads are linked to."),+ "count": IntegerDatabaseField(name="count", description="Number of email threads linked to the account."),+ "last_message_at": DateTimeDatabaseField(+ name="last_message_at", nullable=True, description="When the latest email message was sent."+ ),+ "recent": StringJSONDatabaseField(name="recent", description="Newest 10 email thread summaries."),+ }++ def lazy_select(+ self, table_to_add: LazyTableToAdd, context: HogQLContext, node: ast.SelectQuery+ ) -> ast.SelectQuery | ast.SelectSetQuery:+ _require_ticket_access(context, "system._account_email_threads")+ return _account_email_threads_select()++ def to_printed_clickhouse(self, context: HogQLContext) -> str:+ return "account_email_threads"++ def to_printed_hogql(self) -> str:+ return "account_email_threads"++def _join_on_account_id(select: ast.SelectQuery | ast.SelectSetQuery, join_to_add: LazyJoinToAdd) -> ast.JoinExpr:return ast.JoinExpr(alias=join_to_add.to_table,@@ -527,6 +885,46 @@ def account_relationships_join(return _join_on_account_id(_account_relationships_select(join_to_add.fields_accessed), join_to_add)+def account_meetings_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 `accounts.meetings`")+ return _join_on_account_id(_account_meetings_select(), join_to_add)+++def account_slack_summaries_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 `accounts.slack_summaries`")+ return _join_on_account_id(_account_slack_summaries_select(), join_to_add)+++def account_feature_requests_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 `accounts.feature_requests`")+ return _join_on_account_id(_account_feature_requests_select(), join_to_add)+++def account_support_tickets_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 `accounts.support_tickets`")+ _require_ticket_access(context, "system.support_tickets")+ return _join_on_account_id(_account_support_tickets_select(), join_to_add)+++def account_email_threads_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 `accounts.email_threads`")+ _require_ticket_access(context, "system._account_email_threads")+ return _join_on_account_id(_account_email_threads_select(), join_to_add)++account_tags_lazy_join: LazyJoin = LazyJoin(from_field=["id"],join_table=_AccountTagsTable(),@@ -558,6 +956,36 @@ account_relationships_lazy_join: LazyJoin = LazyJoin(resolver=ACCOUNT_RELATIONSHIPS,)+account_meetings_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_AccountMeetingsTable(),+ resolver=ACCOUNT_MEETINGS,+)++account_slack_summaries_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_AccountSlackSummariesTable(),+ resolver=ACCOUNT_SLACK_SUMMARIES,+)++account_feature_requests_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_AccountFeatureRequestsTable(),+ resolver=ACCOUNT_FEATURE_REQUESTS,+)++account_support_tickets_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_AccountSupportTicketsTable(),+ resolver=ACCOUNT_SUPPORT_TICKETS,+)++account_email_threads_lazy_join: LazyJoin = LazyJoin(+ from_field=["id"],+ join_table=_AccountEmailThreadsTable(),+ resolver=ACCOUNT_EMAIL_THREADS,+)+account_relationship_definitions: PostgresTable = PostgresTable(name="account_relationship_definitions",@@ -683,6 +1111,11 @@ accounts: PostgresTable = PostgresTable("custom_properties": account_custom_properties_lazy_join,"custom_properties_history": account_custom_properties_history_lazy_join,"relationships": account_relationships_lazy_join,+ "meetings": account_meetings_lazy_join,+ "slack_summaries": account_slack_summaries_lazy_join,+ "feature_requests": account_feature_requests_lazy_join,+ "support_tickets": account_support_tickets_lazy_join,+ "email_threads": account_email_threads_lazy_join,},)diff --git a/products/customer_analytics/backend/test/test_facade_hogql.py b/products/customer_analytics/backend/test/test_facade_hogql.pyindex 72310233402b..f27b2bd539f7 100644--- a/products/customer_analytics/backend/test/test_facade_hogql.py+++ b/products/customer_analytics/backend/test/test_facade_hogql.py@@ -7,24 +7,36 @@from uuid import uuid4from posthog.test.base import NonAtomicBaseTest+from unittest.mock import Mockfrom django.test import SimpleTestCasefrom django.utils import timezonefrom parameterized import parameterized+from posthog.hogql.context import HogQLContext+from posthog.hogql.database.database import Databasefrom posthog.hogql.database.models import ExpressionField, LazyJoin, Table-from posthog.hogql.errors import QueryError+from posthog.hogql.errors import QueryError, TableAccessDeniedErrorfrom posthog.hogql.query import execute_hogql_query+from posthog.auth import ProjectSecretAPIKeyUserfrom posthog.models import OrganizationMembership, TaggedItem, Userfrom posthog.models.organization import AvailableFeature+from posthog.models.project_secret_api_key import ProjectSecretAPIKeyfrom products.access_control.backend.models.access_control import AccessControl+from products.conversations.backend.models import EmailThread, EmailThreadAccountLinkfrom products.customer_analytics.backend.facade.hogql import (+ account_channel_summaries,account_custom_property_values,account_custom_property_values_history,+ account_email_thread_links,+ account_email_threads,+ account_email_threads_join,+ account_meetings,account_resource_notebooks,+ account_support_tickets_join,account_tagged_items,accounts,custom_property_definitions,@@ -37,6 +49,7 @@ from products.customer_analytics.backend.facade.hogql import ()from products.customer_analytics.backend.models import (Account,+ AccountChannelSummary,CustomPropertyDefinition,CustomPropertyValue,FeatureRequest,@@ -46,6 +59,7 @@ from products.customer_analytics.backend.models import (FeatureRequestProductArea,FeatureRequestProductAreaLink,)+from products.customer_analytics.backend.models.meeting import Meetingfrom products.notebooks.backend.models import ResourceNotebook@@ -58,6 +72,10 @@ class TestFacadeHogqlSystemTables(SimpleTestCase):("account_custom_property_values_history", account_custom_property_values_history, CustomPropertyValue),("account_tagged_items", account_tagged_items, TaggedItem),("account_resource_notebooks", account_resource_notebooks, ResourceNotebook),+ ("account_meetings", account_meetings, Meeting),+ ("account_channel_summaries", account_channel_summaries, AccountChannelSummary),+ ("account_email_threads", account_email_threads, EmailThread),+ ("account_email_thread_links", account_email_thread_links, EmailThreadAccountLink),("feature_requests", feature_requests, FeatureRequest),("feature_request_product_areas", feature_request_product_areas, FeatureRequestProductArea),("feature_request_account_links", feature_request_account_links, FeatureRequestAccountLink),@@ -83,6 +101,104 @@ class TestFacadeHogqlSystemTables(SimpleTestCase):)+class TestAccountCommunicationHogqlAccess(SimpleTestCase):+ @parameterized.expand(+ [+ ("email_threads", account_email_threads_join, "system._account_email_threads"),+ ("support_tickets", account_support_tickets_join, "system.support_tickets"),+ ]+ )+ def test_ticket_access_is_required(self, _name, resolver, table_name) -> None:+ access_control = Mock()+ access_control.check_access_level_for_resource.return_value = False+ database = Mock(user_access_control=access_control)+ database.is_table_access_denied.return_value = False+ context = HogQLContext(database=database)+ join_to_add = Mock(fields_accessed={"count": ["count"]})++ with self.assertRaises(TableAccessDeniedError) as error:+ resolver(join_to_add, context, Mock())++ assert error.exception.table_name == table_name+ access_control.check_access_level_for_resource.assert_called_once_with("ticket", "viewer")+++class TestAccountCommunicationHogqlProjectSecretKey(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ @parameterized.expand(+ [+ ("email_threads", account_email_threads_join),+ ("support_tickets", account_support_tickets_join),+ ]+ )+ def test_ticket_scoped_key_can_resolve_communication_join(self, _name, resolver) -> None:+ key = ProjectSecretAPIKey.objects.create(+ team=self.team,+ label="account-communication-access",+ secure_value="sha256$" + "f" * 64,+ scopes=["account:read", "ticket:read"],+ )+ context = HogQLContext(database=Database.create_for(team=self.team, user=ProjectSecretAPIKeyUser(key)))++ resolver(Mock(fields_accessed={"count": ["count"]}), context, Mock())+++class TestAccountCommunicationHogqlIsolation(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def test_hidden_email_tables_require_ticket_access_and_filter_denied_accounts(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},+ ]+ self.organization.save()+ viewer = User.objects.create_and_join(self.organization, "[email protected]", "testtest")+ membership = OrganizationMembership.objects.get(user=viewer, organization=self.organization)+ visible_account = Account.objects.unscoped().create(team=self.team, name="Visible account")+ denied_account = Account.objects.unscoped().create(team=self.team, name="Denied account")++ for account, subject in ((visible_account, "Visible thread"), (denied_account, "Denied thread")):+ thread = EmailThread.objects.for_team(self.team.id).create(+ team=self.team,+ canonical_thread_key=f"thread-{account.id}",+ subject=subject,+ )+ EmailThreadAccountLink.objects.for_team(self.team.id).create(+ team=self.team,+ thread=thread,+ account_id=str(account.id),+ match_source="known_email",+ )++ AccessControl.objects.create(+ team=self.team,+ resource="account",+ resource_id=str(denied_account.id),+ access_level="none",+ organization_member=membership,+ )++ threads = execute_hogql_query(+ "SELECT subject FROM system._account_email_threads", team=self.team, user=viewer+ ).results+ links = execute_hogql_query(+ "SELECT account_id FROM system._account_email_thread_links", team=self.team, user=viewer+ ).results++ assert threads == [("Visible thread",)]+ assert links == [(str(visible_account.id),)]++ AccessControl.objects.create(+ team=self.team,+ resource="ticket",+ access_level="none",+ organization_member=membership,+ )+ with self.assertRaises(TableAccessDeniedError):+ execute_hogql_query("SELECT subject FROM system._account_email_threads", team=self.team, user=viewer)++class TestFeatureRequestHogqlAccess(NonAtomicBaseTest):CLASS_DATA_LEVEL_SETUP = Falsediff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-customer-analytics.md b/products/posthog_ai/skills/querying-posthog-data/references/models-customer-analytics.mdindex e6261a6e8de4..0a08d5ff1e5d 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-customer-analytics.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-customer-analytics.md@@ -27,7 +27,20 @@ Column | Type | Nullable | Description`created_at` | timestamptz | NOT NULL | When the account was created`updated_at` | timestamptz | NULL | When the account was last updated-Lazy-joined fields: `tags` (tag names), `custom_properties` (see below), `relationships` (active assignments keyed by definition id), `notebooks`.+Lazy-joined fields:++- `tags.names`: tag names.+- `notebooks.count`: number of linked internal notes.+- `custom_properties.values`: current values keyed by immutable definition ID.+- `custom_properties_history.values`: numeric value history keyed by immutable definition ID.+- `relationships.values`: active user IDs keyed by immutable relationship-definition ID.+- `meetings`: meeting count, latest start time, and the newest 10 meeting summaries.+- `slack_summaries`: summary count, latest generation time, and the newest 10 Slack summaries.+- `feature_requests`: active request count, latest update time, and the newest 10 linked requests.+- `support_tickets`: ticket count, latest message time, and the newest 10 linked tickets. Requires ticket access.+- `email_threads`: thread count, latest message time, and the newest 10 linked email threads. Requires ticket access.++The `recent` fields are JSON arrays. They hold at most 10 records, newest first. Use the top-level tables when you need complete history.## Account relationships (`system.account_relationship_definitions`, `system.account_relationships`)@@ -216,7 +229,7 @@ There is no standalone values table. An account's current value for a definitionaccounts.custom_properties.values.`<definition_id>````-The `<definition_id>` is a `system.custom_property_definitions.id` (backtick-quoted, since it is a UUID). Only the current value is returned — superseded (soft-deleted) values are excluded — and it is team-isolated via the accounts row.+The `<definition_id>` is a `system.custom_property_definitions.id` (backtick-quoted, since it is a UUID). Only the current value is returned. Superseded values are excluded. The immutable ID keeps saved queries working when a property name changes.## Common query patternsdiff --git a/products/posthog_ai/skills/querying-posthog-data/references/models-support-tickets.md b/products/posthog_ai/skills/querying-posthog-data/references/models-support-tickets.mdindex aea317d3512a..c7c830e604c5 100644--- a/products/posthog_ai/skills/querying-posthog-data/references/models-support-tickets.md+++ b/products/posthog_ai/skills/querying-posthog-data/references/models-support-tickets.md@@ -10,6 +10,7 @@ Column | Type | Nullable | Description`id` | uuid | NOT NULL | Primary key`team_id` | integer | NOT NULL | Team this ticket belongs to`ticket_number` | integer | NOT NULL | Auto-incrementing number, unique per team+`organization_id` | varchar(400) | NULL | Customer organization key. Matches a customer analytics account's `external_id`.`channel_source` | varchar(20) | NOT NULL | Origin channel: `widget`, `email`, or `slack``channel_detail` | varchar(30) | NULL | Sub-type: `slack_channel_message`, `slack_bot_mention`, `slack_emoji_reaction`, `widget_embedded`, `widget_api``distinct_id` | varchar(400) | NOT NULL | PostHog distinct_id linking the ticket to a person@@ -32,6 +33,7 @@ Column | Type | Nullable | Description### Key Relationships- Tickets belong to a **Team** (`team_id`)+- Tickets can link to a customer analytics account through `organization_id = system.accounts.external_id`- Tickets are linked to a **Person** via `distinct_id`- Ticket assignments are managed via `TicketAssignment` (not exposed as a system table)