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(customer-analytics): add postgres accounts table query (#79989)

Arthur Moreira de Deus112c2a10d29b
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 69c9fd7849a1..91fee7190fdd 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -239,6 +239,328 @@
"required": ["columns", "hogql", "kind", "limit", "offset", "results", "types"],
"type": "object"
},
+ "AccountsTableAccountField": {
+ "enum": [
+ "name",
+ "external_id",
+ "created_at",
+ "updated_at",
+ "stripe_customer_id",
+ "hubspot_deal_id",
+ "billing_id",
+ "sfdc_id",
+ "zendesk_id"
+ ],
+ "type": "string"
+ },
+ "AccountsTableAccountFieldColumn": {
+ "additionalProperties": false,
+ "properties": {
+ "field": {
+ "$ref": "#/definitions/AccountsTableAccountField"
+ },
+ "kind": {
+ "const": "account_field",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "field"],
+ "type": "object"
+ },
+ "AccountsTableColumn": {
+ "description": "A typed column supported by the Postgres-backed Accounts table.",
+ "discriminator": {
+ "propertyName": "kind"
+ },
+ "oneOf": [
+ {
+ "$ref": "#/definitions/AccountsTableAccountFieldColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableTagsColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableNoteCountColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableRelationshipColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableCustomPropertyColumn"
+ },
+ {
+ "$ref": "#/definitions/AccountsTableCustomPropertyHistoryColumn"
+ }
+ ],
+ "required": ["kind"],
+ "type": "object"
+ },
+ "AccountsTableCustomPropertyColumn": {
+ "additionalProperties": false,
+ "properties": {
+ "definitionId": {
+ "description": "Team-scoped custom property definition to return for each account.",
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom_property",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "definitionId"],
+ "type": "object"
+ },
+ "AccountsTableCustomPropertyHistoryColumn": {
+ "additionalProperties": false,
+ "properties": {
+ "definitionId": {
+ "description": "Team-scoped numeric custom property definition whose write history should be returned.",
+ "type": "string"
+ },
+ "kind": {
+ "const": "custom_property_history",
+ "type": "string"
+ },
+ "windowDays": {
+ "description": "Number of days of history to return. The current value is included even when it is older.",
+ "enum": [7, 14, 30, 90],
+ "type": "number"
+ }
+ },
+ "required": ["kind", "definitionId", "windowDays"],
+ "type": "object"
+ },
+ "AccountsTableCustomPropertyHistoryPoint": {
+ "additionalProperties": false,
+ "properties": {
+ "timestamp": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "value": {
+ "type": "number"
+ }
+ },
+ "required": ["timestamp", "value"],
+ "type": "object"
+ },
+ "AccountsTableCustomPropertyValue": {
+ "type": ["string", "number", "boolean", "null"]
+ },
+ "AccountsTableNoteCountColumn": {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "note_count",
+ "type": "string"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
+ "AccountsTableQuery": {
+ "additionalProperties": false,
+ "properties": {
+ "columns": {
+ "description": "Columns to load for each account. Account identity fields are always returned.",
+ "items": {
+ "$ref": "#/definitions/AccountsTableColumn"
+ },
+ "type": "array"
+ },
+ "kind": {
+ "const": "AccountsTableQuery",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/positive_integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "response": {
+ "$ref": "#/definitions/AccountsTableQueryResponse"
+ },
+ "tags": {
+ "$ref": "#/definitions/QueryLogTags"
+ },
+ "version": {
+ "description": "version of the node, used for schema migrations",
+ "type": "number"
+ }
+ },
+ "required": ["columns", "kind"],
+ "type": "object"
+ },
+ "AccountsTableQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hasMore": {
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "kind": {
+ "const": "AccountsTableQuery",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["hasMore", "kind", "limit", "offset", "results"],
+ "type": "object"
+ },
+ "AccountsTableRelationshipColumn": {
+ "additionalProperties": false,
+ "properties": {
+ "definitionId": {
+ "description": "Team-scoped relationship definition to return for each account.",
+ "type": "string"
+ },
+ "kind": {
+ "const": "relationship",
+ "type": "string"
+ }
+ },
+ "required": ["kind", "definitionId"],
+ "type": "object"
+ },
+ "AccountsTableRow": {
+ "additionalProperties": false,
+ "properties": {
+ "accountFields": {
+ "additionalProperties": {
+ "type": ["string", "null"]
+ },
+ "description": "Requested direct Account fields, keyed by their typed field reference.",
+ "type": "object"
+ },
+ "customProperties": {
+ "additionalProperties": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyValue"
+ },
+ "description": "Current values keyed by requested custom property definition ID.",
+ "type": "object"
+ },
+ "customPropertyHistory": {
+ "additionalProperties": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableCustomPropertyHistoryPoint"
+ },
+ "type": "array"
+ },
+ "description": "Numeric write history keyed by requested custom property definition ID.",
+ "type": "object"
+ },
+ "externalId": {
+ "type": ["string", "null"]
+ },
+ "id": {
+ "type": "string"
+ },
+ "name": {
+ "type": "string"
+ },
+ "noteCount": {
+ "$ref": "#/definitions/integer",
+ "description": "Number of linked internal notes. Omitted when the request does not select the note count."
+ },
+ "relationships": {
+ "additionalProperties": {
+ "items": {
+ "$ref": "#/definitions/integer"
+ },
+ "type": "array"
+ },
+ "description": "Active assignee user IDs keyed by requested relationship definition ID.",
+ "type": "object"
+ },
+ "tags": {
+ "description": "Sorted tag names. Omitted when the request does not select tags.",
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": ["id", "name", "accountFields", "relationships", "customProperties", "customPropertyHistory"],
+ "type": "object"
+ },
+ "AccountsTableTagsColumn": {
+ "additionalProperties": false,
+ "properties": {
+ "kind": {
+ "const": "tags",
+ "type": "string"
+ }
+ },
+ "required": ["kind"],
+ "type": "object"
+ },
"ActionConversionGoal": {
"additionalProperties": false,
"properties": {
@@ -1020,6 +1342,9 @@
{
"$ref": "#/definitions/AccountsQuery"
},
+ {
+ "$ref": "#/definitions/AccountsTableQuery"
+ },
{
"$ref": "#/definitions/EndpointsUsageOverviewQuery"
},
@@ -5602,6 +5927,123 @@
],
"type": "object"
},
+ "CachedAccountsTableQueryResponse": {
+ "additionalProperties": false,
+ "properties": {
+ "cache_key": {
+ "type": "string"
+ },
+ "cache_target_age": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "calculation_trigger": {
+ "description": "What triggered the calculation of the query, leave empty if user/immediate",
+ "type": "string"
+ },
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hasMore": {
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "is_cached": {
+ "type": "boolean"
+ },
+ "kind": {
+ "const": "AccountsTableQuery",
+ "type": "string"
+ },
+ "last_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "next_allowed_client_refresh": {
+ "format": "date-time",
+ "type": "string"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "query_metadata": {
+ "type": "object"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRow"
+ },
+ "type": "array"
+ },
+ "timezone": {
+ "type": "string"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "cache_key",
+ "hasMore",
+ "is_cached",
+ "kind",
+ "last_refresh",
+ "limit",
+ "next_allowed_client_refresh",
+ "offset",
+ "results",
+ "timezone"
+ ],
+ "type": "object"
+ },
"CachedActorsPropertyTaxonomyQueryResponse": {
"additionalProperties": false,
"properties": {
@@ -35532,6 +35974,7 @@
"DocumentSimilarityQuery",
"UsageMetricsQuery",
"AccountsQuery",
+ "AccountsTableQuery",
"EndpointsUsageOverviewQuery",
"EndpointsUsageTableQuery",
"EndpointsUsageTrendsQuery",
@@ -44001,6 +44444,84 @@
"required": ["columns", "hogql", "kind", "limit", "offset", "results", "types"],
"type": "object"
},
+ {
+ "additionalProperties": false,
+ "properties": {
+ "error": {
+ "description": "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise.",
+ "type": "string"
+ },
+ "hasMore": {
+ "type": "boolean"
+ },
+ "hogql": {
+ "description": "Generated HogQL query.",
+ "type": "string"
+ },
+ "kind": {
+ "const": "AccountsTableQuery",
+ "type": "string"
+ },
+ "limit": {
+ "$ref": "#/definitions/integer"
+ },
+ "modifiers": {
+ "$ref": "#/definitions/HogQLQueryModifiers",
+ "description": "Modifiers used when performing the query"
+ },
+ "offset": {
+ "$ref": "#/definitions/integer"
+ },
+ "query_status": {
+ "$ref": "#/definitions/QueryStatus",
+ "description": "Query status indicates whether next to the provided data, a query is still running."
+ },
+ "resolved_compare_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The resolved previous/comparison period date range, when comparing against another period"
+ },
+ "resolved_date_range": {
+ "$ref": "#/definitions/ResolvedDateRangeResponse",
+ "description": "The date range used for the query"
+ },
+ "results": {
+ "items": {
+ "$ref": "#/definitions/AccountsTableRow"
+ },
+ "type": "array"
+ },
+ "timings": {
+ "description": "Measured timings for different parts of the query generation process",
+ "items": {
+ "$ref": "#/definitions/QueryTiming"
+ },
+ "type": "array"
+ },
+ "used_data_warehouse_sources": {
+ "description": "Connector-synced data warehouse sources referenced by this query, if any.",
+ "items": {
+ "$ref": "#/definitions/DataWarehouseSourceUsage"
+ },
+ "type": "array"
+ },
+ "warnings": {
+ "description": "Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access.",
+ "items": {
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DataWarehouseSyncWarning"
+ },
+ {
+ "$ref": "#/definitions/AccessControlFilterWarning"
+ }
+ ]
+ },
+ "type": "array"
+ }
+ },
+ "required": ["hasMore", "kind", "limit", "offset", "results"],
+ "type": "object"
+ },
{
"additionalProperties": false,
"properties": {
@@ -45484,6 +46005,9 @@
{
"$ref": "#/definitions/AccountsQuery"
},
+ {
+ "$ref": "#/definitions/AccountsTableQuery"
+ },
{
"$ref": "#/definitions/EndpointsUsageOverviewQuery"
},
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index e76690be8d8f..3056dfa475fa 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -183,6 +183,7 @@ export enum NodeKind {
// Customer analytics
UsageMetricsQuery = 'UsageMetricsQuery',
AccountsQuery = 'AccountsQuery',
+ AccountsTableQuery = 'AccountsTableQuery',
// Endpoints usage queries
EndpointsUsageOverviewQuery = 'EndpointsUsageOverviewQuery',
@@ -267,6 +268,7 @@ export type AnyDataNode =
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -390,6 +392,7 @@ export type QuerySchema =
// Customer analytics
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
// Endpoints usage
| EndpointsUsageOverviewQuery
@@ -2759,6 +2762,107 @@ export interface AccountsQuery extends DataNode<AccountsQueryResponse> {
offset?: integer
}
+export enum AccountsTableAccountField {
+ Name = 'name',
+ ExternalId = 'external_id',
+ CreatedAt = 'created_at',
+ UpdatedAt = 'updated_at',
+ StripeCustomerId = 'stripe_customer_id',
+ HubspotDealId = 'hubspot_deal_id',
+ BillingId = 'billing_id',
+ SalesforceId = 'sfdc_id',
+ ZendeskId = 'zendesk_id',
+}
+
+export interface AccountsTableAccountFieldColumn {
+ kind: 'account_field'
+ field: AccountsTableAccountField
+}
+
+export interface AccountsTableTagsColumn {
+ kind: 'tags'
+}
+
+export interface AccountsTableNoteCountColumn {
+ kind: 'note_count'
+}
+
+export interface AccountsTableRelationshipColumn {
+ kind: 'relationship'
+ /** Team-scoped relationship definition to return for each account. */
+ definitionId: string
+}
+
+export interface AccountsTableCustomPropertyColumn {
+ kind: 'custom_property'
+ /** Team-scoped custom property definition to return for each account. */
+ definitionId: string
+}
+
+export interface AccountsTableCustomPropertyHistoryColumn {
+ kind: 'custom_property_history'
+ /** Team-scoped numeric custom property definition whose write history should be returned. */
+ definitionId: string
+ /** Number of days of history to return. The current value is included even when it is older. */
+ windowDays: 7 | 14 | 30 | 90
+}
+
+/**
+ * A typed column supported by the Postgres-backed Accounts table.
+ * @discriminator kind
+ */
+export type AccountsTableColumn =
+ | AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn
+
+export type AccountsTableCustomPropertyValue = string | number | boolean | null
+
+export interface AccountsTableCustomPropertyHistoryPoint {
+ /** @format date-time */
+ timestamp: string
+ value: number
+}
+
+export interface AccountsTableRow {
+ id: string
+ name: string
+ externalId?: string | null
+ /** Requested direct Account fields, keyed by their typed field reference. */
+ accountFields: Record<string, string | null>
+ /** Sorted tag names. Omitted when the request does not select tags. */
+ tags?: string[]
+ /** Number of linked internal notes. Omitted when the request does not select the note count. */
+ noteCount?: integer
+ /** Active assignee user IDs keyed by requested relationship definition ID. */
+ relationships: Record<string, integer[]>
+ /** Current values keyed by requested custom property definition ID. */
+ customProperties: Record<string, AccountsTableCustomPropertyValue>
+ /** Numeric write history keyed by requested custom property definition ID. */
+ customPropertyHistory: Record<string, AccountsTableCustomPropertyHistoryPoint[]>
+}
+
+export type CachedAccountsTableQueryResponse = CachedQueryResponse<AccountsTableQueryResponse>
+
+export interface AccountsTableQueryResponse extends AnalyticsQueryResponseBase {
+ kind: NodeKind.AccountsTableQuery
+ results: AccountsTableRow[]
+ hasMore: boolean
+ limit: integer
+ offset: integer
+}
+
+export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse> {
+ kind: NodeKind.AccountsTableQuery
+ /** Columns to load for each account. Account identity fields are always returned. */
+ columns: AccountsTableColumn[]
+ limit?: positive_integer
+ offset?: integer
+}
+
export interface TimelineEntry {
/** Session ID. None means out-of-session events */
sessionId?: string
diff --git a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
index a00db1f97b0f..2d335ef1f259 100644
--- a/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
+++ b/frontend/src/scenes/saved-insights/insightTypesMetadata.tsx
@@ -555,6 +555,11 @@ export const QUERY_TYPES_METADATA: Record<NodeKind, InsightTypeMetadata> = {
icon: IconPieChart,
inMenu: false,
},
+ [NodeKind.AccountsTableQuery]: {
+ name: 'Accounts table',
+ icon: IconPieChart,
+ inMenu: false,
+ },
[NodeKind.EndpointsUsageOverviewQuery]: {
name: 'Endpoints usage overview',
icon: IconPieChart,
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 159e384f3393..3dd772843012 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -162,6 +162,7 @@ def _process_query_request(
# API token must hold the product scope, not just query:read, to run them through
# the generic endpoint.
_QUERY_KIND_SCOPES: dict[str, list[str]] = {
+ "AccountsTableQuery": ["query:read", "account:read"],
"MetricsQuery": ["metrics:read"],
# Both scopes listed: this result replaces the view's default query:read
# rather than adding to it, and a token must hold every listed scope.
diff --git a/posthog/clickhouse/query_tagging.py b/posthog/clickhouse/query_tagging.py
index 3585cf725eae..163eb2b4649a 100644
--- a/posthog/clickhouse/query_tagging.py
+++ b/posthog/clickhouse/query_tagging.py
@@ -222,6 +222,8 @@ def kind_fallback_tags(kind: NodeKind) -> FallbackTags | None:
return {"product": Product.LOGS}
case NodeKind.METRICS_QUERY:
return {"product": Product.METRICS}
+ case NodeKind.ACCOUNTS_TABLE_QUERY:
+ return {"product": Product.CUSTOMER_ANALYTICS}
case NodeKind.RECORDINGS_QUERY | NodeKind.SESSION_BATCH_EVENTS_QUERY:
return {"product": Product.REPLAY}
case (
diff --git a/posthog/hogql_queries/access_controlled_resources.py b/posthog/hogql_queries/access_controlled_resources.py
index ecedc37fdd0f..d8e58b7a04dd 100644
--- a/posthog/hogql_queries/access_controlled_resources.py
+++ b/posthog/hogql_queries/access_controlled_resources.py
@@ -52,6 +52,9 @@ def queried_access_controlled_resources(query, team: "Team") -> Optional[set[str
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.warehouse_sources.backend.facade.models import DataWarehouseTable # noqa: PLC0415
+ if getattr(query, "kind", None) == "AccountsTableQuery":
+ return _with_fallback_parents({"account"})
+
# Raw HogQL is the only query that references system.* and warehouse tables by name
if getattr(query, "kind", None) == "HogQLQuery":
sql = getattr(query, "query", None)
diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.py
index e3be86acecd6..8a850cedcdd8 100644
--- a/posthog/hogql_queries/query_runner.py
+++ b/posthog/hogql_queries/query_runner.py
@@ -14,6 +14,7 @@ from pydantic import BaseModel, ConfigDict
from posthog.schema import (
AccountsQuery,
+ AccountsTableQuery,
ActorsPropertyTaxonomyQuery,
ActorsQuery,
BreakdownType,
@@ -366,6 +367,7 @@ RunnableQueryNode = Union[
ActorsPropertyTaxonomyQuery,
UsageMetricsQuery,
AccountsQuery,
+ AccountsTableQuery,
EndpointsUsageOverviewQuery,
EndpointsUsageTableQuery,
EndpointsUsageTrendsQuery,
@@ -1244,6 +1246,18 @@ def get_query_runner(
user=user,
)
+ if kind == "AccountsTableQuery":
+ from products.customer_analytics.backend.facade.queries import AccountsTableQueryRunner
+
+ return AccountsTableQueryRunner(
+ query=query,
+ team=team,
+ timings=timings,
+ modifiers=modifiers,
+ limit_context=limit_context,
+ user=user,
+ )
+
if kind == "EndpointsUsageOverviewQuery":
from .endpoints.endpoints_usage_overview import EndpointsUsageOverviewQueryRunner
diff --git a/posthog/hogql_queries/test/test_access_controlled_resources.py b/posthog/hogql_queries/test/test_access_controlled_resources.py
index 4983bcede32e..48dc285cc799 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 BaseTest
from parameterized import parameterized
from posthog.schema import (
+ AccountsTableQuery,
DataWarehouseNode,
EntityType,
EventsNode,
@@ -116,6 +117,9 @@ class TestQueriedAccessControlledResources(BaseTest):
query = TrendsQuery(series=[EventsNode(event="$pageview")])
assert queried_access_controlled_resources(query, self.team) == set()
+ def test_accounts_table_query_partitions_on_account_access(self):
+ assert queried_access_controlled_resources(AccountsTableQuery(columns=[]), self.team) == {"account"}
+
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/posthog/schema.py b/posthog/schema.py
index ed7184794d0b..c0349b38aba2 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -13,6 +13,7 @@ from pydantic import AwareDatetime, BaseModel, ConfigDict, Field, RootModel, con
from posthog.schema_discriminators import property_filter_discriminator
from posthog.schema_enums import (
AccessControlLevel as AccessControlLevel,
+ AccountsTableAccountField as AccountsTableAccountField,
Action as Action,
AgentMode as AgentMode,
AggregationAxisFormat as AggregationAxisFormat,
@@ -294,6 +295,7 @@ from posthog.schema_enums import (
WebVitalsMetric as WebVitalsMetric,
WebVitalsMetricBand as WebVitalsMetricBand,
WebVitalsPercentile as WebVitalsPercentile,
+ WindowDays as WindowDays,
YAxisPosition as YAxisPosition,
YAxisScaleType as YAxisScaleType,
)
@@ -320,6 +322,73 @@ class AccessControlFilterWarning(BaseModel):
)
+class AccountsTableAccountFieldColumn(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ field: AccountsTableAccountField
+ kind: Literal["account_field"] = "account_field"
+
+
+class AccountsTableCustomPropertyColumn(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ definitionId: str = Field(
+ ...,
+ description=("Team-scoped custom property definition to return for each account."),
+ )
+ kind: Literal["custom_property"] = "custom_property"
+
+
+class AccountsTableCustomPropertyHistoryColumn(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ definitionId: str = Field(
+ ...,
+ description=("Team-scoped numeric custom property definition whose write history should be returned."),
+ )
+ kind: Literal["custom_property_history"] = "custom_property_history"
+ windowDays: WindowDays = Field(
+ ...,
+ description=("Number of days of history to return. The current value is included even when it is older."),
+ )
+
+
+class AccountsTableCustomPropertyHistoryPoint(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ timestamp: AwareDatetime
+ value: float
+
+
+class AccountsTableNoteCountColumn(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ kind: Literal["note_count"] = "note_count"
+
+
+class AccountsTableRelationshipColumn(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ definitionId: str = Field(
+ ...,
+ description="Team-scoped relationship definition to return for each account.",
+ )
+ kind: Literal["relationship"] = "relationship"
+
+
+class AccountsTableTagsColumn(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ kind: Literal["tags"] = "tags"
+
+
class AlertScheduleRestrictionWindow(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -2976,6 +3045,39 @@ class AccountCustomPropertyFilter(BaseModel):
value: list[str | float | bool] | str | float | bool | None = None
+class AccountsTableRow(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ accountFields: dict[str, str | None] = Field(
+ ...,
+ description=("Requested direct Account fields, keyed by their typed field reference."),
+ )
+ customProperties: dict[str, str | float | bool | None] = Field(
+ ...,
+ description="Current values keyed by requested custom property definition ID.",
+ )
+ customPropertyHistory: dict[str, list[AccountsTableCustomPropertyHistoryPoint]] = Field(
+ ...,
+ description=("Numeric write history keyed by requested custom property definition ID."),
+ )
+ externalId: str | None = None
+ id: str
+ name: str
+ noteCount: int | None = Field(
+ default=None,
+ description=("Number of linked internal notes. Omitted when the request does not select the note count."),
+ )
+ relationships: dict[str, list[int]] = Field(
+ ...,
+ description=("Active assignee user IDs keyed by requested relationship definition ID."),
+ )
+ tags: list[str] | None = Field(
+ default=None,
+ description="Sorted tag names. Omitted when the request does not select tags.",
+ )
+
+
class ActionConversionGoal(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -8496,6 +8598,57 @@ class AccountsQueryResponse(BaseModel):
)
+class AccountsTableQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hasMore: bool
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"
+ limit: int
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ offset: int
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[AccountsTableRow]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class ActorsPropertyTaxonomyQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -10182,6 +10335,68 @@ class CachedAccountsQueryResponse(BaseModel):
)
+class CachedAccountsTableQueryResponse(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ cache_key: str
+ cache_target_age: AwareDatetime | None = None
+ calculation_trigger: str | None = Field(
+ default=None,
+ description=("What triggered the calculation of the query, leave empty if user/immediate"),
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hasMore: bool
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ is_cached: bool
+ kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"
+ last_refresh: AwareDatetime
+ limit: int
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ next_allowed_client_refresh: AwareDatetime
+ offset: int
+ query_metadata: dict[str, Any] | None = None
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[AccountsTableRow]
+ timezone: str
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
class CachedActorsPropertyTaxonomyQueryResponse(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -21977,8 +22192,12 @@ class QueryResponseAlternative87(BaseModel):
"Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
),
)
+ hasMore: bool
hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"
+ limit: int
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ offset: int
query_status: QueryStatus | None = Field(
default=None,
description=("Query status indicates whether next to the provided data, a query is still running."),
@@ -21990,7 +22209,7 @@ class QueryResponseAlternative87(BaseModel):
resolved_date_range: ResolvedDateRangeResponse | None = Field(
default=None, description="The date range used for the query"
)
- results: list[EndpointsUsageOverviewItem]
+ results: list[AccountsTableRow]
timings: list[QueryTiming] | None = Field(
default=None,
description=("Measured timings for different parts of the query generation process"),
@@ -22015,6 +22234,53 @@ class QueryResponseAlternative87(BaseModel):
class QueryResponseAlternative88(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ error: str | None = Field(
+ default=None,
+ description=(
+ "Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise."
+ ),
+ )
+ hogql: str | None = Field(default=None, description="Generated HogQL query.")
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ query_status: QueryStatus | None = Field(
+ default=None,
+ description=("Query status indicates whether next to the provided data, a query is still running."),
+ )
+ resolved_compare_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None,
+ description=("The resolved previous/comparison period date range, when comparing against another period"),
+ )
+ resolved_date_range: ResolvedDateRangeResponse | None = Field(
+ default=None, description="The date range used for the query"
+ )
+ results: list[EndpointsUsageOverviewItem]
+ timings: list[QueryTiming] | None = Field(
+ default=None,
+ description=("Measured timings for different parts of the query generation process"),
+ )
+ used_data_warehouse_sources: list[DataWarehouseSourceUsage] | None = Field(
+ default=None,
+ description=("Connector-synced data warehouse sources referenced by this query, if any."),
+ )
+ warnings: list[DataWarehouseSyncWarning | AccessControlFilterWarning] | None = Field(
+ default=None,
+ description=(
+ "Warnings about data warehouse sources referenced by the query whose"
+ " latest sync failed, is paused, hit a billing limit, or is otherwise"
+ " stale. Results may not reflect current source data. Accumulated"
+ " across every HogQL execution that contributes to this response — so"
+ " insights backed by warehouse tables (Trends, Funnels, etc.) receive"
+ " the same warnings as raw HogQL queries. Also carries access control"
+ " warnings when a system-table query filters out objects the user can't"
+ " access."
+ ),
+ )
+
+
+class QueryResponseAlternative89(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22066,7 +22332,7 @@ class QueryResponseAlternative88(BaseModel):
)
-class QueryResponseAlternative89(BaseModel):
+class QueryResponseAlternative90(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22113,7 +22379,7 @@ class QueryResponseAlternative89(BaseModel):
)
-class QueryResponseAlternative90(BaseModel):
+class QueryResponseAlternative91(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22160,7 +22426,7 @@ class QueryResponseAlternative90(BaseModel):
)
-class QueryResponseAlternative91(BaseModel):
+class QueryResponseAlternative92(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22207,7 +22473,7 @@ class QueryResponseAlternative91(BaseModel):
)
-class QueryResponseAlternative92(BaseModel):
+class QueryResponseAlternative93(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22254,7 +22520,7 @@ class QueryResponseAlternative92(BaseModel):
)
-class QueryResponseAlternative93(BaseModel):
+class QueryResponseAlternative94(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22301,7 +22567,7 @@ class QueryResponseAlternative93(BaseModel):
)
-class QueryResponseAlternative94(BaseModel):
+class QueryResponseAlternative95(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22348,7 +22614,7 @@ class QueryResponseAlternative94(BaseModel):
)
-class QueryResponseAlternative95(BaseModel):
+class QueryResponseAlternative96(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22395,7 +22661,7 @@ class QueryResponseAlternative95(BaseModel):
)
-class QueryResponseAlternative96(BaseModel):
+class QueryResponseAlternative97(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22445,7 +22711,7 @@ class QueryResponseAlternative96(BaseModel):
)
-class QueryResponseAlternative97(BaseModel):
+class QueryResponseAlternative98(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22492,7 +22758,7 @@ class QueryResponseAlternative97(BaseModel):
)
-class QueryResponseAlternative98(BaseModel):
+class QueryResponseAlternative99(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22539,7 +22805,7 @@ class QueryResponseAlternative98(BaseModel):
)
-class QueryResponseAlternative99(BaseModel):
+class QueryResponseAlternative100(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22586,7 +22852,7 @@ class QueryResponseAlternative99(BaseModel):
)
-class QueryResponseAlternative100(BaseModel):
+class QueryResponseAlternative101(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22633,7 +22899,7 @@ class QueryResponseAlternative100(BaseModel):
)
-class QueryResponseAlternative101(BaseModel):
+class QueryResponseAlternative102(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22680,7 +22946,7 @@ class QueryResponseAlternative101(BaseModel):
)
-class QueryResponseAlternative102(BaseModel):
+class QueryResponseAlternative103(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22727,7 +22993,7 @@ class QueryResponseAlternative102(BaseModel):
)
-class QueryResponseAlternative103(BaseModel):
+class QueryResponseAlternative104(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22774,7 +23040,7 @@ class QueryResponseAlternative103(BaseModel):
)
-class QueryResponseAlternative104(BaseModel):
+class QueryResponseAlternative105(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -22821,7 +23087,7 @@ class QueryResponseAlternative104(BaseModel):
)
-class QueryResponseAlternative105(BaseModel):
+class QueryResponseAlternative106(BaseModel):
model_config = ConfigDict(
extra="forbid",
)
@@ -23870,6 +24136,33 @@ class AccountsQuery(BaseModel):
version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+class AccountsTableQuery(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ columns: list[
+ Annotated[
+ AccountsTableAccountFieldColumn
+ | AccountsTableTagsColumn
+ | AccountsTableNoteCountColumn
+ | AccountsTableRelationshipColumn
+ | AccountsTableCustomPropertyColumn
+ | AccountsTableCustomPropertyHistoryColumn,
+ Field(discriminator="kind"),
+ ]
+ ] = Field(
+ ...,
+ description=("Columns to load for each account. Account identity fields are always returned."),
+ )
+ kind: Literal["AccountsTableQuery"] = "AccountsTableQuery"
+ limit: conint(ge=1) | None = None
+ modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
+ offset: int | None = None
+ response: AccountsTableQueryResponse | None = None
+ tags: QueryLogTags | None = None
+ version: float | None = Field(default=None, description="version of the node, used for schema migrations")
+
+
class ActionsNode(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -27847,6 +28140,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative103
| QueryResponseAlternative104
| QueryResponseAlternative105
+ | QueryResponseAlternative106
]
):
root: (
@@ -27952,6 +28246,7 @@ class QueryResponseAlternative(
| QueryResponseAlternative103
| QueryResponseAlternative104
| QueryResponseAlternative105
+ | QueryResponseAlternative106
)
@@ -28902,6 +29197,7 @@ class HogQLAutocomplete(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29013,6 +29309,7 @@ class HogQLMetadata(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29152,6 +29449,7 @@ class MaxInsightContext(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29287,6 +29585,7 @@ class QueryRequest(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29414,6 +29713,7 @@ class QuerySchemaRoot(
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29511,6 +29811,7 @@ class QuerySchemaRoot(
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29613,6 +29914,7 @@ class QueryUpgradeRequest(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29715,6 +30017,7 @@ class QueryUpgradeResponse(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
@@ -29999,6 +30302,7 @@ class VisualizationArtifactContent(BaseModel):
| VectorSearchQuery
| UsageMetricsQuery
| AccountsQuery
+ | AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index b342e6436250..98aacab3388f 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -30,6 +30,25 @@ class AccessControlLevel(StrEnum):
MANAGER = "manager"
+class AccountsTableAccountField(StrEnum):
+ NAME = "name"
+ EXTERNAL_ID = "external_id"
+ CREATED_AT = "created_at"
+ UPDATED_AT = "updated_at"
+ STRIPE_CUSTOMER_ID = "stripe_customer_id"
+ HUBSPOT_DEAL_ID = "hubspot_deal_id"
+ BILLING_ID = "billing_id"
+ SFDC_ID = "sfdc_id"
+ ZENDESK_ID = "zendesk_id"
+
+
+class WindowDays(float, Enum):
+ NUMBER_7 = 7
+ NUMBER_14 = 14
+ NUMBER_30 = 30
+ NUMBER_90 = 90
+
+
class MathGroupTypeIndex(float, Enum):
NUMBER_0 = 0
NUMBER_1 = 1
@@ -3282,6 +3301,7 @@ class NodeKind(StrEnum):
DOCUMENT_SIMILARITY_QUERY = "DocumentSimilarityQuery"
USAGE_METRICS_QUERY = "UsageMetricsQuery"
ACCOUNTS_QUERY = "AccountsQuery"
+ ACCOUNTS_TABLE_QUERY = "AccountsTableQuery"
ENDPOINTS_USAGE_OVERVIEW_QUERY = "EndpointsUsageOverviewQuery"
ENDPOINTS_USAGE_TABLE_QUERY = "EndpointsUsageTableQuery"
ENDPOINTS_USAGE_TRENDS_QUERY = "EndpointsUsageTrendsQuery"
diff --git a/products/ai_observability/frontend/e2e/multimodal-trace.spec.ts b/products/ai_observability/frontend/e2e/multimodal-trace.spec.ts
index f05380e921d3..bcf6e820ac6a 100644
--- a/products/ai_observability/frontend/e2e/multimodal-trace.spec.ts
+++ b/products/ai_observability/frontend/e2e/multimodal-trace.spec.ts
@@ -16,6 +16,11 @@ const SCREENSHOT_BYTES = fs.readFileSync(path.join(FIXTURE_DIR, 'screenshot.png'
const POINTER_RE = /phaiblob:\/\/v1\/sha256\/(?<hash>[0-9a-f]{64})\?mime=(?<mime>[^&]+)&size=(?<size>\d+)/
test.describe('AI observability multimodal trace', () => {
+ test.skip(
+ true,
+ 'Flaky: blob offloading can exceed the CI polling window. Follow-up: https://github.com/PostHog/posthog/issues/80843'
+ )
+
test('a screenshot sent through ingestion renders in the trace view', async ({
page,
request,
diff --git a/products/customer_analytics/backend/facade/api.py b/products/customer_analytics/backend/facade/api.py
index 1b0bbc858e26..756fa66fc91d 100644
--- a/products/customer_analytics/backend/facade/api.py
+++ b/products/customer_analytics/backend/facade/api.py
@@ -26,7 +26,7 @@ from django.apps import apps
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import IntegrityError, transaction
-from django.db.models import CharField, Exists, OuterRef, Prefetch, Q
+from django.db.models import CharField, Count, Exists, OuterRef, Prefetch, Q
from django.utils import timezone
import structlog
@@ -91,6 +91,7 @@ from products.customer_analytics.backend.models import (
CustomPropertyDefinition,
CustomPropertySource,
CustomPropertySyncRun,
+ CustomPropertyValue,
DisplayType,
EventStream,
EventStreamMember,
@@ -103,15 +104,20 @@ from products.customer_analytics.backend.models.account import (
RETIRED_ROLE_KEYS,
AccountProperties as _ModelAccountProperties,
)
+from products.customer_analytics.backend.models.custom_property_definition import (
+ DATA_TYPE_BY_DISPLAY_TYPE,
+ NUMERIC_DISPLAY_TYPES,
+ DataType,
+)
from products.customer_analytics.backend.tasks.tasks import send_announcement
from products.notebooks.backend.facade import (
api as notebooks,
contracts as notebook_contracts,
)
-# ResourceNotebook stays a direct import for the account-list Prefetch only — prefetching the
-# account -> ResourceNotebook -> notebook relation can't cross a data facade. All account-notebook
-# CRUD goes through `notebooks` (the facade). Tracked by the notebooks legacy-leak interface block.
+# ResourceNotebook stays a direct import for account-list reads because the account relation cannot
+# cross a data facade. All account-notebook CRUD goes through `notebooks` (the facade). Tracked by
+# the notebooks legacy-leak interface block.
from products.notebooks.backend.models import ResourceNotebook
from products.workflows.backend.services.template_input_usage import get_hog_flows_referencing_template_input_keys
@@ -365,14 +371,27 @@ def _to_external_account(account: Account) -> contracts.ExternalAccount:
)
+def _json_safe_scalar(value: Any) -> float | bool | str | None:
+ if isinstance(value, datetime):
+ return value.isoformat()
+ if isinstance(value, float | bool | str):
+ return value
+ return None
+
+
def _scalar_value(row: "CustomPropertyValue") -> float | bool | str | None:
"""Return the row's value as a JSON-safe scalar; datetimes become ISO strings."""
- v = _custom_property_values_logic.value_of(row)
- if isinstance(v, datetime):
- return v.isoformat()
- if isinstance(v, float | bool | str):
- return v
- return None
+ return _json_safe_scalar(_custom_property_values_logic.value_of(row))
+
+
+def _scalar_value_for_display_type(row: "CustomPropertyValue", display_type: DisplayType) -> float | bool | str | None:
+ value_column = {
+ DataType.STRING: "value_str",
+ DataType.NUMERIC: "value_num",
+ DataType.BOOLEAN: "value_bool",
+ DataType.DATETIME: "value_datetime",
+ }[DATA_TYPE_BY_DISPLAY_TYPE[display_type]]
+ return _json_safe_scalar(getattr(row, value_column))
def _get_external_account_by_external_id(team_id: int, external_id: str) -> Account | None:
@@ -2062,6 +2081,200 @@ def _to_account_view(account: Account) -> contracts.AccountView:
)
+class InvalidAccountTableColumn(ValueError):
+ pass
+
+
+ACCOUNT_TABLE_MAX_HISTORY_POINTS = 50_000
+
+
+def _account_table_field_values(
+ account: Account, fields: frozenset[contracts.AccountTableField]
+) -> dict[contracts.AccountTableField, str | None]:
+ properties = account.properties
+ values: dict[contracts.AccountTableField, str | None] = {}
+ for field in sorted(fields, key=lambda account_field: account_field.value):
+ match field:
+ case contracts.AccountTableField.NAME:
+ values[field] = account.name
+ case contracts.AccountTableField.EXTERNAL_ID:
+ values[field] = account.external_id
+ case contracts.AccountTableField.CREATED_AT:
+ values[field] = account.created_at.isoformat() if account.created_at else None
+ case contracts.AccountTableField.UPDATED_AT:
+ values[field] = account.updated_at.isoformat() if account.updated_at else None
+ case contracts.AccountTableField.STRIPE_CUSTOMER_ID:
+ values[field] = properties.stripe_customer_id
+ case contracts.AccountTableField.HUBSPOT_DEAL_ID:
+ values[field] = properties.hubspot_deal_id
+ case contracts.AccountTableField.BILLING_ID:
+ values[field] = properties.billing_id
+ case contracts.AccountTableField.SFDC_ID:
+ values[field] = properties.sfdc_id
+ case contracts.AccountTableField.ZENDESK_ID:
+ values[field] = properties.zendesk_id
+ case _:
+ raise ValueError(f"Unsupported account table field: {field}")
+ return values
+
+
+def _validate_account_table_definitions(
+ *, team_id: int, selection: contracts.AccountTableColumnSelection
+) -> dict[UUID, DisplayType]:
+ relationship_ids = selection.relationship_definition_ids
+ if relationship_ids:
+ valid_relationship_ids = set(
+ AccountRelationshipDefinition.objects.for_team(team_id)
+ .filter(id__in=relationship_ids)
+ .values_list("id", flat=True)
+ )
+ invalid_relationship_ids = relationship_ids - valid_relationship_ids
+ if invalid_relationship_ids:
+ invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in invalid_relationship_ids))
+ raise InvalidAccountTableColumn(f"Unknown relationship definitions: {invalid_ids}")
+
+ custom_property_ids = selection.custom_property_definition_ids | frozenset(
+ selection.custom_property_history_windows
+ )
+ if not custom_property_ids:
+ return {}
+
+ custom_property_display_types = {
+ definition_id: DisplayType(display_type)
+ for definition_id, display_type in CustomPropertyDefinition.objects.for_team(team_id)
+ .filter(id__in=custom_property_ids, target_type=TargetType.ACCOUNT)
+ .values_list("id", "display_type")
+ }
+ invalid_custom_property_ids = custom_property_ids - set(custom_property_display_types)
+ if invalid_custom_property_ids:
+ invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in invalid_custom_property_ids))
+ raise InvalidAccountTableColumn(f"Unknown account custom property definitions: {invalid_ids}")
+
+ non_numeric_history_ids = {
+ definition_id
+ for definition_id in selection.custom_property_history_windows
+ if custom_property_display_types[definition_id] not in NUMERIC_DISPLAY_TYPES
+ }
+ if non_numeric_history_ids:
+ invalid_ids = ", ".join(sorted(str(definition_id) for definition_id in non_numeric_history_ids))
+ raise InvalidAccountTableColumn(f"Custom property history requires numeric definitions: {invalid_ids}")
+ return custom_property_display_types
+
+
+def query_accounts_table(
+ *,
+ team_id: int,
+ user_access_control: "UserAccessControl",
+ selection: contracts.AccountTableColumnSelection,
+ offset: int,
+ limit: int,
+) -> contracts.AccountTablePage:
+ custom_property_display_types = _validate_account_table_definitions(team_id=team_id, selection=selection)
+
+ queryset = _accounts_queryset(team_id, user_access_control).order_by("-created_at", "-id")
+ fetched_accounts = list(queryset[offset : offset + limit + 1])
+ has_more = len(fetched_accounts) > limit
+ accounts = fetched_accounts[:limit]
+ account_ids = [account.id for account in accounts]
+
+ tags_by_account: dict[UUID, list[str]] = {account_id: [] for account_id in account_ids}
+ if selection.include_tags:
+ for account_id, tag_name in (
+ TaggedItem.objects.filter(account_id__in=account_ids)
+ .order_by("tag__name")
+ .values_list("account_id", "tag__name")
+ ):
+ tags_by_account[account_id].append(tag_name)
+
+ note_counts_by_account: dict[UUID, int] = dict.fromkeys(account_ids, 0)
+ if selection.include_note_count:
+ for result in (
+ ResourceNotebook.objects.filter(account_id__in=account_ids).values("account_id").annotate(count=Count("id"))
+ ):
+ note_counts_by_account[result["account_id"]] = result["count"]
+
+ relationship_ids = selection.relationship_definition_ids
+ sorted_relationship_ids = sorted(relationship_ids, key=lambda definition_id: definition_id.hex)
+ relationships_by_account: dict[UUID, dict[UUID, list[int]]] = {
+ account_id: {definition_id: [] for definition_id in sorted_relationship_ids} for account_id in account_ids
+ }
+ if relationship_ids:
+ for account_id, definition_id, user_id in (
+ AccountRelationship.objects.for_team(team_id)
+ .filter(
+ account_id__in=account_ids,
+ definition_id__in=relationship_ids,
+ ended_at__isnull=True,
+ user_id__isnull=False,
+ )
+ .order_by("user_id")
+ .values_list("account_id", "definition_id", "user_id")
+ ):
+ relationships_by_account[account_id][definition_id].append(user_id)
+
+ custom_property_ids = selection.custom_property_definition_ids
+ sorted_custom_property_ids = sorted(custom_property_ids, key=lambda definition_id: definition_id.hex)
+ custom_properties_by_account: dict[UUID, dict[UUID, float | bool | str | None]] = {
+ account_id: dict.fromkeys(sorted_custom_property_ids) for account_id in account_ids
+ }
+ if custom_property_ids:
+ for value in CustomPropertyValue.objects.for_team(team_id).filter(
+ account_id__in=account_ids,
+ definition_id__in=custom_property_ids,
+ is_deleted=False,
+ ):
+ custom_properties_by_account[value.account_id][value.definition_id] = _scalar_value_for_display_type(
+ value, custom_property_display_types[value.definition_id]
+ )
+
+ history_windows = selection.custom_property_history_windows
+ custom_property_history_by_account: dict[
+ UUID, dict[UUID, list[contracts.AccountTableCustomPropertyHistoryPoint]]
+ ] = {account_id: {definition_id: [] for definition_id in history_windows} for account_id in account_ids}
+ if history_windows:
+ now = timezone.now()
+ history_filter = Q()
+ for definition_id, window_days in history_windows.items():
+ history_filter |= Q(definition_id=definition_id, created_at__gte=now - timedelta(days=window_days))
+ history_filter |= Q(definition_id=definition_id, is_deleted=False)
+ history_point_count = 0
+ history_values = (
+ CustomPropertyValue.objects.for_team(team_id)
+ .filter(history_filter, account_id__in=account_ids, value_num__isnull=False)
+ .order_by("created_at", "id")
+ .iterator(chunk_size=2_000)
+ )
+ for value in history_values:
+ history_point_count += 1
+ if history_point_count > ACCOUNT_TABLE_MAX_HISTORY_POINTS:
+ raise InvalidAccountTableColumn(
+ f"Account table queries support up to {ACCOUNT_TABLE_MAX_HISTORY_POINTS} history points."
+ )
+ assert value.value_num is not None
+ custom_property_history_by_account[value.account_id][value.definition_id].append(
+ contracts.AccountTableCustomPropertyHistoryPoint(
+ timestamp=value.created_at,
+ value=value.value_num,
+ )
+ )
+
+ rows = [
+ contracts.AccountTableRow(
+ id=account.id,
+ name=account.name,
+ external_id=account.external_id,
+ account_fields=_account_table_field_values(account, selection.account_fields),
+ tags=tags_by_account[account.id] if selection.include_tags else None,
+ note_count=note_counts_by_account[account.id] if selection.include_note_count else None,
+ relationships=relationships_by_account[account.id],
+ custom_properties=custom_properties_by_account[account.id],
+ custom_property_history=custom_property_history_by_account[account.id],
+ )
+ for account in accounts
+ ]
+ return contracts.AccountTablePage(rows=rows, has_more=has_more, limit=limit, offset=offset)
+
+
def list_accounts_for_view(
*,
team_id: int,
diff --git a/products/customer_analytics/backend/facade/contracts.py b/products/customer_analytics/backend/facade/contracts.py
index 53a3a9237207..2e8722666be1 100644
--- a/products/customer_analytics/backend/facade/contracts.py
+++ b/products/customer_analytics/backend/facade/contracts.py
@@ -179,6 +179,55 @@ class AccountRef:
external_id: str | None
+class AccountTableField(str, Enum):
+ NAME = "name"
+ EXTERNAL_ID = "external_id"
+ CREATED_AT = "created_at"
+ UPDATED_AT = "updated_at"
+ STRIPE_CUSTOMER_ID = "stripe_customer_id"
+ HUBSPOT_DEAL_ID = "hubspot_deal_id"
+ BILLING_ID = "billing_id"
+ SFDC_ID = "sfdc_id"
+ ZENDESK_ID = "zendesk_id"
+
+
+@dataclass(frozen=True, kw_only=True)
+class AccountTableColumnSelection:
+ account_fields: frozenset[AccountTableField] = frozenset()
+ include_tags: bool = False
+ include_note_count: bool = False
+ relationship_definition_ids: frozenset[UUID] = frozenset()
+ custom_property_definition_ids: frozenset[UUID] = frozenset()
+ custom_property_history_windows: dict[UUID, int] = field(default_factory=dict)
+
+
+@dataclass(frozen=True, kw_only=True)
+class AccountTableCustomPropertyHistoryPoint:
+ timestamp: datetime
+ value: float
+
+
+@dataclass(frozen=True, kw_only=True)
+class AccountTableRow:
+ id: UUID
+ name: str
+ external_id: str | None
+ account_fields: dict[AccountTableField, str | None] = field(default_factory=dict)
+ tags: list[str] | None = None
+ note_count: int | None = None
+ relationships: dict[UUID, list[int]] = field(default_factory=dict)
+ custom_properties: dict[UUID, float | bool | str | None] = field(default_factory=dict)
+ custom_property_history: dict[UUID, list[AccountTableCustomPropertyHistoryPoint]] = field(default_factory=dict)
+
+
+@dataclass(frozen=True, kw_only=True)
+class AccountTablePage:
+ rows: list[AccountTableRow]
+ has_more: bool
+ limit: int
+ offset: int
+
+
@dataclass(frozen=True)
class AccountNote:
"""An internal note (notebook) attached to an account."""
diff --git a/products/customer_analytics/backend/facade/queries.py b/products/customer_analytics/backend/facade/queries.py
index 47c2c70b63af..92d3f3070c3c 100644
--- a/products/customer_analytics/backend/facade/queries.py
+++ b/products/customer_analytics/backend/facade/queries.py
@@ -1,16 +1,18 @@
-"""Facade re-exports for customer_analytics HogQL query runners.
+"""Facade re-exports for customer_analytics query runners.
Core's query-runner registry (``posthog/hogql_queries/query_runner.py``) dispatches
on query ``kind`` and constructs these runners by class identity. Re-exporting the
-classes keeps that registry coupling at the facade boundary while the heavy HogQL
+classes keeps that registry coupling at the facade boundary while query implementation
imports stay out of ``facade/api.py`` so config-only consumers don't drag them onto
the ``django.setup()`` path.
"""
from products.customer_analytics.backend.hogql_queries.accounts_query_runner import AccountsQueryRunner
+from products.customer_analytics.backend.hogql_queries.accounts_table_query_runner import AccountsTableQueryRunner
from products.customer_analytics.backend.hogql_queries.usage_metrics_query_runner import UsageMetricsQueryRunner
__all__ = [
"AccountsQueryRunner",
+ "AccountsTableQueryRunner",
"UsageMetricsQueryRunner",
]
diff --git a/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
new file mode 100644
index 000000000000..7e13b151493c
--- /dev/null
+++ b/products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py
@@ -0,0 +1,135 @@
+from typing import NoReturn
+from uuid import UUID
+
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ AccountsTableAccountFieldColumn,
+ AccountsTableCustomPropertyColumn,
+ AccountsTableCustomPropertyHistoryColumn,
+ AccountsTableCustomPropertyHistoryPoint,
+ AccountsTableNoteCountColumn,
+ AccountsTableQuery,
+ AccountsTableQueryResponse,
+ AccountsTableRelationshipColumn,
+ AccountsTableRow,
+ AccountsTableTagsColumn,
+ CachedAccountsTableQueryResponse,
+)
+
+from posthog.hogql.constants import get_default_limit_for_context, get_max_limit_for_context
+
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner
+from posthog.models import User
+from posthog.rbac.user_access_control import UserAccessControl, UserAccessControlError
+
+from products.customer_analytics.backend.facade import api, contracts
+
+ACCOUNTS_TABLE_MAX_COLUMNS = 100
+ACCOUNTS_TABLE_MAX_PAGE_SIZE = 500
+
+
+class AccountsTableQueryRunner(AnalyticsQueryRunner[AccountsTableQueryResponse]):
+ query: AccountsTableQuery
+ cached_response: CachedAccountsTableQueryResponse
+
+ def validate_query_runner_access(self, user: User) -> bool:
+ return UserAccessControl(user=user, team=self.team).assert_access_level_for_resource("account", "viewer")
+
+ def to_query(self) -> NoReturn:
+ raise NotImplementedError("AccountsTableQueryRunner executes against Postgres")
+
+ def _column_selection(self) -> contracts.AccountTableColumnSelection:
+ if len(self.query.columns) > ACCOUNTS_TABLE_MAX_COLUMNS:
+ raise ValidationError(f"Account table queries support up to {ACCOUNTS_TABLE_MAX_COLUMNS} columns.")
+
+ account_fields: set[contracts.AccountTableField] = set()
+ include_tags = False
+ include_note_count = False
+ relationship_definition_ids: set[UUID] = set()
+ custom_property_definition_ids: set[UUID] = set()
+ custom_property_history_windows: dict[UUID, int] = {}
+
+ try:
+ for column in self.query.columns:
+ if isinstance(column, AccountsTableAccountFieldColumn):
+ account_fields.add(contracts.AccountTableField(column.field.value))
+ elif isinstance(column, AccountsTableTagsColumn):
+ include_tags = True
+ elif isinstance(column, AccountsTableNoteCountColumn):
+ include_note_count = True
+ elif isinstance(column, AccountsTableRelationshipColumn):
+ relationship_definition_ids.add(UUID(column.definitionId))
+ elif isinstance(column, AccountsTableCustomPropertyColumn):
+ custom_property_definition_ids.add(UUID(column.definitionId))
+ elif isinstance(column, AccountsTableCustomPropertyHistoryColumn):
+ definition_id = UUID(column.definitionId)
+ window_days = int(column.windowDays.value)
+ custom_property_history_windows[definition_id] = max(
+ window_days,
+ custom_property_history_windows.get(definition_id, 0),
+ )
+ except ValueError as error:
+ raise ValidationError("Account table definition IDs must be valid UUIDs.") from error
+
+ return contracts.AccountTableColumnSelection(
+ account_fields=frozenset(account_fields),
+ include_tags=include_tags,
+ include_note_count=include_note_count,
+ relationship_definition_ids=frozenset(relationship_definition_ids),
+ custom_property_definition_ids=frozenset(custom_property_definition_ids),
+ custom_property_history_windows=custom_property_history_windows,
+ )
+
+ def _calculate(self) -> AccountsTableQueryResponse:
+ user_access_control = self.user_access_control
+ if user_access_control is None:
+ raise UserAccessControlError("account", "viewer")
+
+ limit = min(
+ self.query.limit or get_default_limit_for_context(self.limit_context),
+ get_max_limit_for_context(self.limit_context),
+ ACCOUNTS_TABLE_MAX_PAGE_SIZE,
+ )
+ offset = max(self.query.offset or 0, 0)
+
+ try:
+ page = api.query_accounts_table(
+ team_id=self.team.id,
+ user_access_control=user_access_control,
+ selection=self._column_selection(),
+ offset=offset,
+ limit=limit,
+ )
+ except api.InvalidAccountTableColumn as error:
+ raise ValidationError(str(error)) from error
+
+ return AccountsTableQueryResponse(
+ results=[
+ AccountsTableRow(
+ id=str(row.id),
+ name=row.name,
+ externalId=row.external_id,
+ accountFields={field.value: value for field, value in row.account_fields.items()},
+ tags=row.tags,
+ noteCount=row.note_count,
+ relationships={
+ str(definition_id): user_ids for definition_id, user_ids in row.relationships.items()
+ },
+ customProperties={
+ str(definition_id): value for definition_id, value in row.custom_properties.items()
+ },
+ customPropertyHistory={
+ str(definition_id): [
+ AccountsTableCustomPropertyHistoryPoint(timestamp=point.timestamp, value=point.value)
+ for point in points
+ ]
+ for definition_id, points in row.custom_property_history.items()
+ },
+ )
+ for row in page.rows
+ ],
+ hasMore=page.has_more,
+ limit=page.limit,
+ offset=page.offset,
+ )
diff --git a/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
new file mode 100644
index 000000000000..8b8d79322231
--- /dev/null
+++ b/products/customer_analytics/backend/hogql_queries/test/test_accounts_table_query_runner.py
@@ -0,0 +1,331 @@
+from datetime import timedelta
+
+import pytest
+from freezegun import freeze_time
+from posthog.test.base import APIBaseTest, BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from parameterized import parameterized
+from rest_framework import status
+from rest_framework.exceptions import ValidationError
+
+from posthog.schema import (
+ AccountsTableAccountField,
+ AccountsTableAccountFieldColumn,
+ AccountsTableCustomPropertyColumn,
+ AccountsTableCustomPropertyHistoryColumn,
+ AccountsTableNoteCountColumn,
+ AccountsTableQuery,
+ AccountsTableQueryResponse,
+ AccountsTableRelationshipColumn,
+ AccountsTableTagsColumn,
+)
+
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership, Tag, Team
+from posthog.models.personal_api_key import PersonalAPIKey
+from posthog.models.utils import generate_random_token_personal, hash_key_value
+from posthog.rbac.user_access_control import UserAccessControl
+
+from products.customer_analytics.backend.facade import api, contracts
+from products.customer_analytics.backend.hogql_queries.accounts_table_query_runner import (
+ ACCOUNTS_TABLE_MAX_COLUMNS,
+ ACCOUNTS_TABLE_MAX_PAGE_SIZE,
+ AccountsTableQueryRunner,
+)
+from products.customer_analytics.backend.models import (
+ AccountRelationship,
+ AccountRelationshipDefinition,
+ CustomPropertyValue,
+ DisplayType,
+)
+from products.customer_analytics.backend.test.factories import create_account, create_custom_property_definition
+from products.notebooks.backend.models import Notebook, ResourceNotebook
+
+try:
+ from ee.models.rbac.access_control import AccessControl
+except ImportError:
+ pass
+
+
+@freeze_time("2026-01-15T12:00:00Z")
+class TestAccountsTableQueryRunner(BaseTest):
+ def _run(self, query: AccountsTableQuery) -> AccountsTableQueryResponse:
+ return AccountsTableQueryRunner(query=query, team=self.team, user=self.user).calculate()
+
+ def test_returns_requested_postgres_cells_with_typed_defaults(self) -> None:
+ empty_account = create_account(team_id=self.team.id, name="Empty")
+ account = create_account(
+ team_id=self.team.id,
+ name="Acme",
+ external_id="acme-1",
+ _properties={"stripe_customer_id": "cus_123"},
+ )
+
+ for tag_name in ["priority", "enterprise"]:
+ account.tagged_items.create(tag=Tag.objects.create(team=self.team, name=tag_name))
+
+ notebook = Notebook.objects.create(team=self.team, created_by=self.user)
+ ResourceNotebook.objects.create(account=account, notebook=notebook)
+
+ relationship_definition = AccountRelationshipDefinition.objects.unscoped().create(
+ team=self.team,
+ name="CSM",
+ )
+ AccountRelationship.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ definition=relationship_definition,
+ user=self.user,
+ )
+
+ numeric_definition = create_custom_property_definition(
+ team_id=self.team.id,
+ name="MRR",
+ display_type=DisplayType.CURRENCY,
+ )
+ text_definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+ old_value = CustomPropertyValue.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ definition=numeric_definition,
+ value_num=10,
+ is_deleted=True,
+ )
+ current_value = CustomPropertyValue.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ definition=numeric_definition,
+ value_num=20,
+ )
+ CustomPropertyValue.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ definition=text_definition,
+ value_str="enterprise",
+ )
+ now = timezone.now()
+ CustomPropertyValue.objects.unscoped().filter(id=old_value.id).update(created_at=now - timedelta(days=5))
+ CustomPropertyValue.objects.unscoped().filter(id=current_value.id).update(created_at=now - timedelta(days=1))
+
+ response = self._run(
+ AccountsTableQuery(
+ columns=[
+ AccountsTableAccountFieldColumn(field=AccountsTableAccountField.STRIPE_CUSTOMER_ID),
+ AccountsTableTagsColumn(),
+ AccountsTableNoteCountColumn(),
+ AccountsTableRelationshipColumn(definitionId=str(relationship_definition.id)),
+ AccountsTableCustomPropertyColumn(definitionId=str(numeric_definition.id)),
+ AccountsTableCustomPropertyColumn(definitionId=str(text_definition.id)),
+ AccountsTableCustomPropertyHistoryColumn(
+ definitionId=str(numeric_definition.id),
+ windowDays=30,
+ ),
+ ]
+ )
+ )
+
+ rows = {row.id: row for row in response.results}
+ full_row = rows[str(account.id)]
+ assert full_row.accountFields == {"stripe_customer_id": "cus_123"}
+ assert full_row.tags == ["enterprise", "priority"]
+ assert full_row.noteCount == 1
+ assert full_row.relationships == {str(relationship_definition.id): [self.user.id]}
+ assert full_row.customProperties == {
+ str(numeric_definition.id): 20.0,
+ str(text_definition.id): "enterprise",
+ }
+ assert [point.value for point in full_row.customPropertyHistory[str(numeric_definition.id)]] == [10.0, 20.0]
+
+ empty_row = rows[str(empty_account.id)]
+ assert empty_row.tags == []
+ assert empty_row.noteCount == 0
+ assert empty_row.relationships == {str(relationship_definition.id): []}
+ assert empty_row.customProperties == {
+ str(numeric_definition.id): None,
+ str(text_definition.id): None,
+ }
+ assert empty_row.customPropertyHistory == {str(numeric_definition.id): []}
+
+ def test_hydrates_custom_properties_with_bounded_queries(self) -> None:
+ definition = create_custom_property_definition(
+ team_id=self.team.id,
+ name="Health score",
+ display_type=DisplayType.NUMBER,
+ )
+ accounts = [create_account(team_id=self.team.id, name=f"Account {index}") for index in range(3)]
+ for index, account in enumerate(accounts):
+ CustomPropertyValue.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ definition=definition,
+ value_num=index,
+ )
+
+ with self.assertNumQueries(6):
+ page = api.query_accounts_table(
+ team_id=self.team.id,
+ user_access_control=UserAccessControl(user=self.user, team=self.team),
+ selection=contracts.AccountTableColumnSelection(
+ custom_property_definition_ids=frozenset({definition.id})
+ ),
+ offset=0,
+ limit=100,
+ )
+
+ assert {row.custom_properties[definition.id] for row in page.rows} == {0.0, 1.0, 2.0}
+
+ def test_caps_selected_columns_and_page_size(self) -> None:
+ with self.assertRaises(ValidationError):
+ self._run(AccountsTableQuery(columns=[AccountsTableTagsColumn()] * (ACCOUNTS_TABLE_MAX_COLUMNS + 1)))
+
+ response = self._run(AccountsTableQuery(columns=[], limit=ACCOUNTS_TABLE_MAX_PAGE_SIZE + 1))
+
+ assert response.limit == ACCOUNTS_TABLE_MAX_PAGE_SIZE
+
+ @patch.object(api, "ACCOUNT_TABLE_MAX_HISTORY_POINTS", 1)
+ def test_rejects_history_results_over_the_point_budget(self) -> None:
+ account = create_account(team_id=self.team.id, name="Acme")
+ definition = create_custom_property_definition(
+ team_id=self.team.id,
+ name="Health score",
+ display_type=DisplayType.NUMBER,
+ )
+ for index, value in enumerate([10, 20]):
+ CustomPropertyValue.objects.unscoped().create(
+ team=self.team,
+ account=account,
+ definition=definition,
+ value_num=value,
+ is_deleted=index == 0,
+ )
+
+ with self.assertRaises(ValidationError):
+ self._run(
+ AccountsTableQuery(
+ columns=[AccountsTableCustomPropertyHistoryColumn(definitionId=str(definition.id), windowDays=30)]
+ )
+ )
+
+ def test_applies_stable_limit_and_offset_pagination(self) -> None:
+ accounts = [create_account(team_id=self.team.id, name=name) for name in ["First", "Second", "Third"]]
+
+ response = self._run(AccountsTableQuery(columns=[], limit=1, offset=1))
+ expected_account = sorted(accounts, key=lambda account: (account.created_at, account.id), reverse=True)[1]
+
+ assert [row.id for row in response.results] == [str(expected_account.id)]
+ assert response.hasMore is True
+ assert response.limit == 1
+ assert response.offset == 1
+
+ @parameterized.expand(["relationship", "custom_property"])
+ def test_rejects_definition_from_another_team(self, column_kind: str) -> None:
+ other_team = Team.objects.create(organization=self.organization)
+ column: AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn
+ if column_kind == "relationship":
+ relationship_definition = AccountRelationshipDefinition.objects.unscoped().create(
+ team=other_team, name="Other CSM"
+ )
+ column = AccountsTableRelationshipColumn(definitionId=str(relationship_definition.id))
+ else:
+ custom_property_definition = create_custom_property_definition(team_id=other_team.id, name="Other plan")
+ column = AccountsTableCustomPropertyColumn(definitionId=str(custom_property_definition.id))
+
+ with self.assertRaises(ValidationError):
+ self._run(AccountsTableQuery(columns=[column]))
+
+ def test_rejects_history_for_non_numeric_custom_property(self) -> None:
+ definition = create_custom_property_definition(team_id=self.team.id, name="Plan")
+
+ with self.assertRaises(ValidationError):
+ self._run(
+ AccountsTableQuery(
+ columns=[AccountsTableCustomPropertyHistoryColumn(definitionId=str(definition.id), windowDays=30)]
+ )
+ )
+
+ def test_rejects_malformed_definition_id(self) -> None:
+ with self.assertRaises(ValidationError):
+ self._run(
+ AccountsTableQuery(columns=[AccountsTableCustomPropertyColumn(definitionId="not-a-definition-id")])
+ )
+
+ @pytest.mark.ee
+ def test_object_access_filters_rows_and_partitions_the_cache(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()
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ visible_account = create_account(team_id=self.team.id, name="Visible")
+ denied_account = create_account(team_id=self.team.id, name="Denied")
+ blocking_access = AccessControl.objects.create(
+ team=self.team,
+ resource="account",
+ resource_id=str(denied_account.id),
+ access_level="none",
+ organization_member=self.organization_membership,
+ )
+
+ blocked_runner = AccountsTableQueryRunner(
+ query=AccountsTableQuery(columns=[]),
+ team=self.team,
+ user=self.user,
+ )
+ blocked_cache_key = blocked_runner.get_cache_key()
+ response = blocked_runner.calculate()
+
+ assert [row.id for row in response.results] == [str(visible_account.id)]
+
+ blocking_access.delete()
+ unblocked_cache_key = AccountsTableQueryRunner(
+ query=AccountsTableQuery(columns=[]),
+ team=self.team,
+ user=self.user,
+ ).get_cache_key()
+ assert blocked_cache_key != unblocked_cache_key
+
+
+class TestAccountsTableQueryAPI(APIBaseTest):
+ def _token(self, scopes: list[str]) -> str:
+ value = generate_random_token_personal()
+ PersonalAPIKey.objects.create(
+ label="accounts table query",
+ user=self.user,
+ secure_value=hash_key_value(value),
+ scopes=scopes,
+ scoped_teams=[],
+ scoped_organizations=[],
+ )
+ return value
+
+ def test_query_endpoint_requires_account_scope_and_dispatches(self) -> None:
+ account = create_account(team_id=self.team.id, name="Acme")
+ endpoint = f"/api/projects/{self.team.id}/query/"
+ payload = {
+ "query": AccountsTableQuery(columns=[]).model_dump(),
+ "refresh": "force_blocking",
+ }
+
+ for incomplete_scopes in [["query:read"], ["account:read"]]:
+ denied = self.client.post(
+ endpoint,
+ payload,
+ format="json",
+ headers={"authorization": f"Bearer {self._token(incomplete_scopes)}"},
+ )
+ assert denied.status_code == status.HTTP_403_FORBIDDEN
+
+ allowed = self.client.post(
+ endpoint,
+ payload,
+ format="json",
+ headers={"authorization": f"Bearer {self._token(['query:read', 'account:read'])}"},
+ )
+ assert allowed.status_code == status.HTTP_200_OK, allowed.content
+ assert [row["id"] for row in allowed.json()["results"]] == [str(account.id)]
diff --git a/products/customer_analytics/frontend/components/Accounts/AGENTS.md b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
index 262d49dc6c9c..47a88973f8d9 100644
--- a/products/customer_analytics/frontend/components/Accounts/AGENTS.md
+++ b/products/customer_analytics/frontend/components/Accounts/AGENTS.md
@@ -220,7 +220,8 @@ The tool is registered for the page regardless of agent mode. The Customer analy
### Backend touchpoints
- `products/customer_analytics/backend/models` — the `Account` model (`external_id` = group key).
-- `products/customer_analytics/backend/` — `accounts_query_runner` (builds the list rows + cell tuples).
+- `products/customer_analytics/backend/hogql_queries/accounts_query_runner.py` — the current Accounts page query runner, which builds positional list rows through HogQL.
+- `products/customer_analytics/backend/hogql_queries/accounts_table_query_runner.py` — the typed Postgres-only `AccountsTableQuery` runner. It returns keyed rows for the planned Accounts page migration but is not wired into the page yet.
- `products/customer_analytics/backend/max_tools/` — `OpenAccountTool` and other account Max tools.
- `ee/hogai/core/agent_modes/presets/customer_analytics.py` — the Customer analytics agent mode (gated by the `customer-analytics-csp` flag).
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index e909148b8ba2..2cde45ab97b9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -826,6 +826,149 @@ export namespace Schemas {
version?: number | null;
}
+ export type AccountsTableAccountField = typeof AccountsTableAccountField[keyof typeof AccountsTableAccountField];
+
+
+ export const AccountsTableAccountField = {
+ Name: 'name',
+ ExternalId: 'external_id',
+ CreatedAt: 'created_at',
+ UpdatedAt: 'updated_at',
+ StripeCustomerId: 'stripe_customer_id',
+ HubspotDealId: 'hubspot_deal_id',
+ BillingId: 'billing_id',
+ SfdcId: 'sfdc_id',
+ ZendeskId: 'zendesk_id',
+ } as const;
+
+ export interface AccountsTableAccountFieldColumn {
+ field: AccountsTableAccountField;
+ kind?: 'account_field';
+ }
+
+ export interface AccountsTableCustomPropertyColumn {
+ /** Team-scoped custom property definition to return for each account. */
+ definitionId: string;
+ kind?: 'custom_property';
+ }
+
+ export type WindowDays = typeof WindowDays[keyof typeof WindowDays];
+
+
+ export const WindowDays = {
+ Number7: 7,
+ Number14: 14,
+ Number30: 30,
+ Number90: 90,
+ } as const;
+
+ export interface AccountsTableCustomPropertyHistoryColumn {
+ /** Team-scoped numeric custom property definition whose write history should be returned. */
+ definitionId: string;
+ kind?: 'custom_property_history';
+ /** Number of days of history to return. The current value is included even when it is older. */
+ windowDays: WindowDays;
+ }
+
+ export interface AccountsTableCustomPropertyHistoryPoint {
+ timestamp: string;
+ value: number;
+ }
+
+ export const AccountsTableNoteCountColumnValue = {
+ kind: 'note_count',
+ } as const;
+ export type AccountsTableNoteCountColumn = typeof AccountsTableNoteCountColumnValue;
+
+ export const AccountsTableTagsColumnValue = {
+ kind: 'tags',
+ } as const;
+ export type AccountsTableTagsColumn = typeof AccountsTableTagsColumnValue;
+
+ export interface AccountsTableRelationshipColumn {
+ /** Team-scoped relationship definition to return for each account. */
+ definitionId: string;
+ kind?: 'relationship';
+ }
+
+ /**
+ * Requested direct Account fields, keyed by their typed field reference.
+ */
+ export type AccountsTableRowAccountFields = {[key: string]: string | null};
+
+ /**
+ * Current values keyed by requested custom property definition ID.
+ */
+ export type AccountsTableRowCustomProperties = {[key: string]: string | number | boolean | null};
+
+ /**
+ * Numeric write history keyed by requested custom property definition ID.
+ */
+ export type AccountsTableRowCustomPropertyHistory = {[key: string]: AccountsTableCustomPropertyHistoryPoint[]};
+
+ /**
+ * Active assignee user IDs keyed by requested relationship definition ID.
+ */
+ export type AccountsTableRowRelationships = {[key: string]: number[]};
+
+ export interface AccountsTableRow {
+ /** Requested direct Account fields, keyed by their typed field reference. */
+ accountFields: AccountsTableRowAccountFields;
+ /** Current values keyed by requested custom property definition ID. */
+ customProperties: AccountsTableRowCustomProperties;
+ /** Numeric write history keyed by requested custom property definition ID. */
+ customPropertyHistory: AccountsTableRowCustomPropertyHistory;
+ externalId?: string | null;
+ id: string;
+ name: string;
+ /** Number of linked internal notes. Omitted when the request does not select the note count. */
+ noteCount?: number | null;
+ /** Active assignee user IDs keyed by requested relationship definition ID. */
+ relationships: AccountsTableRowRelationships;
+ /** Sorted tag names. Omitted when the request does not select tags. */
+ tags?: string[] | null;
+ }
+
+ export interface AccountsTableQueryResponse {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ hasMore: boolean;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ kind?: 'AccountsTableQuery';
+ limit: number;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ offset: number;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: AccountsTableRow[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface AccountsTableQuery {
+ /** Columns to load for each account. Account identity fields are always returned. */
+ columns: (AccountsTableAccountFieldColumn | AccountsTableTagsColumn | AccountsTableNoteCountColumn | AccountsTableRelationshipColumn | AccountsTableCustomPropertyColumn | AccountsTableCustomPropertyHistoryColumn)[];
+ kind?: 'AccountsTableQuery';
+ limit?: number | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ offset?: number | null;
+ response?: AccountsTableQueryResponse | null;
+ tags?: QueryLogTags | null;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
/**
* * `user` - user
* * `team` - team
@@ -39462,7 +39605,7 @@ export namespace Schemas {
query: string;
response?: HogQLMetadataResponse | null;
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
tags?: QueryLogTags | null;
/** Variables to be subsituted into the query */
variables?: HogQLMetadataVariables;
@@ -39488,7 +39631,7 @@ export namespace Schemas {
query: string;
response?: HogQLAutocompleteResponse | null;
/** Query in whose context to validate. */
- sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
+ sourceQuery?: EventsNode | ActionsNode | PersonsNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | CalendarHeatmapQuery | RecordingsQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | null;
/** Start position of the editor word */
startPosition: number;
tags?: QueryLogTags | null;
@@ -63150,7 +63293,7 @@ export namespace Schemas {
* ```
*
* For more details on HogQL queries, see the [PostHog HogQL documentation](/docs/hogql#api-access). */
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
/** Whether results should be calculated sync or async, and how much to rely on the cache:
* - `'blocking'` - calculate synchronously (returning only when the query is done), UNLESS there are very fresh results in the cache
* - `'async'` - kick off background calculation (returning immediately with a query status), UNLESS there are very fresh results in the cache
@@ -65153,17 +65296,21 @@ export namespace Schemas {
export interface QueryResponseAlternative87 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
+ hasMore: boolean;
/** Generated HogQL query. */
hogql?: string | null;
+ kind?: 'AccountsTableQuery';
+ limit: number;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
+ offset: number;
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus | null;
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: EndpointsUsageOverviewItem[];
+ results: AccountsTableRow[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -65173,6 +65320,28 @@ export namespace Schemas {
}
export interface QueryResponseAlternative88 {
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null;
+ /** Generated HogQL query. */
+ hogql?: string | null;
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiers | null;
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatus | null;
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponse | null;
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponse | null;
+ results: EndpointsUsageOverviewItem[];
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTiming[] | null;
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsage[] | null;
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
+ }
+
+ export interface QueryResponseAlternative89 {
columns?: unknown[] | null;
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
@@ -65199,9 +65368,9 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative89ResultsItem = { [key: string]: unknown };
+ export type QueryResponseAlternative90ResultsItem = { [key: string]: unknown };
- export interface QueryResponseAlternative89 {
+ export interface QueryResponseAlternative90 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65214,7 +65383,7 @@ export namespace Schemas {
resolved_compare_date_range?: ResolvedDateRangeResponse | null;
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse | null;
- results: QueryResponseAlternative89ResultsItem[];
+ results: QueryResponseAlternative90ResultsItem[];
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[] | null;
/** Connector-synced data warehouse sources referenced by this query, if any. */
@@ -65223,7 +65392,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative90 {
+ export interface QueryResponseAlternative91 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65245,7 +65414,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative91 {
+ export interface QueryResponseAlternative92 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65267,7 +65436,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative92 {
+ export interface QueryResponseAlternative93 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65289,7 +65458,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative93 {
+ export interface QueryResponseAlternative94 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65311,7 +65480,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative94 {
+ export interface QueryResponseAlternative95 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65333,7 +65502,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative95 {
+ export interface QueryResponseAlternative96 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65355,7 +65524,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative96 {
+ export interface QueryResponseAlternative97 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65378,7 +65547,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative97 {
+ export interface QueryResponseAlternative98 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65400,7 +65569,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative98 {
+ export interface QueryResponseAlternative99 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65422,7 +65591,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative99 {
+ export interface QueryResponseAlternative100 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65444,7 +65613,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative100 {
+ export interface QueryResponseAlternative101 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65466,7 +65635,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative101 {
+ export interface QueryResponseAlternative102 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65488,7 +65657,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative102 {
+ export interface QueryResponseAlternative103 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65510,7 +65679,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative103 {
+ export interface QueryResponseAlternative104 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65532,7 +65701,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative104 {
+ export interface QueryResponseAlternative105 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65554,7 +65723,7 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export interface QueryResponseAlternative105 {
+ export interface QueryResponseAlternative106 {
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string | null;
/** Generated HogQL query. */
@@ -65576,18 +65745,18 @@ export namespace Schemas {
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[] | null;
}
- export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | unknown | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105;
+ export type QueryResponseAlternative = { [key: string]: unknown } | QueryResponseAlternative1 | QueryResponseAlternative2 | QueryResponseAlternative3 | QueryResponseAlternative4 | QueryResponseAlternative5 | QueryResponseAlternative6 | QueryResponseAlternative7 | QueryResponseAlternative8 | QueryResponseAlternative9 | QueryResponseAlternative10 | QueryResponseAlternative11 | QueryResponseAlternative12 | QueryResponseAlternative13 | QueryResponseAlternative14 | QueryResponseAlternative15 | QueryResponseAlternative16 | QueryResponseAlternative17 | QueryResponseAlternative18 | QueryResponseAlternative19 | QueryResponseAlternative20 | QueryResponseAlternative21 | QueryResponseAlternative22 | QueryResponseAlternative23 | QueryResponseAlternative24 | QueryResponseAlternative25 | QueryResponseAlternative26 | QueryResponseAlternative27 | QueryResponseAlternative28 | QueryResponseAlternative29 | QueryResponseAlternative30 | QueryResponseAlternative31 | QueryResponseAlternative32 | QueryResponseAlternative33 | QueryResponseAlternative34 | unknown | QueryResponseAlternative35 | QueryResponseAlternative36 | QueryResponseAlternative37 | QueryResponseAlternative38 | QueryResponseAlternative39 | QueryResponseAlternative40 | QueryResponseAlternative41 | QueryResponseAlternative42 | QueryResponseAlternative43 | QueryResponseAlternative44 | QueryResponseAlternative45 | QueryResponseAlternative46 | QueryResponseAlternative47 | QueryResponseAlternative48 | QueryResponseAlternative49 | QueryResponseAlternative50 | QueryResponseAlternative52 | QueryResponseAlternative53 | QueryResponseAlternative54 | QueryResponseAlternative56 | QueryResponseAlternative57 | QueryResponseAlternative58 | QueryResponseAlternative59 | QueryResponseAlternative60 | QueryResponseAlternative61 | QueryResponseAlternative62 | QueryResponseAlternative63 | QueryResponseAlternative65 | QueryResponseAlternative66 | QueryResponseAlternative67 | QueryResponseAlternative68 | QueryResponseAlternative69 | QueryResponseAlternative70 | QueryResponseAlternative71 | QueryResponseAlternative72 | QueryResponseAlternative73 | QueryResponseAlternative74 | QueryResponseAlternative75 | QueryResponseAlternative76 | QueryResponseAlternative77 | QueryResponseAlternative78 | QueryResponseAlternative79 | QueryResponseAlternative80 | QueryResponseAlternative83 | QueryResponseAlternative84 | QueryResponseAlternative85 | QueryResponseAlternative86 | QueryResponseAlternative87 | QueryResponseAlternative88 | QueryResponseAlternative89 | QueryResponseAlternative90 | QueryResponseAlternative91 | QueryResponseAlternative92 | QueryResponseAlternative93 | QueryResponseAlternative94 | QueryResponseAlternative95 | QueryResponseAlternative96 | QueryResponseAlternative97 | QueryResponseAlternative98 | QueryResponseAlternative99 | QueryResponseAlternative100 | QueryResponseAlternative101 | QueryResponseAlternative102 | QueryResponseAlternative103 | QueryResponseAlternative104 | QueryResponseAlternative105 | QueryResponseAlternative106;
export interface QueryStatusResponse {
query_status: QueryStatus;
}
export interface QueryUpgradeRequest {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QueryUpgradeResponse {
- query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
+ query: EventsNode | ActionsNode | PersonsNode | DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode | EventsQuery | SessionsQuery | ActorsQuery | GroupsQuery | InsightActorsQuery | InsightActorsQueryOptions | SessionsTimelineQuery | HogQuery | HogQLQuery | HogQLMetadata | HogQLAutocomplete | SessionAttributionExplorerQuery | ErrorTrackingQuery | ErrorTrackingSimilarIssuesQuery | ErrorTrackingBreakdownsQuery | ErrorTrackingIssueCorrelationQuery | ExperimentFunnelsQuery | ExperimentTrendsQuery | ExperimentQuery | ExperimentExposureQuery | DocumentSimilarityQuery | WebOverviewQuery | WebStatsTableQuery | WebExternalClicksTableQuery | WebBotsTableQuery | WebGoalsQuery | WebVitalsQuery | WebVitalsPathBreakdownQuery | WebPageURLSearchQuery | WebAnalyticsExternalSummaryQuery | WebNotableChangesQuery | MarketingAnalyticsTableQuery | MarketingAnalyticsAggregatedQuery | MarketingAnalyticsAttributionQuery | MarketingAnalyticsAttributionPathsQuery | NonIntegratedConversionsTableQuery | DataVisualizationNode | DataTableNode | SavedInsightNode | InsightVizNode | TrendsQuery | FunnelsQuery | RetentionQuery | PathsQuery | PathsV2Query | StickinessQuery | LifecycleQuery | FunnelCorrelationQuery | DatabaseSchemaQuery | RecordingsQuery | LogsQuery | LogAttributesQuery | LogValuesQuery | MetricsQuery | TraceSpansQuery | TraceSpansAggregationQuery | TraceSpansTreeQuery | TraceSpansAttributeBreakdownQuery | SuggestedQuestionsQuery | TeamTaxonomyQuery | EventTaxonomyQuery | ActorsPropertyTaxonomyQuery | TracesQuery | TraceQuery | SessionQuery | TraceNeighborsQuery | VectorSearchQuery | UsageMetricsQuery | AccountsQuery | AccountsTableQuery | EndpointsUsageOverviewQuery | EndpointsUsageTableQuery | EndpointsUsageTrendsQuery | MCPToolCallBreakdownQuery | MCPToolCallsAndErrorsQuery | MCPHarnessBreakdownQuery | MCPToolTopUsersQuery | MCPToolFailuresQuery | MCPToolFailureOccurrencesQuery | MCPToolStatsQuery | MCPToolDailyStatsQuery | MCPToolQualityRowsQuery | MCPToolQualityDailyStatsQuery | MCPToolCategoryCountsQuery | MCPToolCategoriesQuery | MCPToolDescriptionsQuery | MCPToolSampleIntentsQuery | MCPToolNeighborsQuery | PropertyValuesQuery;
}
export interface QuotaResourceLimit {