:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { DataColorToken } from 'lib/colors'
// eslint-disable-next-line import/no-cycle
import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import type { FunnelLayout } from 'lib/constants'
import type { AggregationAxisFormat } from 'lib/insights/aggregationAxisFormat'
import { ConversionGoalSchema } from '~/taxonomy/marketingAnalytics'
import {
AnnotationScope,
AnyFilterLike,
AnyGroupScopeFilter,
AnyPersonScopeFilter,
AnyPropertyFilter,
BaseMathType,
BinCountValue,
BreakdownAttributionType,
BreakdownKeyType,
BreakdownType,
CalendarHeatmapMathType,
ChartDisplayCategory,
ChartDisplayType,
CohortPropertyFilter,
CountPerActorMathType,
DataWarehouseViewLink,
EventPropertyFilter,
EventType,
ExperimentHoldoutType,
ExperimentIdType,
ExperimentMetricGoal,
ExperimentMetricMathType,
ExperimentStatsMethod,
FileSystemIconColor,
FilterLogicalOperator,
FunnelConversionWindowTimeUnit,
FunnelMathType,
FunnelPathType,
FunnelStepReference,
FunnelVizType,
GroupMathType,
HogQLMathType,
InsightShortId,
InsightType,
IntegrationType,
IntervalType,
LifecycleToggle,
LogEntryPropertyFilter,
MatchedRecordingEvent,
PathCleaningFilter,
PathType,
PersonPropertyFilter,
PropertyGroupFilter,
PropertyGroupFilterValue,
PropertyMathType,
PropertyOperator,
RecordingPropertyFilter,
RetentionDashboardDisplayType,
RetentionEntity,
RetentionPeriod,
RetentionType,
SessionPropertyFilter,
SessionRecordingType,
SlackIntegrationScope,
SlackIntegrationScopeInReview,
StepOrderValue,
} from '~/types'
import { BIVisualizationNode } from './schema-business-intelligence'
import { integer, non_negative_integer, numerical_key, positive_integer } from './type-utils'
export { ChartDisplayCategory }
// Re-exported so the codegen picks them up and emits matching `StrEnum`s in posthog/schema.py.
// The runtime consts live in `~/types` as `SLACK_INTEGRATION_SCOPES` and `SLACK_INTEGRATION_SCOPES_IN_REVIEW`.
export { SlackIntegrationScope, SlackIntegrationScopeInReview }
/**
* PostHog Query Schema definition.
*
* This file acts as the source of truth for:
*
* - frontend/src/queries/schema.json
* - generated from typescript via "pnpm --filter=@posthog/frontend run schema:build:json"
*
* - posthog/schema.py
* - generated from json the above json via "pnpm -w run schema:build:python"
* */
export enum NodeKind {
// Data nodes
EventsNode = 'EventsNode',
GroupNode = 'GroupNode',
ActionsNode = 'ActionsNode',
DataWarehouseNode = 'DataWarehouseNode',
FunnelsDataWarehouseNode = 'FunnelsDataWarehouseNode',
LifecycleDataWarehouseNode = 'LifecycleDataWarehouseNode',
EventsQuery = 'EventsQuery',
SessionsQuery = 'SessionsQuery',
PersonsNode = 'PersonsNode',
HogQuery = 'HogQuery',
HogQLQuery = 'HogQLQuery',
HogQLMetadata = 'HogQLMetadata',
HogQLAutocomplete = 'HogQLAutocomplete',
ActorsQuery = 'ActorsQuery',
GroupsQuery = 'GroupsQuery',
FunnelsActorsQuery = 'FunnelsActorsQuery',
PathsV2ActorsQuery = 'PathsV2ActorsQuery',
SessionsTimelineQuery = 'SessionsTimelineQuery',
RecordingsQuery = 'RecordingsQuery',
SessionAttributionExplorerQuery = 'SessionAttributionExplorerQuery',
ErrorTrackingQuery = 'ErrorTrackingQuery',
ErrorTrackingSimilarIssuesQuery = 'ErrorTrackingSimilarIssuesQuery',
ErrorTrackingFingerprintProjectionQuery = 'ErrorTrackingFingerprintProjectionQuery',
ErrorTrackingBreakdownsQuery = 'ErrorTrackingBreakdownsQuery',
ErrorTrackingReleasesQuery = 'ErrorTrackingReleasesQuery',
ErrorTrackingIssueCorrelationQuery = 'ErrorTrackingIssueCorrelationQuery',
ErrorTrackingIssueEventsQuery = 'ErrorTrackingIssueEventsQuery',
LogsQuery = 'LogsQuery',
LogAttributesQuery = 'LogAttributesQuery',
LogValuesQuery = 'LogValuesQuery',
MetricsQuery = 'MetricsQuery',
MetricsHistogramQuery = 'MetricsHistogramQuery',
TraceSpansQuery = 'TraceSpansQuery',
TraceSpansAggregationQuery = 'TraceSpansAggregationQuery',
TraceSpansTreeQuery = 'TraceSpansTreeQuery',
TraceSpansAttributeBreakdownQuery = 'TraceSpansAttributeBreakdownQuery',
TraceSpansSymbolStatsQuery = 'TraceSpansSymbolStatsQuery',
SessionBatchEventsQuery = 'SessionBatchEventsQuery',
// Interface nodes
DataTableNode = 'DataTableNode',
DataVisualizationNode = 'DataVisualizationNode',
BIVisualizationNode = 'BIVisualizationNode',
SavedInsightNode = 'SavedInsightNode',
InsightVizNode = 'InsightVizNode',
TrendsQuery = 'TrendsQuery',
CalendarHeatmapQuery = 'CalendarHeatmapQuery',
FunnelsQuery = 'FunnelsQuery',
RetentionQuery = 'RetentionQuery',
PathsQuery = 'PathsQuery',
PathsV2Query = 'PathsV2Query',
StickinessQuery = 'StickinessQuery',
StickinessActorsQuery = 'StickinessActorsQuery',
LifecycleQuery = 'LifecycleQuery',
InsightActorsQuery = 'InsightActorsQuery',
InsightActorsQueryOptions = 'InsightActorsQueryOptions',
// Web analytics + Web Vitals queries
WebOverviewQuery = 'WebOverviewQuery',
WebStatsTableQuery = 'WebStatsTableQuery',
WebExternalClicksTableQuery = 'WebExternalClicksTableQuery',
WebBotsTableQuery = 'WebBotsTableQuery',
WebAgentAnalyticsQuery = 'WebAgentAnalyticsQuery',
WebPageDirectoryQuery = 'WebPageDirectoryQuery',
WebGoalsQuery = 'WebGoalsQuery',
WebVitalsQuery = 'WebVitalsQuery',
WebVitalsPathBreakdownQuery = 'WebVitalsPathBreakdownQuery',
WebPageURLSearchQuery = 'WebPageURLSearchQuery',
WebAnalyticsExternalSummaryQuery = 'WebAnalyticsExternalSummaryQuery',
WebNotableChangesQuery = 'WebNotableChangesQuery',
// Revenue analytics queries
// Marketing analytics queries
MarketingAnalyticsTableQuery = 'MarketingAnalyticsTableQuery',
MarketingAnalyticsAggregatedQuery = 'MarketingAnalyticsAggregatedQuery',
MarketingAnalyticsAttributionQuery = 'MarketingAnalyticsAttributionQuery',
MarketingAnalyticsAttributionPathsQuery = 'MarketingAnalyticsAttributionPathsQuery',
MarketingAnalyticsRetentionQuery = 'MarketingAnalyticsRetentionQuery',
MarketingAnalyticsSearchQuery = 'MarketingAnalyticsSearchQuery',
MarketingAnalyticsRecommendationsQuery = 'MarketingAnalyticsRecommendationsQuery',
// Experiment queries
ExperimentMetric = 'ExperimentMetric',
ExperimentQuery = 'ExperimentQuery',
ExperimentExposureQuery = 'ExperimentExposureQuery',
ExperimentEventExposureConfig = 'ExperimentEventExposureConfig',
ExperimentWarehouseNativeExposureConfig = 'ExperimentWarehouseNativeExposureConfig',
ExperimentActorsQuery = 'ExperimentActorsQuery',
ExperimentTrendsQuery = 'ExperimentTrendsQuery',
ExperimentFunnelsQuery = 'ExperimentFunnelsQuery',
ExperimentDataWarehouseNode = 'ExperimentDataWarehouseNode',
ExperimentWarehouseNativeNode = 'ExperimentWarehouseNativeNode',
ExperimentExposureNode = 'ExperimentExposureNode',
// Database metadata
DatabaseSchemaQuery = 'DatabaseSchemaQuery',
// AI queries
SuggestedQuestionsQuery = 'SuggestedQuestionsQuery',
TeamTaxonomyQuery = 'TeamTaxonomyQuery',
InboxUsageQuery = 'InboxUsageQuery',
EventTaxonomyQuery = 'EventTaxonomyQuery',
ActorsPropertyTaxonomyQuery = 'ActorsPropertyTaxonomyQuery',
TracesQuery = 'TracesQuery',
TraceQuery = 'TraceQuery',
SessionQuery = 'SessionQuery',
TraceNeighborsQuery = 'TraceNeighborsQuery',
VectorSearchQuery = 'VectorSearchQuery',
DocumentSimilarityQuery = 'DocumentSimilarityQuery',
// Customer analytics
UsageMetricsQuery = 'UsageMetricsQuery',
AccountsQuery = 'AccountsQuery',
AccountsTableQuery = 'AccountsTableQuery',
AccountUsersQuery = 'AccountUsersQuery',
// Endpoints usage queries
EndpointsUsageOverviewQuery = 'EndpointsUsageOverviewQuery',
EndpointsUsageTableQuery = 'EndpointsUsageTableQuery',
EndpointsUsageTrendsQuery = 'EndpointsUsageTrendsQuery',
// MCP analytics
MCPToolCallBreakdownQuery = 'MCPToolCallBreakdownQuery',
MCPToolCallsAndErrorsQuery = 'MCPToolCallsAndErrorsQuery',
MCPHarnessBreakdownQuery = 'MCPHarnessBreakdownQuery',
MCPModelBreakdownQuery = 'MCPModelBreakdownQuery',
MCPProtocolVersionBreakdownQuery = 'MCPProtocolVersionBreakdownQuery',
MCPToolTopUsersQuery = 'MCPToolTopUsersQuery',
MCPToolFailuresQuery = 'MCPToolFailuresQuery',
MCPToolFailureOccurrencesQuery = 'MCPToolFailureOccurrencesQuery',
MCPToolStatsQuery = 'MCPToolStatsQuery',
MCPToolDailyStatsQuery = 'MCPToolDailyStatsQuery',
MCPToolQualityRowsQuery = 'MCPToolQualityRowsQuery',
MCPToolQualityDailyStatsQuery = 'MCPToolQualityDailyStatsQuery',
MCPToolCategoryCountsQuery = 'MCPToolCategoryCountsQuery',
MCPToolCategoriesQuery = 'MCPToolCategoriesQuery',
MCPToolCategoryMapQuery = 'MCPToolCategoryMapQuery',
MCPToolDescriptionsQuery = 'MCPToolDescriptionsQuery',
MCPToolSampleIntentsQuery = 'MCPToolSampleIntentsQuery',
MCPToolNeighborsQuery = 'MCPToolNeighborsQuery',
MCPMissingCapabilitiesQuery = 'MCPMissingCapabilitiesQuery',
// Property values
PropertyValuesQuery = 'PropertyValuesQuery',
}
/**
* @discriminator kind
*/
export type AnyDataNode =
| EventsNode // never queried directly
| ActionsNode // old actions API endpoint
| PersonsNode // old persons API endpoint
| EventsQuery
| SessionsQuery
| ActorsQuery
| GroupsQuery
| InsightActorsQuery
| InsightActorsQueryOptions
| SessionsTimelineQuery
| HogQuery
| HogQLQuery
| HogQLMetadata
| HogQLAutocomplete
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
| MarketingAnalyticsRecommendationsQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
| WebBotsTableQuery
| WebAgentAnalyticsQuery
| WebPageDirectoryQuery
| WebGoalsQuery
| WebVitalsQuery
| WebVitalsPathBreakdownQuery
| WebPageURLSearchQuery
| WebAnalyticsExternalSummaryQuery
| WebNotableChangesQuery
| SessionAttributionExplorerQuery
| ErrorTrackingQuery
| ErrorTrackingSimilarIssuesQuery
| ErrorTrackingFingerprintProjectionQuery
| ErrorTrackingBreakdownsQuery
| ErrorTrackingReleasesQuery
| ErrorTrackingIssueCorrelationQuery
| ErrorTrackingIssueEventsQuery
| LogsQuery
| LogAttributesQuery
| LogValuesQuery
| MetricsQuery
| MetricsHistogramQuery
| TraceSpansQuery
| TraceSpansAggregationQuery
| TraceSpansTreeQuery
| TraceSpansAttributeBreakdownQuery
| CalendarHeatmapQuery
| RecordingsQuery
| TracesQuery
| TraceQuery
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
| InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
| MCPToolCallBreakdownQuery
| MCPToolCallsAndErrorsQuery
| MCPHarnessBreakdownQuery
| MCPModelBreakdownQuery
| MCPProtocolVersionBreakdownQuery
| MCPToolTopUsersQuery
| MCPToolFailuresQuery
| MCPToolFailureOccurrencesQuery
| MCPToolStatsQuery
| MCPToolDailyStatsQuery
| MCPToolQualityRowsQuery
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
| MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
| MCPMissingCapabilitiesQuery
/**
* @discriminator kind
*/
export type QuerySchema =
// Data nodes (see utils.ts)
| EventsNode // never queried directly
| ActionsNode // old actions API endpoint
| PersonsNode // old persons API endpoint
| DataWarehouseNode
| FunnelsDataWarehouseNode
| LifecycleDataWarehouseNode
| EventsQuery
| SessionsQuery
| ActorsQuery
| GroupsQuery
| InsightActorsQuery
| InsightActorsQueryOptions
| SessionsTimelineQuery
| HogQuery
| HogQLQuery
| HogQLMetadata
| HogQLAutocomplete
| SessionAttributionExplorerQuery
| ErrorTrackingQuery
| ErrorTrackingSimilarIssuesQuery
| ErrorTrackingFingerprintProjectionQuery
| ErrorTrackingBreakdownsQuery
| ErrorTrackingReleasesQuery
| ErrorTrackingIssueCorrelationQuery
| ErrorTrackingIssueEventsQuery
| ExperimentQuery
| ExperimentExposureQuery
| DocumentSimilarityQuery
// Web Analytics + Web Vitals
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
| WebBotsTableQuery
| WebAgentAnalyticsQuery
| WebPageDirectoryQuery
| WebGoalsQuery
| WebVitalsQuery
| WebVitalsPathBreakdownQuery
| WebPageURLSearchQuery
| WebAnalyticsExternalSummaryQuery
| WebNotableChangesQuery
// Revenue analytics
// Marketing analytics
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| MarketingAnalyticsAttributionQuery
| MarketingAnalyticsAttributionPathsQuery
| MarketingAnalyticsRetentionQuery
| MarketingAnalyticsSearchQuery
| MarketingAnalyticsRecommendationsQuery
// Interface nodes
| DataVisualizationNode
| BIVisualizationNode
| DataTableNode
| SavedInsightNode
| InsightVizNode
// Classic insights
| TrendsQuery
| FunnelsQuery
| RetentionQuery
| PathsQuery
| PathsV2Query
| StickinessQuery
| LifecycleQuery
// Misc
| DatabaseSchemaQuery
// Session Recordings
| RecordingsQuery
// Logs
| LogsQuery
| LogAttributesQuery
| LogValuesQuery
// Metrics
| MetricsQuery
| MetricsHistogramQuery
// Tracing
| TraceSpansQuery
| TraceSpansAggregationQuery
| TraceSpansTreeQuery
| TraceSpansAttributeBreakdownQuery
// AI
| SuggestedQuestionsQuery
| TeamTaxonomyQuery
| EventTaxonomyQuery
| ActorsPropertyTaxonomyQuery
| TracesQuery
| TraceQuery
| SessionQuery
| TraceNeighborsQuery
| VectorSearchQuery
// Customer analytics
| InboxUsageQuery
| UsageMetricsQuery
| AccountsQuery
| AccountsTableQuery
// Endpoints usage
| EndpointsUsageOverviewQuery
| EndpointsUsageTableQuery
| EndpointsUsageTrendsQuery
// MCP analytics
| MCPToolCallBreakdownQuery
| MCPToolCallsAndErrorsQuery
| MCPHarnessBreakdownQuery
| MCPModelBreakdownQuery
| MCPProtocolVersionBreakdownQuery
| MCPToolTopUsersQuery
| MCPToolFailuresQuery
| MCPToolFailureOccurrencesQuery
| MCPToolStatsQuery
| MCPToolDailyStatsQuery
| MCPToolQualityRowsQuery
| MCPToolQualityDailyStatsQuery
| MCPToolCategoryCountsQuery
| MCPToolCategoriesQuery
| MCPToolCategoryMapQuery
| MCPToolDescriptionsQuery
| MCPToolSampleIntentsQuery
| MCPToolNeighborsQuery
| MCPMissingCapabilitiesQuery
// Property values
| PropertyValuesQuery
// Keep this, because QuerySchema itself will be collapsed as it is used in other models
export type QuerySchemaRoot = QuerySchema
// Dynamically make a union type out of all the types in all `response` fields in QuerySchema
type QueryResponseType<T> = T extends { response?: infer R } ? { response: R } : never
type QueryAllResponses = QueryResponseType<QuerySchema>
export type QueryResponseAlternative = QueryAllResponses['response']
/**
* Node base class, everything else inherits from here.
* @internal - no need to emit to schema.json.
*/
export interface Node<R extends Record<string, any> = Record<string, any>> {
kind: NodeKind
/** version of the node, used for schema migrations */
version?: number
/** @internal Don't use this property at runtime, it's here for typing. */
response?: R
}
// Data nodes
export type AnyResponseType =
| Record<string, any>
| HogQueryResponse
| HogQLQueryResponse
| HogQLMetadataResponse
| HogQLAutocompleteResponse
| EventsNode['response']
| EventsQueryResponse
| SessionsQueryResponse
| ErrorTrackingQueryResponse
| LogsQueryResponse
| LogAttributesQueryResponse
| LogValuesQueryResponse
| MetricsQueryResponse
| TraceSpansQueryResponse
| TraceSpansAggregationQueryResponse
| TraceSpansTreeQueryResponse
| TraceSpansAttributeBreakdownQueryResponse
/** Tags that will be added to the Query log comment **/
export interface QueryLogTags {
/** Scene where this query is shown in the UI. Use string, there's no need to churn the Schema when we add a new Scene **/
scene?: string
/** Product responsible for this query. Use string, there's no need to churn the Schema when we add a new product **/
productKey?: string
/** Name of the query, preferably unique. For example web_analytics_vitals */
name?: string
/** Short id of the saved Web analytics filter preset this query was run under, if any. */
presetId?: string
}
/** @internal - no need to emit to schema.json. */
export interface DataNode<R extends Record<string, any> = Record<string, any>> extends Node<R> {
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers
tags?: QueryLogTags
}
/** HogQL Query Options are automatically set per team. However, they can be overridden in the query. */
export interface HogQLQueryModifiers {
personsOnEventsMode?:
| 'disabled' // `disabled` is deprecated and set for removal - `person_id_override_properties_joined` is its faster functional equivalent
| 'person_id_no_override_properties_on_events'
| 'person_id_override_properties_on_events'
| 'person_id_override_properties_joined'
personsArgMaxVersion?: 'auto' | 'v1' | 'v2'
inCohortVia?: 'auto' | 'leftjoin' | 'subquery' | 'leftjoin_conjoined'
materializationMode?: 'auto' | 'legacy_null_as_string' | 'legacy_null_as_null' | 'disabled'
optimizeJoinedFilters?: boolean
/** Push a `session_id_v7 IN (SELECT … FROM events WHERE …)` predicate into the raw_sessions subquery to limit aggregation to sessions that participate in the outer events filter. */
sessionIdPushdown?: boolean
/** Padding, in minutes, on each side of the event time range when it filters the sessions table by session start. Defaults to 3 days. It can only narrow the range: values above the default are ignored. Lower it only for a query that keeps just the sessions that start inside its own time range. */
sessionTimestampBufferMinutes?: integer
/** Pre-filter raw_sessions aggregation by `session_id_v7 IN (cheap pre-aggregation that only materializes the columns referenced by the outer-WHERE session predicate)`. Useful when the breakdown/SELECT pulls in many session columns (e.g. `$channel_type`) but the filter only references one (e.g. `$entry_current_url`). */
sessionPropertyPreAggregation?: boolean
/** Push an `id IN (SELECT person_id FROM <left table> WHERE …)` predicate into the joined persons subquery, so the latest-version lookup only reads persons that the outer query's left-table filters can reach. Applies only to a persons join from the query's own FROM table. */
personIdPushdown?: boolean
/** Replace negated person-property filters in the WHERE of an `events` query (such as `email not_icontains`) with `person_id NOT IN (SELECT id FROM persons WHERE <the filters fail>)`, so the query no longer joins every person. Applies only when every filtered person property has a materialized column, nothing else in the query reads that persons join, and the join would be a LEFT JOIN. */
negatedPersonFiltersNotIn?: boolean
dataWarehouseEventsModifiers?: DataWarehouseEventsModifier[]
debug?: boolean
timings?: boolean
s3TableUseInvalidColumns?: boolean
personsJoinMode?: 'inner' | 'left'
bounceRatePageViewMode?: 'count_pageviews' | 'uniq_urls' | 'uniq_page_screen_autocaptures'
bounceRateDurationSeconds?: number
sessionTableVersion?: 'auto' | 'v1' | 'v2' | 'v3'
sessionsV2JoinMode?: 'string' | 'uuid'
materializedColumnsOptimizationMode?: 'disabled' | 'optimized'
propertyGroupsMode?: 'enabled' | 'disabled' | 'optimized'
useMaterializedViews?: boolean
/** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, a staff person's `ph_new_events_schema` cookie applies, then the project's listing in the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA_TEAMS` instance setting, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance setting. This is an internal rollout switch, and the project settings API ignores it. */
useNewEventsSchema?: boolean
customChannelTypeRules?: CustomChannelRule[]
customBotDefinitions?: CustomBotRule[]
/** Do not treat a missing user agent as automation on cookieless events. Positive bot signals and custom project rules still apply. Resolved server-side; not intended to be set by clients. */
cookielessTrafficIsRegular?: boolean | null
useWebAnalyticsPreAggregatedTables?: boolean
/** Serve filters on the stored session-entry attribution properties (`$channel_type`, `$entry_utm_*`, `$entry_referring_domain`) by recomputing the value from the session's first pageview. Resolved server-side; not intended to be set by clients. */
webAnalyticsFirstPageviewFilters?: boolean
formatCsvAllowDoubleQuotes?: boolean
convertToProjectTimezone?: boolean
/** Try to automatically convert HogQL queries to use preaggregated tables at the AST level **/
usePreaggregatedTableTransforms?: boolean
usePreaggregatedIntermediateResults?: boolean
optimizeProjections?: boolean
/** Reuse eligible bounded event aggregates within one query execution. When unset, the server may enable it via the cloud feature flag. */
materializeRepeatedCTEs?: boolean
/** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
typeAwareCastSimplification?: boolean
pushDownPredicates?: boolean
/** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
mergeFederatedAggregateJoins?: boolean
/** If these are provided, the query will fail if these skip indexes are not used */
forceClickhouseDataSkippingIndexes?: string[]
inlineCohortCalculation?: 'off' | 'auto' | 'always'
/** HogQL parser backend; absent → `rust_py_with_cpp_shadow` (rust-py is primary, cpp runs as a sampled shadow). `*_shadow` modes return the primary result and sample-compare against the other parser, reporting divergences without failing the request. The `rust_py_*` modes drive the same hand-rolled Rust parser as `rust_*` but build `posthog.hogql.ast` dataclass instances directly via PyO3, skipping the JSON round-trip. */
parserMode?:
| 'cpp_only'
| 'cpp_with_rust_shadow'
| 'cpp_with_rust_py_shadow'
| 'rust_with_cpp_shadow'
| 'rust_only'
| 'rust_py_only'
| 'rust_py_with_cpp_shadow'
}
export interface DataWarehouseEventsModifier {
table_name: string
timestamp_field: string
distinct_id_field: string
id_field: string
}
export interface DataWarehouseSyncWarning {
/** Tells warning kinds apart in the shared `warnings` list */
type: 'warehouse_sync'
/** Name of the warehouse table the warning refers to */
table_name: string
/** Name of the ExternalDataSchema responsible for syncing the table */
schema_name: string
/** Source type, e.g. "Stripe", "Hubspot" */
source_type: string
/** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */
source_id?: string | null
/** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
status: string
/** Human-readable warning shown to the user */
message: string
/**
* True when the last sync is still within the table's sync interval, so the data is current and the
* warning only says it will stop updating (a sync paused recently). False or absent when the data is out of date.
*/
data_is_current?: boolean
}
export interface AccessControlFilterWarning {
/** Tells warning kinds apart in the shared `warnings` list */
type: 'access_control'
/** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */
resources: string[]
/** Human-readable warning shown to the user */
message: string
}
export interface BreakdownNotAppliedWarning {
/** Tells warning kinds apart in the shared `warnings` list */
type: 'breakdown_not_applied'
/** Human-readable warning shown to the user */
message: string
}
/**
* `no_event_filter`: nothing narrows the query to particular events. `no_start_date`: nothing bounds
* where it starts reading. `persons_join`: the join to the persons tables reads as much as the events do.
*/
export type QueryScanFindingKind = 'no_event_filter' | 'no_start_date' | 'persons_join'
/** Where the change that fixes a finding goes. `insight_date_range` is the range a SQL insight takes through `{filters}`. */
export type QueryScanFixLocation = 'query' | 'subquery' | 'view' | 'insight_date_range' | 'dashboard_date_filter'
/** One finding of a query's analysis. */
export interface QueryScanWarning {
kind: QueryScanFindingKind
/** A label for what in the query text kept the read wide, such as `in_or`. Only analytics and the assistant read it, and the labels can change. */
cause?: string
/** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
by_design?: boolean
/** Where the change goes. Absent means the query itself. */
fix_location?: QueryScanFixLocation
/** Shown to the person: what happened and what to do. */
message: string
/** What "Fix with AI" and the assistant are told to do. */
fix: string
/** The one fact the finding rests on. */
evidence?: string
/** Whether the person can change the query so it reads less and still answers the same question. Surfaces show the full advice and "Fix with AI" only when a finding is actionable. */
actionable: boolean
}
/** The stored analysis of one query, kept for 30 days by cache key and put on every response for that query. */
export interface QueryScanAnalysis {
/** Every finding, fixable or not. Empty when the analysis found none. */
findings: QueryScanWarning[]
/** How much of the project's events in the query's date range the query read, 0 to 1. */
range_share?: number
/** How much of all the project's events the query read, 0 to 1. */
project_share?: number
/** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
assistant_prompt?: string
}
/** What a query cost and, once analyzed, why. Only on responses to a signed-in user of a team whose flag shows findings. */
export interface QueryScanSummary {
/** Rows ClickHouse read for the last fresh run, all tables included. */
rows_read: integer
/** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */
duration_ms: integer
/** True when ClickHouse stopped the run instead of finishing it. */
killed?: boolean
/** True when the run asked for an analysis, or found one stored. While `analysis` is absent, poll `GET /query/scan/{cache_key}` for it. */
analysis_requested?: boolean
/** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */
analysis?: QueryScanAnalysis
}
/** From `GET /query/scan/{cache_key}`: the analysis once the job has stored it. Empty while the job runs, 404 when nothing is stored. */
export interface QueryScanResponse {
analysis?: QueryScanAnalysis
}
export interface HogQLQueryResponse<T = any[]> extends AnalyticsQueryResponseBase {
results: T
/** Input query string */
query?: string
/** Executed ClickHouse query */
clickhouse?: string
/** Returned columns */
columns?: any[]
/** Display formats for directly selected virtual properties, aligned with columns. */
column_formats?: (string | null)[]
/** Types of returned columns */
types?: any[]
/** Query explanation output */
explain?: string[]
/** Query metadata output */
metadata?: HogQLMetadataResponse
/**
* 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.
* Also carries access control warnings when a system-table query filters out objects the user can't access.
*/
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning)[]
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedHogQLQueryResponse = CachedQueryResponse<HogQLQueryResponse>
/** Filters object that will be converted to a HogQL {filters} placeholder */
export interface HogQLFilters {
properties?: AnyPropertyFilter[]
dateRange?: DateRange
/** Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}. */
compareFilter?: CompareFilter
filterTestAccounts?: boolean
/** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
interval?: IntervalType
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilter
}
export interface HogQLVariable {
variableId: string
code_name: string
value?: any
isNull?: boolean
}
export interface HogQLQuery extends DataNode<HogQLQueryResponse> {
kind: NodeKind.HogQLQuery
query: string
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string
/** Compile and run this query against the hosted Trino target. */
executionTarget?: 'default' | 'managed_trino'
/** Run the selected connection query directly without translating it through HogQL first */
sendRawQuery?: boolean
/** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */
filters?: HogQLFilters
/** Variables to be substituted into the query */
variables?: Record<string, HogQLVariable>
/** Constant values that can be referenced with the {placeholder} syntax in the query */
values?: Record<string, any>
/** Rows to skip before the default row limit applies. Rejected when the query sets its own LIMIT, uses UNION, or runs as raw SQL. */
offset?: non_negative_integer
/** @deprecated use modifiers.debug instead */
explain?: boolean
/** Client provided name of the query */
name?: string
}
export interface HogQueryResponse {
results: any
bytecode?: any[]
coloredBytecode?: any[]
stdout?: string
query_status?: never
}
export interface HogQuery extends DataNode<HogQueryResponse> {
kind: NodeKind.HogQuery
code?: string
}
export interface RecordingsQueryResponse extends AnalyticsQueryResponseBase {
results: SessionRecordingType[]
has_next: boolean
/** Cursor for the next page. Contains the ordering value and session_id from the last record. */
next_cursor?: string
}
export type CachedRecordingsQueryResponse = CachedQueryResponse<RecordingsQueryResponse>
export const VALID_RECORDING_ORDERS = [
'duration',
'recording_duration',
'inactive_seconds',
'active_seconds',
'start_time',
'console_error_count',
'click_count',
'keypress_count',
'mouse_activity_count',
'activity_score',
'recording_ttl',
'surfacing_score',
] as const
export interface MatchingEventsResponse {
results: MatchedRecordingEvent[]
}
export type RecordingOrder = (typeof VALID_RECORDING_ORDERS)[number]
export type RecordingOrderDirection = 'ASC' | 'DESC'
export interface RecordingsQueryExperimentExposureFilter {
/** Experiment whose exposed persons' sessions to show. Must belong to the environment the query runs in. */
experiment_id: integer
/** Narrow to persons exposed to this variant. Defaults to all of the experiment's variants. */
variant?: string
/**
* Narrow to persons exposed to any of these variants. Defaults to all of the experiment's variants.
* Do not combine with `variant`, the single-variant form that predates this field.
*/
variants?: string[]
/**
* Only sessions carrying in-session exposure evidence: an event matching the experiment's exposure criteria
* inside the session (with the stamped `$feature/<flag_key>` property standing in when the exposure event was
* never captured with a session id). Defaults to all exposed persons' sessions from first exposure onward.
*/
in_session?: boolean
}
export interface RecordingsQuery extends DataNode<RecordingsQueryResponse> {
kind: NodeKind.RecordingsQuery
/**
* @default "-3d"
* */
date_from?: string | null
date_to?: string | null
events?: Record<string, any>[]
actions?: Record<string, any>[]
properties?: AnyPropertyFilter[]
console_log_filters?: LogEntryPropertyFilter[]
having_predicates?: AnyPropertyFilter[] // duration and snapshot_source filters
comment_text?: RecordingPropertyFilter // search comments by text content
filter_test_accounts?: boolean
/** Restrict results to recordings above the replay relevance threshold. */
recommended_only?: boolean
/**
* @default "AND"
* */
operand?: FilterLogicalOperator
/**
* Where a filter that is evaluated against events must match. 'session' (default) matches an event
* anywhere in the session, including before the recording started or after it ended. 'recording' only
* matches events from one minute before the recording starts until one minute after it ends.
* This applies to every filter the events table answers: events, actions,
* event properties, and, when the project resolves them on events, person, group, and cohort properties.
* @default "session"
*/
event_match_scope?: 'recording' | 'session'
session_ids?: string[]
/** Exclude recordings already viewed by the current user ('current-user'), by any team member ('any-user'), or none (default). Applied server-side so pagination and the result cursor operate on the filtered set. */
hide_viewed_recordings?: 'current-user' | 'any-user' | null
/** If provided, this recording will be fetched and prepended to the results, even if it doesn't match the filters */
session_recording_id?: string
person_uuid?: string
distinct_ids?: string[]
/**
* Only sessions of persons exposed to this experiment, each ending at or after the person's
* first exposure as the experiment's exposure criteria count it. Resolved server-side from the
* experiment, so it links sessions even when the exposure events themselves carry no session id
* (e.g. server-side SDKs). Composes with the query's date range like any other filter, so set
* date_from to the experiment's start (or earlier) to cover the full run: the default window
* only reaches back a few days.
*/
experiment_exposure?: RecordingsQueryExperimentExposureFilter
/**
* @default "start_time"
* */
order?: RecordingOrder
/**
* Replay originally had all ordering as descending
* by specifying the field name,
* this runs counter to Django behavior
* where the field name specifies ascending sorting (e.g. the_field_name)
* and -the_field_name would indicate descending order
* to avoid invalidating or migrating all existing filters
* we keep DESC as the default
* or allow specification of an explicit order direction here
* @default "DESC"
*/
order_direction?: RecordingOrderDirection
limit?: integer
offset?: integer
/** Cursor for pagination. Contains the ordering value and session_id from the last record of the previous page. */
after?: string
user_modified_filters?: Record<string, any>
}
export interface HogQLNotice {
start?: integer
end?: integer
message: string
fix?: string
/** An https page with more detail about the notice. The editor links to it from the notice's hover. */
url?: string
}
export enum QueryIndexUsage {
Undecisive = 'undecisive',
No = 'no',
Partial = 'partial',
Yes = 'yes',
}
export enum PredicateIndexVerdict {
/** A skip index on the source column prunes granules for this predicate. */
Indexed = 'indexed',
/** The source carries an index this operator could use, but a type mismatch defeats it. */
Blocked = 'blocked',
/** The property reads from a dedicated column, but no index prunes this operator. */
UnindexedColumn = 'unindexed_column',
/** The property is parsed out of the JSON blob on every row. */
UnindexedJson = 'unindexed_json',
/** Negations, regexes and case-sensitive LIKE cannot be pruned by any skip index. */
OperatorNotIndexable = 'operator_not_indexable',
}
export enum PredicateScope {
Event = 'event',
Person = 'person',
Group = 'group',
Unknown = 'unknown',
}
export enum PredicateFixAction {
/** A query edit unblocks an index that already exists. */
EditQuery = 'edit_query',
/** The property definition declares a type its stored values do not have. */
EditPropertyType = 'edit_property_type',
/** The property has no dedicated column to index. */
Materialize = 'materialize',
}
export interface PredicateQuickfix {
/** Character offset in the query where the replaced range starts. */
start: integer
/** Character offset in the query where the replaced range ends. */
end: integer
/** Replacement text, substituted for the range verbatim. */
text: string
}
/** How one property filter in the query reads its data, decided before the query runs. */
export interface PredicateIndexUsage {
property_name: string
scope: PredicateScope
/** HogQL comparison operator, e.g. `==`, `in`, `ilike`. */
operator: string
/** Where the value is physically read from, e.g. `materialized column` or `JSON blob`. */
source_label: string
column_name?: string
/** Type the property definition declares. */
semantic_type: string
/** Type the value is physically stored as. */
physical_type: string
/** Skip indexes this predicate can actually use. */
usable_indexes: string[]
verdict: PredicateIndexVerdict
message: string
/** Prose advice for a reader. */
fix?: string
fix_action?: PredicateFixAction
/** Instruction for an AI rewrite of the query, set when a query edit would help. */
ai_fix_prompt?: string
/** A deterministic query edit that unblocks the index. */
quickfix?: PredicateQuickfix
start?: integer
end?: integer
}
export interface HogQLMetadataColumn {
/** Output column name, in the same order as the SELECT list. */
name: string
/** Inferred runtime type, including nullability. Unknown means inference could not determine the type; execution remains authoritative. */
type: string
}
export interface HogQLMetadataResponse {
query?: string
isValid?: boolean
/** The validator raised an internal error, such as a database failure, so the errors do not prove that the query is invalid. */
internalError?: boolean
isUsingIndices?: QueryIndexUsage
/** One entry per property filter, in query order. */
index_usage?: PredicateIndexUsage[]
errors: HogQLNotice[]
warnings: HogQLNotice[]
notices: HogQLNotice[]
query_status?: never
table_names?: string[]
ch_table_names?: string[]
/** Best-effort output schema, without executing the query. Only included when includeOutputTypes is requested and inference succeeds. */
output_columns?: HogQLMetadataColumn[]
}
export type AutocompleteCompletionItemKind =
| 'Method'
| 'Function'
| 'Constructor'
| 'Field'
| 'Variable'
| 'Class'
| 'Struct'
| 'Interface'
| 'Module'
| 'Property'
| 'Event'
| 'Operator'
| 'Unit'
| 'Value'
| 'Constant'
| 'Enum'
| 'EnumMember'
| 'Keyword'
| 'Text'
| 'Color'
| 'File'
| 'Reference'
| 'Customcolor'
| 'Folder'
| 'TypeParameter'
| 'User'
| 'Issue'
| 'Snippet'
export interface AutocompleteCompletionItem {
/**
* The label of this completion item. By default
* this is also the text that is inserted when selecting
* this completion.
*/
label: string
/**
* A human-readable string that represents a doc-comment.
*/
documentation?: string
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*/
detail?: string
/**
* A string or snippet that should be inserted in a document when selecting
* this completion.
*/
insertText: string
/**
* The kind of this completion item. Based on the kind
* an icon is chosen by the editor.
*/
kind: AutocompleteCompletionItemKind
/**
* Overrides the editor's default ordering for this item. Set when the backend can rank a
* suggestion, for example a function whose return type fits the comparison being written.
*/
sortText?: string
}
export interface HogQLAutocompleteResponse {
suggestions: AutocompleteCompletionItem[]
/** Whether or not the suggestions returned are complete */
incomplete_list: boolean
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[]
query_status?: never
}
export enum HogLanguage {
hog = 'hog',
hogJson = 'hogJson',
hogQL = 'hogQL',
hogQLExpr = 'hogQLExpr',
hogTemplate = 'hogTemplate',
liquid = 'liquid',
}
export interface HogQLMetadata extends DataNode<HogQLMetadataResponse> {
kind: NodeKind.HogQLMetadata
/** Language to validate */
language: HogLanguage
/** Query to validate */
query: string
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string
/** Query within which "expr" and "template" are validated. Defaults to "select * from events" */
sourceQuery?: AnyDataNode
/** Extra globals for the query */
globals?: Record<string, any>
/** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */
filters?: HogQLFilters
/** Variables to be subsituted into the query */
variables?: Record<string, HogQLVariable>
/** Enable more verbose output, usually run from the /debug page */
debug?: boolean
/** Analyze how each property filter reads its data. Costs a second type-resolution pass, so only editors that render the result should ask for it. */
indexUsage?: boolean
/** Validate on the Python validator with freshly fetched sources, the same sources query execution uses. Adds a sources fetch on every request, so only set it where the result blocks an action. */
freshSources?: boolean
/** Infer output column names and types without executing the query. Adds a type-resolution pass, so callers must opt in. */
includeOutputTypes?: boolean
}
export interface HogQLAutocomplete extends DataNode<HogQLAutocompleteResponse> {
kind: NodeKind.HogQLAutocomplete
/** Language to validate */
language: HogLanguage
/** Query to validate */
query: string
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string
/** Query in whose context to validate. */
sourceQuery?: AnyDataNode
/** Global values in scope */
globals?: Record<string, any>
/** Table to validate the expression against */
filters?: HogQLFilters
/**
* Start position of the editor word
*/
startPosition: integer
/**
* End position of the editor word
*/
endPosition: integer
}
export type MathType =
| BaseMathType
| FunnelMathType
| PropertyMathType
| CountPerActorMathType
| GroupMathType
| HogQLMathType
| ExperimentMetricMathType
| CalendarHeatmapMathType
export interface EntityNode extends Node {
name?: string
custom_name?: string
math?: MathType
math_multiplier?: number
math_property?: string
math_property_type?: string
math_property_revenue_currency?: RevenueCurrencyPropertyConfig
math_hogql?: string
math_group_type_index?: 0 | 1 | 2 | 3 | 4
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
/** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
fixedProperties?: AnyPropertyFilter[]
optionalInFunnel?: boolean
}
export interface EventsNode extends EntityNode {
kind: NodeKind.EventsNode
/** The event or `null` for all events. */
event?: string | null
limit?: integer
/** Columns to order by */
orderBy?: string[]
}
export interface DataWarehouseNode extends EntityNode {
id: string
kind: NodeKind.DataWarehouseNode
id_field: string
table_name: string
timestamp_field: string
distinct_id_field: string
dw_source_type?: string
}
export interface FunnelsDataWarehouseNode extends EntityNode {
id: string
kind: NodeKind.FunnelsDataWarehouseNode
id_field: string
table_name: string
timestamp_field: string
aggregation_target_field: string
dw_source_type?: string
}
export interface LifecycleDataWarehouseNode extends EntityNode {
id: string
kind: NodeKind.LifecycleDataWarehouseNode
table_name: string
timestamp_field: string
aggregation_target_field: string
created_at_field: string
}
export interface ActionsNode extends EntityNode {
kind: NodeKind.ActionsNode
id: integer
}
// NOTE: attaching `@discriminator` here breaks ts-json-schema-generator on the generic
// alias ("multiple definitions") — per-query `*SeriesNodeUnion` aliases carry the tag instead.
export type AnyEntityNode<WarehouseNode = DataWarehouseNode> = EventsNode | ActionsNode | WarehouseNode
export type AnyDataWarehouseNode = DataWarehouseNode | FunnelsDataWarehouseNode | LifecycleDataWarehouseNode
export interface GroupNode<WarehouseNode = DataWarehouseNode> extends EntityNode {
kind: NodeKind.GroupNode
/** Group of entities combined with AND/OR operator */
operator: FilterLogicalOperator
/** Entities to combine in this group */
nodes: AnyEntityNode<WarehouseNode>[]
limit?: integer
/** Columns to order by */
orderBy?: string[]
}
export interface QueryTiming {
/** Key. Shortened to 'k' to save on data. */
k: string
/** Time in seconds. Shortened to 't' to save on data. */
t: number
}
export interface EventsQueryResponse extends AnalyticsQueryResponseBase {
results: any[][]
columns: any[]
types: string[]
hogql: string
hasMore?: boolean
limit?: integer
offset?: integer
/** Cursor for fetching the next page of results */
nextCursor?: string
}
export type CachedEventsQueryResponse = CachedQueryResponse<EventsQueryResponse>
export interface EventsQueryPersonColumn {
uuid: string
created_at: string
properties: {
name?: string
email?: string
}
distinct_id: string
}
/** An action step definition for matching events without a saved action */
export interface EventsQueryActionStep {
event?: string | null
properties?: AnyPropertyFilter[]
selector?: string | null
tag_name?: string | null
text?: string | null
text_matching?: 'contains' | 'exact' | 'regex' | null
href?: string | null
href_matching?: 'contains' | 'exact' | 'regex' | null
url?: string | null
url_matching?: 'contains' | 'exact' | 'regex' | null
}
export interface EventsQuery extends DataNode<EventsQueryResponse> {
kind: NodeKind.EventsQuery
/** source for querying events for insights */
source?: InsightActorsQuery
/** Return a limited set of data. Required. */
select: HogQLExpression[]
/** HogQL filters to apply on returned data */
where?: HogQLExpression[]
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
/** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
fixedProperties?: AnyFilterLike[]
/** Filter test accounts */
filterTestAccounts?: boolean
/** Limit to events matching this string */
event?: string | null
/** Filter to events matching any of these event names */
events?: string[] | null
/**
* Number of rows to return
*/
limit?: integer
/**
* Number of rows to skip before returning rows
*/
offset?: integer
/**
* Show events matching a given action
*/
actionId?: integer
/** Show events matching action steps directly, used when no actionId is provided (e.g. previewing unsaved actions). Ignored if actionId is set. */
actionSteps?: EventsQueryActionStep[]
/** Show events for a given person */
personId?: string
/** Only fetch events that happened before this timestamp */
before?: string
/** Only fetch events that happened after this timestamp */
after?: string
/** Columns to order by */
orderBy?: string[]
}
export interface SessionsQueryResponse extends AnalyticsQueryResponseBase {
results: any[][]
columns: any[]
types: string[]
hogql: string
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedSessionsQueryResponse = CachedQueryResponse<SessionsQueryResponse>
export interface SessionsQuery extends DataNode<SessionsQueryResponse> {
kind: NodeKind.SessionsQuery
/** Return a limited set of data. Required. */
select: HogQLExpression[]
/** HogQL filters to apply on returned data */
where?: HogQLExpression[]
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
/** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
fixedProperties?: AnyFilterLike[]
/** Filter test accounts */
filterTestAccounts?: boolean
/**
* Number of rows to return
*/
limit?: integer
/**
* Number of rows to skip before returning rows
*/
offset?: integer
/** Show sessions for a given person */
personId?: string
/** Only fetch sessions that started before this timestamp */
before?: string
/** Only fetch sessions that started after this timestamp */
after?: string
/** Columns to order by */
orderBy?: string[]
/** Filter sessions by event name - sessions that contain this event */
event?: string | null
/**
* Filter sessions by action - sessions that contain events matching this action
*/
actionId?: integer
/** Event property filters - filters sessions that contain events matching these properties */
eventProperties?: AnyPropertyFilter[]
}
/**
* @deprecated Use `ActorsQuery` instead.
*/
export interface PersonsNode extends DataNode {
kind: NodeKind.PersonsNode
search?: string
cohort?: integer
distinctId?: string
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
/** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
fixedProperties?: AnyPropertyFilter[]
limit?: integer
offset?: integer
}
// Data table node
export type HasPropertiesNode = EventsNode | EventsQuery | PersonsNode
// Named separately from `DataTableNodeSource` so the JSDoc `@discriminator` tag
// can attach without tripping ts-json-schema-generator's dedup (same workaround
// pattern as `FunnelsQuerySeriesNodeUnion = FunnelsQuerySeriesNode`). The alias is
// the public type — callers continue to use `DataTableNodeSource`.
/**
* @discriminator kind
*/
export type DataTableNodeSourceUnion =
| EventsNode
| EventsQuery
| PersonsNode
| ActorsQuery
| GroupsQuery
| HogQLQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
| WebBotsTableQuery
| WebGoalsQuery
| WebVitalsQuery
| WebVitalsPathBreakdownQuery
| SessionAttributionExplorerQuery
| SessionsQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| ErrorTrackingQuery
| ErrorTrackingIssueCorrelationQuery
| TracesQuery
| TraceQuery
| SessionQuery
| EndpointsUsageTableQuery
| AccountsQuery
| AccountsTableQuery
export type DataTableNodeSource = DataTableNodeSourceUnion
export interface DataTableNode
extends
Node<
NonNullable<
(
| EventsNode
| EventsQuery
| PersonsNode
| ActorsQuery
| GroupsQuery
| HogQLQuery
| WebOverviewQuery
| WebStatsTableQuery
| WebExternalClicksTableQuery
| WebBotsTableQuery
| WebGoalsQuery
| WebVitalsQuery
| WebVitalsPathBreakdownQuery
| SessionAttributionExplorerQuery
| SessionsQuery
| MarketingAnalyticsTableQuery
| MarketingAnalyticsAggregatedQuery
| ErrorTrackingQuery
| ErrorTrackingIssueCorrelationQuery
| TracesQuery
| SessionQuery
| EndpointsUsageTableQuery
| AccountsQuery
| AccountsTableQuery
)['response']
>
>,
DataTableNodeViewProps {
kind: NodeKind.DataTableNode
/** Source of the events */
source: DataTableNodeSource
/** Columns shown in the table, unless the `source` provides them. */
columns?: HogQLExpression[]
/** Columns that aren't shown in the table, even if in columns or returned data */
hiddenColumns?: HogQLExpression[]
/** Columns that are sticky when scrolling horizontally */
pinnedColumns?: HogQLExpression[]
tags?: QueryLogTags
}
export interface GoalLine {
label: string
value: number
borderColor?: string
displayLabel?: boolean
displayIfCrossed?: boolean
position?: 'start' | 'end'
/** Recalculate from returned chart marks. An absent calculation uses the fixed value. */
calculation?: 'fixed' | 'mean' | 'median' | 'min' | 'max'
/** SQL chart calculations use the primary axis, across all series or separately per series. */
scope?: 'all' | 'series'
}
export interface ChartAxis {
column: string
settings?: {
formatting?: ChartSettingsFormatting
display?: ChartSettingsDisplay
}
}
export interface ChartSettingsFormatting {
prefix?: string
suffix?: string
style?: 'none' | 'number' | 'short' | 'percent'
decimalPlaces?: number
}
export interface ChartSettingsDisplay {
color?: string
label?: string
description?: string
trendLine?: boolean
yAxisPosition?: 'left' | 'right'
displayType?: 'auto' | 'line' | 'bar' | 'area'
/** Keep this series out of the tooltip's total row, e.g. a target line over stacked bars. */
excludeFromTotal?: boolean
/** Overrides the chart's "Show values on series" for this series. Unset or 'auto' follows the chart setting. */
valueLabels?: 'auto' | 'show' | 'hide'
}
export interface HeatmapGradientStop {
value: number
color: string
}
export enum HeatmapSortOrder {
Asc = 'asc',
Desc = 'desc',
}
export interface HeatmapSettings {
xAxisColumn?: string
yAxisColumn?: string
valueColumn?: string
xAxisLabel?: string
yAxisLabel?: string
nullLabel?: string
nullValue?: string
gradient?: HeatmapGradientStop[]
gradientPreset?: string
gradientScaleMode?: 'absolute' | 'relative'
sortColumn?: string
sortOrder?: HeatmapSortOrder
}
export interface PieChartSettings {
/** What to render on each slice. Defaults to values. */
sliceContent?: 'labels' | 'values' | 'none'
/** Whether slice values show as absolute amounts or shares of the total. Only applies when
* `sliceContent` is `values`. */
valueDisplay?: 'absolute' | 'percentage'
/** Whether to show the aggregation total. Defaults to on only when slices show values. */
showTotal?: boolean
}
export interface ScatterChartSettings {
/** X-axis scale. A `logarithmic` axis can't place a non-positive value, so those points are dropped. */
xScale?: 'linear' | 'logarithmic'
/** Whether the X axis should start at zero. Off by default, because pinning either axis of two
* independent measures to zero squashes the correlation into a corner. */
xStartAtZero?: boolean
/** Whether to draw a least-squares fit line through each series' points. */
showBestFit?: boolean
}
export interface MetricChartSettings {
/** Which value the resting headline shows: the latest point, the total, or the average of the returned points.
* @default latest */
summary?: 'total' | 'average' | 'latest'
/** Show the change pill comparing the first point to the latest point.
* @default true */
showChange?: boolean
/** Change pill color when the series went up. Defaults to green. */
changeIncreaseColor?: string
/** Change pill color when the series went down. Defaults to red. */
changeDecreaseColor?: string
/** Color the sparkline by whether the series went up or down.
* @default false */
colorByDirection?: boolean
/** Sparkline color when the series went up. Defaults to green. */
lineIncreaseColor?: string
/** Sparkline color when the series went down. Defaults to red. */
lineDecreaseColor?: string
}
export interface BoxPlotSettings {
xAxisColumn?: string | null
seriesColumn?: string | null
minColumn?: string
p25Column?: string
medianColumn?: string
meanColumn?: string
p75Column?: string
maxColumn?: string
excludeOutliers?: boolean
}
export interface YAxisSettings {
label?: string
scale?: 'linear' | 'logarithmic'
/** Whether the Y axis should start at zero */
startAtZero?: boolean
showGridLines?: boolean
showTicks?: boolean
}
export interface ChartSettings {
xAxis?: ChartAxis
xAxisLabel?: string
xAxisDateFormat?: string
xAxisTickRotation?: number
yAxis?: ChartAxis[]
goalLines?: GoalLine[]
/** Deprecated: use `[left|right]YAxisSettings`. Whether the Y axis should start at zero */
yAxisAtZero?: boolean
leftYAxisSettings?: YAxisSettings
rightYAxisSettings?: YAxisSettings
/** Whether we fill the bars to 100% in stacked mode */
stackBars100?: boolean
seriesBreakdownColumn?: string | null
showXAxisTicks?: boolean
showXAxisBorder?: boolean
showYAxisBorder?: boolean
showLegend?: boolean
showAnnotations?: boolean
/** Shows only the annotations saved at this level. Unset shows every level. */
annotationsScope?: AnnotationScope
/** Where the legend sits relative to the chart. Unset falls back per chart type: right for pie and donut, bottom for proportion bar, top for the rest. */
legendPosition?: 'top' | 'bottom' | 'left' | 'right'
showValuesOnSeries?: boolean
valueLabelPosition?: 'end' | 'center'
valueLabelBackground?: boolean
valueLabelFontSize?: number
valueLabelRotation?: number
barGap?: number
// Deprecated: superseded by `pie.showTotal`. Retained so pre-existing pie-chart insights still
// validate (ChartSettings is `extra="forbid"`). Read as a fallback in the pie chart components.
showPieTotal?: boolean
showTotalRow?: boolean
showNullsAsZero?: boolean
heatmap?: HeatmapSettings
pie?: PieChartSettings
scatter?: ScatterChartSettings
boxPlot?: BoxPlotSettings
metric?: MetricChartSettings
/** Per-breakdown-value color customizations. Keyed by the raw breakdown column value. */
resultCustomizations?: Record<string, ResultCustomizationByValue>
/** Chart rendering style overrides (line shape). Only applies to line and area charts. */
chartStyle?: ChartStyle
}
export interface ConditionalFormattingRule {
id: string
templateId: string
columnName: string
bytecode: any[]
input: string
color: string
colorMode?: 'light' | 'dark'
}
export interface TableSettings {
columns?: ChartAxis[]
conditionalFormatting?: ConditionalFormattingRule[]
pinnedColumns?: string[]
transpose?: boolean
}
export interface SharingConfigurationSettings {
whitelabel?: boolean
theme?: 'light' | 'dark' | 'system'
// Insights
noHeader?: boolean
legend?: boolean
detailed?: boolean
hideExtraDetails?: boolean
// Recordings
showInspector?: boolean
}
export interface DataVisualizationNode extends Node<never> {
kind: NodeKind.DataVisualizationNode
source: HogQLQuery
display?: ChartDisplayType
chartSettings?: ChartSettings
tableSettings?: TableSettings
}
export type VisualizationNode = DataVisualizationNode | BIVisualizationNode
export type DataTableNodeViewPropsContextType = 'event_definition' | 'team_columns'
export interface DataTableNodeViewPropsContext {
type: DataTableNodeViewPropsContextType
eventDefinitionId?: string
}
interface DataTableNodeViewProps {
/** Show with most visual options enabled. Used in scenes. */ full?: boolean
/** Include an event filter above the table (EventsNode only) */
showEventFilter?: boolean
/** Include an events filter above the table to filter by multiple events (EventsQuery only) */
showEventsFilter?: boolean
/** Include a free text search field (PersonsNode only) */
showSearch?: boolean
/** Include a property filter above the table */
showPropertyFilter?: boolean | TaxonomicFilterGroupType[]
/** Show filter to exclude test accounts */
showTestAccountFilters?: boolean
/** Include a HogQL query editor above HogQL tables */
showHogQLEditor?: boolean
/** Show the kebab menu at the end of the row */
showActions?: boolean
/** Show a recording column for events with session recordings */
showRecordingColumn?: boolean
/** Show date range selector */
showDateRange?: boolean
/** Show the export button */
showExport?: boolean
/** Show a reload button */
showReload?: boolean
/** Show count of total and filtered results */
showCount?: boolean
/** Show the time it takes to run a query */
showElapsedTime?: boolean
/** Show a detailed query timing breakdown */
showTimings?: boolean
/** Show a button to configure the table's columns if possible */
showColumnConfigurator?: boolean
/** Show a button to configure and persist the table's default columns if possible */
showPersistentColumnConfigurator?: boolean
/** Context key for universal column configuration (e.g., "survey:123") */
contextKey?: string
/** Shows a list of saved queries */
showSavedQueries?: boolean
/** Show saved filters feature for this table (requires uniqueKey) */
showSavedFilters?: boolean
/** Show table views feature for this table (requires uniqueKey) */
showTableViews?: boolean
/** Render date-time columns (timestamp, created_at, last_seen, last_seen_at, session_start,
* session_end) as absolute date+time instead of relative ("X ago"). The toggle is exposed
* in the column header menu only on EventsQuery / ActorsQuery sources. */
showAbsoluteTime?: boolean
/** Can expand row to show raw event data (default: true) */
expandable?: boolean
/** Link properties via the URL (default: false) */
propertiesViaUrl?: boolean
/** Can the user click on column headers to sort the table? (default: true) */
allowSorting?: boolean
/** Show a button to open the current query as a new insight. (default: true) */
showOpenEditorButton?: boolean
/** Show a results table */
showResultsTable?: boolean
/** Show actors query options and back to source */
showSourceQueryOptions?: boolean
/** Uses the embedded version of LemonTable */
embedded?: boolean
/** Context for the table, used by components like ColumnConfigurator */
context?: DataTableNodeViewPropsContext
/** Default columns to use when resetting column configuration */
defaultColumns?: string[]
}
// Saved insight node
export interface SavedInsightNode extends Node<never>, InsightVizNodeViewProps, DataTableNodeViewProps {
kind: NodeKind.SavedInsightNode
shortId: InsightShortId
}
// Insight viz node
/** Chart specific rendering options.
* Use ChartRenderingMetadata for non-serializable values, e.g. onClick handlers
* @see ChartRenderingMetadata
* **/
export interface VizSpecificOptions {
[InsightType.RETENTION]?: {
hideLineGraph?: boolean
hideSizeColumn?: boolean
useSmallLayout?: boolean
}
[ChartDisplayType.ActionsPie]?: {
disableHoverOffset?: boolean
hideAggregation?: boolean
}
}
export interface InsightVizNode<T = InsightQueryNode> extends Node<never>, InsightVizNodeViewProps {
kind: NodeKind.InsightVizNode
source: T
}
interface InsightVizNodeViewProps {
/** Show with most visual options enabled. Used in insight scene. */
full?: boolean
showHeader?: boolean
showTable?: boolean
/** @deprecated Funnel correlation was removed. The value is ignored. */
showCorrelationTable?: boolean
showLastComputation?: boolean
showLastComputationRefresh?: boolean
showFilters?: boolean
showResults?: boolean
/** Query is embedded inside another bordered component */
embedded?: boolean
suppressSessionAnalysisWarning?: boolean
hidePersonsModal?: boolean
hideTooltipOnScroll?: boolean
vizSpecificOptions?: VizSpecificOptions
}
/** Base class for insight query nodes. Should not be used directly. */
export interface InsightsQueryBase<R extends AnalyticsQueryResponseBase> extends Node<R> {
/** Date range for the query */
dateRange?: DateRange
/**
* Exclude internal and test users by applying the respective filters
*
* @default false
*/
filterTestAccounts?: boolean
/**
* Property filters for all series
*
* @default []
*/
properties?: AnyPropertyFilter[] | PropertyGroupFilter
/**
* Groups aggregation
*/
aggregation_group_type_index?: integer | null
/** Sampling rate */
samplingFactor?: number | null
/** Colors used in the insight's visualization */
dataColorTheme?: number | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers
/** Tags that will be added to the Query log comment */
tags?: QueryLogTags
}
export enum ResultCustomizationBy {
Value = 'value',
Position = 'position',
}
export type TrendsFormulaNode = {
formula: string
/** Optional user-defined name for the formula */
custom_name?: string
}
/** Per-insight chart rendering style. Pure presentation — no field changes the computed values.
* Every field is optional; unset fields fall through to the app-level chart defaults. */
export interface ChartStyle {
/** Line interpolation: straight segments or a smoothed curve through the points. */
curve?: 'linear' | 'smooth'
/** How series are told apart: one color per series, or one color at stepped opacities. */
seriesColorMode?: 'palette' | 'opacity'
}
export type TrendsFilter = {
/** @default 1 */
smoothingIntervals?: integer
/** @deprecated Use formulaNodes instead. */
formula?: string
/** @deprecated Use formulaNodes instead. */
formulas?: string[]
/** List of formulas with optional custom names. Takes precedence over formula/formulas if set. */
formulaNodes?: TrendsFormulaNode[]
/** @default ActionsLineGraph */
display?: ChartDisplayType
/** @default false */
showLegend?: boolean
/** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.
* @default bottom */
legendPosition?: 'top' | 'bottom' | 'left' | 'right'
/** @default false */
showAlertThresholdLines?: boolean
breakdown_histogram_bin_count?: number // TODO: fully move into BreakdownFilter
// The aggregation-axis description below is duplicated, intentionally and divergently, on
// `AssistantTrendsFilter` in schema-assistant-queries.ts. The assistant copy is deliberately
// more cautious ("do not use unless absolutely sure") because Max picks formats without explicit
// query context; this copy is more prescriptive because MCP callers know the units up front.
// Keep both in sync when the format set changes, but treat their wording as audience-specific.
/**
* Y-axis value formatter. Picks a human-friendly unit per value at render time without changing the underlying series values.
*
* - `numeric` (default): raw numbers, e.g. `1,234`.
* - `duration`: values are in seconds; rendered as friendly units per value (`45s`, `2m 12s`, `1h 4m`). Use this whenever the series is in seconds (latency, session length, time-to-event) instead of dividing in `formula` to force minutes or hours.
* - `duration_ms`: values are in milliseconds; rendered as friendly units (`850ms`, `1.5s`, `1m 4s`).
* - `percentage`: values are already in the 0-100 range; appends `%`.
* - `percentage_scaled`: values are a 0-1 ratio; multiplied and rendered as `%`.
* - `currency`: values are in the project's base currency (set in project settings, defaults to USD); rendered with that currency symbol. For values pinned to a specific currency regardless of project base (e.g. `$ai_total_cost_usd` is always USD), use `aggregationAxisPrefix` instead.
* - `short`: compact notation for large counts (`1.2K`, `3.4M`).
* @default numeric
*/
aggregationAxisFormat?: AggregationAxisFormat
/** Literal prefix applied to every value (e.g. `$`). Use to pin a unit or currency symbol that does not depend on `aggregationAxisFormat` — for example, when values are denominated in a fixed currency regardless of the project's base currency. Include any trailing space yourself. */
aggregationAxisPrefix?: string
/** Literal suffix applied to every value (e.g. ` req`). Reserve for units that `aggregationAxisFormat` cannot express. Do not use ` mins`, ` s`, ` ms`, `%` etc. — pick the matching `aggregationAxisFormat` instead so the underlying values stay numerically correct for breakdowns, formulas, and alerts. Include any leading space yourself. */
aggregationAxisPostfix?: string
/** Maximum number of decimal places shown. 1 or 2 is usually right for percentages and currency. */
decimalPlaces?: number
minDecimalPlaces?: number
/** Custom label rendered under the X axis. */
xAxisLabel?: string
/** Custom label rendered alongside the Y axis. */
yAxisLabel?: string
/** @default false */
showValuesOnSeries?: boolean
showLabelsOnSeries?: boolean
/** @default false */
showPercentStackView?: boolean
/** On the horizontal bar-value chart, stack a series' breakdown values into a single bar
* instead of rendering one bar per breakdown value.
* @default false */
stackBreakdownValues?: boolean
yAxisScaleType?: 'log10' | 'linear'
/** Y-axis baseline. When false the axis floats to the data range instead of starting at zero.
* Ignored on bar displays (bars always draw from zero), on a logarithmic scale, and while
* showing percentages.
* @default true */
yAxisStartAtZero?: boolean
/** Pins the bottom of the y-axis; unset means automatic. Ignored in the same cases as
* `yAxisStartAtZero`, while it is on, and when not below `yAxisMax`. */
yAxisMin?: number
/** Pins the top of the y-axis; unset means automatic. Ignored in the same cases as
* `yAxisStartAtZero`, and when `yAxisMin` is not below it. */
yAxisMax?: number
/** @default false */
showMultipleYAxes?: boolean
hiddenLegendIndexes?: integer[]
/**
* Wether result datasets are associated by their values or by their order.
* @default value
**/
resultCustomizationBy?: ResultCustomizationBy
/** Customizations for the appearance of result datasets. */
resultCustomizations?:
| Record<string, ResultCustomizationByValue>
| Record<numerical_key, ResultCustomizationByPosition>
/** Goal Lines */
goalLines?: GoalLine[]
showConfidenceIntervals?: boolean
confidenceLevel?: number
showTrendLines?: boolean
showMovingAverage?: boolean
movingAverageIntervals?: number
/** detailed results table */
detailedResultsAggregationType?: 'total' | 'average' | 'median'
/** @default true */
excludeBoxPlotOutliers?: boolean
/** Ignored. Superseded by `dateRange.daysOfWeek`, which excludes the days from the query
* instead of only hiding their buckets. Still accepted so existing API clients keep working.
* @deprecated Use dateRange.daysOfWeek instead.
* @default false */
hideWeekends?: boolean
/** @default true */
showAnnotations?: boolean
/** Render only annotations with this scope. Unset renders every scope. */
annotationsScope?: AnnotationScope
/** Show the period-over-period change pill on the Metric display.
* @default true */
metricShowChange?: boolean
/** Metric display: change pill color when the metric increased. Defaults to green. */
metricChangeIncreaseColor?: string
/** Metric display: change pill color when the metric decreased. Defaults to red. */
metricChangeDecreaseColor?: string
/** Metric display: color the sparkline by whether the metric increased or decreased.
* @default false */
metricColorByDirection?: boolean
/** Metric display: line color when the metric increased. Defaults to green. */
metricLineIncreaseColor?: string
/** Metric display: line color when the metric decreased. Defaults to red. */
metricLineDecreaseColor?: string
/** Metric display: which summary the resting headline shows — the period total, the average,
* or the latest point. Hovering the sparkline always shows the hovered point's value. Also drives
* the change pill: total/average compare against the previous period when "compare to previous"
* is on; latest compares first→last of the series.
* @default total */
metricSummary?: 'total' | 'average' | 'latest'
/** Chart rendering style overrides (line shape). */
chartStyle?: ChartStyle
}
export type CalendarHeatmapFilter = {
/**
* When true and the series math is `dau`/`unique_users`, each user contributes to the
* (day-of-week, hour) bucket of their session's first event only — matching the web overview
* session-start attribution. When false (default), the user contributes to every bucket
* they have any event in. No effect on `total` math (event counts are unchanged either way).
* @default false
*/
bucketBySessionStart?: boolean
}
export const TRENDS_FILTER_PROPERTIES = new Set<keyof TrendsFilter>([
'smoothingIntervals',
'formula',
'display',
'showLegend',
'legendPosition',
'breakdown_histogram_bin_count',
'aggregationAxisFormat',
'aggregationAxisPrefix',
'aggregationAxisPostfix',
'decimalPlaces',
'showValuesOnSeries',
'showLabelsOnSeries',
'showPercentStackView',
'stackBreakdownValues',
'yAxisScaleType',
'yAxisStartAtZero',
'yAxisMin',
'yAxisMax',
'hiddenLegendIndexes',
'excludeBoxPlotOutliers',
'hideWeekends',
'showAnnotations',
'annotationsScope',
'metricShowChange',
'metricChangeIncreaseColor',
'metricChangeDecreaseColor',
'metricColorByDirection',
'metricLineIncreaseColor',
'metricLineDecreaseColor',
'metricSummary',
'chartStyle',
])
export interface BoxPlotDatum {
day: string
label: string
count?: integer
min: number
p25: number
median: number
p75: number
max: number
mean: number
series_index?: integer
series_label?: string
}
export interface TrendsQueryResponse extends AnalyticsQueryResponseBase {
results: Record<string, any>[]
/**
* The name of each action the query's series reference, keyed by action id. A series saved without a `name`
* displays this name, because the query holds only the action's id.
*/
action_names?: Record<string, string>
/** Wether more breakdown values are available. */
hasMore?: boolean
/** @deprecated Box plot data is now returned in results. This field is no longer populated. */
boxplot_data?: BoxPlotDatum[]
}
export type CachedTrendsQueryResponse = CachedQueryResponse<TrendsQueryResponse>
export type ResultCustomizationBase = {
color?: DataColorToken
hidden?: boolean
}
export interface ResultCustomizationByPosition extends ResultCustomizationBase {
assignmentBy: ResultCustomizationBy.Position
}
export interface ResultCustomizationByValue extends ResultCustomizationBase {
customColor?: string
assignmentBy: ResultCustomizationBy.Value
}
export type ResultCustomization = ResultCustomizationByValue | ResultCustomizationByPosition
// Named separately from `TrendsQuerySeriesNode` so the JSDoc `@discriminator` tag
// can attach without tripping ts-json-schema-generator's dedup (same workaround
// pattern as `FunnelsQuerySeriesNodeUnion = FunnelsQuerySeriesNode`). The alias is
// the public type — callers continue to use `TrendsQuerySeriesNode`.
/**
* @discriminator kind
*/
export type TrendsQuerySeriesNodeUnion = EventsNode | ActionsNode | DataWarehouseNode | GroupNode
export type TrendsQuerySeriesNode = TrendsQuerySeriesNodeUnion
export interface MarketingAnalyticsCostFallback {
/** @minItems 1 @maxItems 200 */
series: DataWarehouseNode[]
/** @minItems 1 @maxItems 200 */
sourceIds: string[]
}
export interface TrendsQuery extends InsightsQueryBase<TrendsQueryResponse> {
kind: NodeKind.TrendsQuery
/**
* Granularity of the response. Can be one of `hour`, `day`, `week` or `month`
*
* @default day
*/
interval?: IntervalType
/**
* Events and actions to include
* @maxItems 200
*/
series: TrendsQuerySeriesNode[]
/** Live series for a Marketing cost trend when materialization coverage is incomplete. */
marketingAnalyticsCostFallback?: MarketingAnalyticsCostFallback
/** Properties specific to the trends insight */
trendsFilter?: TrendsFilter
/**
* Properties specific to the calendar heatmap display variant. Only consulted when
* `trendsFilter.display === ChartDisplayType.CalendarHeatmap`; ignored otherwise.
*/
calendarHeatmapFilter?: CalendarHeatmapFilter
/** Breakdown of the events and actions */
breakdownFilter?: BreakdownFilter
/** Compare to date range */
compareFilter?: CompareFilter
/** Whether we should be comparing against a specific conversion goal */
conversionGoal?: WebAnalyticsConversionGoal | null
}
export interface CalendarHeatmapResponse extends AnalyticsQueryResponseBase {
results: EventsHeatMapStructuredResult
/** Wether more breakdown values are available. */
hasMore?: boolean
}
export type CachedCalendarHeatmapQueryResponse = CachedQueryResponse<CalendarHeatmapResponse>
// Two-level alias so the JSDoc `@discriminator` tag survives ts-json-schema-generator's
// dedup — same workaround pattern as `FunnelsQuerySeriesNodeUnion = FunnelsQuerySeriesNode`.
/**
* @discriminator kind
*/
export type CalendarHeatmapQuerySeriesNodeUnion = EventsNode | ActionsNode | DataWarehouseNode
export type CalendarHeatmapQuerySeriesNode = CalendarHeatmapQuerySeriesNodeUnion
export interface CalendarHeatmapQuery extends InsightsQueryBase<CalendarHeatmapResponse> {
kind: NodeKind.CalendarHeatmapQuery
/**
* Granularity of the response. Can be one of `hour`, `day`, `week` or `month`
*
* @default day
*/
interval?: IntervalType
/** Events and actions to include */
series: CalendarHeatmapQuerySeriesNode[]
/** Properties specific to the trends insight */
calendarHeatmapFilter?: CalendarHeatmapFilter
/** Whether we should be comparing against a specific conversion goal */
conversionGoal?: WebAnalyticsConversionGoal | null
}
export interface CompareFilter {
/**
* Whether to compare the current date range to a previous date range.
* @default false
*/
compare?: boolean
/**
* The date range to compare to. The value is a relative date. Examples of relative dates are: `-1y` for 1 year ago, `-14m` for 14 months ago, `-100w` for 100 weeks ago, `-14d` for 14 days ago, `-30h` for 30 hours ago.
*/
compare_to?: string
}
export interface IntegrationFilter {
/** Selected integration source IDs to filter by (e.g., table IDs or source map IDs) */
integrationSourceIds?: string[]
/** Keep rows that no integration reports cost for, such as organic, email or an unmapped source. Defaults to true. */
includeNonIntegrated?: boolean
}
export interface FunnelExclusionSteps {
funnelFromStep: integer
funnelToStep: integer
}
export interface FunnelExclusionEventsNode extends EventsNode, FunnelExclusionSteps {}
export interface FunnelExclusionActionsNode extends ActionsNode, FunnelExclusionSteps {}
/**
* @discriminator kind
*/
export type FunnelExclusion = FunnelExclusionEventsNode | FunnelExclusionActionsNode
export type FunnelsFilter = {
/** @default [] */
exclusions?: FunnelExclusion[]
/** @default vertical */
layout?: FunnelLayout
/** @asType integer */
binCount?: BinCountValue
/** @default first_touch */
breakdownAttributionType?: BreakdownAttributionType
breakdownAttributionValue?: integer
funnelAggregateByHogQL?: string | null
/** For data warehouse based funnel insights when the aggregation target can't be mapped to persons or groups. */
customAggregationTarget?: boolean
/** To select the range of steps for trends & time to convert funnels, 0-indexed */
funnelToStep?: integer
funnelFromStep?: integer
/** @default ordered */
funnelOrderType?: StepOrderValue
/** @default steps */
funnelVizType?: FunnelVizType
/** @default 14 */
funnelWindowInterval?: integer
/** @default day */
funnelWindowIntervalUnit?: FunnelConversionWindowTimeUnit
hiddenLegendBreakdowns?: string[]
/** @default total */
funnelStepReference?: FunnelStepReference
useUdf?: boolean
/** Customizations for the appearance of result datasets. */
resultCustomizations?: Record<string, ResultCustomizationByValue>
/** Goal Lines */
goalLines?: GoalLine[]
/** Display linear regression trend lines on the chart (only for historical trends viz) */
showTrendLines?: boolean
/**
* Whether to show a legend describing the series. The legend only renders when the funnel has
* multiple series. Only applies to historical-trends funnels.
* @default false
*/
showLegend?: boolean
/** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.
* @default bottom */
legendPosition?: 'top' | 'bottom' | 'left' | 'right'
/** @default false */
showValuesOnSeries?: boolean
/** Breakdown table sorting. Format: 'column_key' or '-column_key' (descending) */
breakdownSorting?: string
/**
* Whether to render annotations on the chart. Only applies to historical-trends funnels.
* @default true
*/
showAnnotations?: boolean
/** Render only annotations with this scope. Only applies to historical-trends funnels. */
annotationsScope?: AnnotationScope
/**
* Trends only: hide periods whose conversion window has not fully elapsed yet, so the recent
* tail of the trend isn't dragged down by entrants who still have time to convert.
* @default false
*/
hideIncompleteConversionWindowPeriods?: boolean
/** Chart rendering style overrides (line shape). Only applies to historical-trends funnels. */
chartStyle?: ChartStyle
}
// Named separately from `FunnelsQuerySeriesNode` so the JSDoc `@discriminator` tag
// can attach without tripping ts-json-schema-generator's dedup (same workaround
// pattern as `ExperimentMetricSourceUnion = ExperimentMetricSource`). The alias is
// the public type — callers continue to use `FunnelsQuerySeriesNode`.
/**
* @discriminator kind
*/
export type FunnelsQuerySeriesNodeUnion = EventsNode | ActionsNode | FunnelsDataWarehouseNode | GroupNode
export type FunnelsQuerySeriesNode = FunnelsQuerySeriesNodeUnion
export interface FunnelsQuery extends InsightsQueryBase<FunnelsQueryResponse> {
kind: NodeKind.FunnelsQuery
/** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */
interval?: IntervalType
/** Events and actions to include */
series: FunnelsQuerySeriesNode[]
/** Properties specific to the funnels insight */
funnelsFilter?: FunnelsFilter
/** Breakdown of the events and actions */
breakdownFilter?: BreakdownFilter
/** Compare to date range */
compareFilter?: CompareFilter
}
/** @asType integer */
type BinNumber = number
export type FunnelStepsResults = Record<string, any>[]
export type FunnelStepsBreakdownResults = Record<string, any>[][]
export type FunnelTimeToConvertResults = {
average_conversion_time: number | null
median_conversion_time: number | null
bins: [BinNumber, BinNumber][]
}
export type FunnelTrendsResults = Record<string, any>[]
export interface FunnelsQueryResponse extends AnalyticsQueryResponseBase {
// This is properly FunnelStepsResults | FunnelStepsBreakdownResults | FunnelTimeToConvertResults | FunnelTrendsResults
// but this large of a union doesn't provide any type-safety and causes python mypy issues, so represented as any.
results: any
/** Median total conversion time across all completers, computed breakdown-agnostically for the Steps viz header. */
total_median_conversion_time?: number | null
}
export type CachedFunnelsQueryResponse = CachedQueryResponse<FunnelsQueryResponse>
export type RetentionFilter = {
retentionType?: RetentionType
/** Whether retention is with regard to initial cohort size, or that of the previous period. */
retentionReference?: 'total' | 'previous'
/** @default 8 */
totalIntervals?: integer
minimumOccurrences?: integer
returningEntity?: RetentionEntity
targetEntity?: RetentionEntity
/** @default Day */
period?: RetentionPeriod
cumulative?: boolean
/** @description The time window mode to use for retention calculations */
timeWindowMode?: 'strict_calendar_dates' | '24_hour_windows'
/** @description Custom brackets for retention calculations */
retentionCustomBrackets?: number[]
/** @description The aggregation type to use for retention
* @default count */
aggregationType?: 'count' | 'sum' | 'avg'
/** @description The property to aggregate when aggregationType is sum or avg */
aggregationProperty?: string
/** @description The type of property to aggregate on (event, person or data_warehouse). Defaults to event.
* @default event */
aggregationPropertyType?: 'event' | 'person' | 'data_warehouse'
/** For data warehouse based retention insights when the aggregation target can't be mapped to persons or groups. */
customAggregationTarget?: boolean
//frontend only
meanRetentionCalculation?: 'simple' | 'weighted' | 'none'
/** controls the display of the retention graph */
display?: ChartDisplayType
dashboardDisplay?: RetentionDashboardDisplayType
showTrendLines?: boolean
/** Draw the mean across cohorts as one line on the retention graph. */
showMeanLine?: boolean
/** The selected interval to display across all cohorts (null = show all intervals for each cohort) */
selectedInterval?: integer | null
goalLines?: GoalLine[]
/** @description Starting index used when labeling cohort columns (e.g. 0 for D0/D1/D2, 1 for D1/D2/D3). Display-only — does not affect retention calculations.
* @default 0 */
cohortLabelStartIndex?: integer
/** Chart rendering style overrides (line shape). */
chartStyle?: ChartStyle
}
export interface RetentionValue {
count: number
label?: string
aggregation_value?: number
}
export interface RetentionResult {
values: RetentionValue[]
label: string
/** @format date-time */
date: string
/** Optional breakdown value for retention cohorts */
breakdown_value?: string | number | null
}
export interface RetentionQueryResponse extends AnalyticsQueryResponseBase {
results: RetentionResult[]
}
export type CachedRetentionQueryResponse = CachedQueryResponse<RetentionQueryResponse>
export interface RetentionQuery extends InsightsQueryBase<RetentionQueryResponse> {
kind: NodeKind.RetentionQuery
/** Properties specific to the retention insight */
retentionFilter: RetentionFilter
/** Breakdown of the events and actions */
breakdownFilter?: BreakdownFilter
}
export type PathsLink = {
source: string
target: string
value: number
average_conversion_time: number
}
export interface PathsQueryResponse extends AnalyticsQueryResponseBase {
results: PathsLink[]
}
export type CachedPathsQueryResponse = CachedQueryResponse<PathsQueryResponse>
export type PathsFilter = {
/** @default 50 */
edgeLimit?: integer
pathsHogQLExpression?: string
includeEventTypes?: PathType[]
startPoint?: string
endPoint?: string
pathGroupings?: string[]
excludeEvents?: string[]
/** @default 5 */
stepLimit?: integer
pathReplacements?: boolean
localPathCleaningFilters?: PathCleaningFilter[] | null
/** @asType integer */
minEdgeWeight?: number
/** @asType integer */
maxEdgeWeight?: number
showFullUrls?: boolean
/** Remove the query string from page view URLs, so pages that differ only in query parameters become one path item */
stripQueryString?: boolean
/** Relevant only within actors query */
pathStartKey?: string
/** Relevant only within actors query */
pathEndKey?: string
/** Relevant only within actors query */
pathDropoffKey?: string
}
export type FunnelPathsFilter = {
funnelPathType: FunnelPathType | undefined
funnelSource: FunnelsQuery
funnelStep?: integer
}
export interface PathsQuery extends InsightsQueryBase<PathsQueryResponse> {
kind: NodeKind.PathsQuery
/** Properties specific to the paths insight */
pathsFilter: PathsFilter
/** Used for displaying paths in relation to funnel steps. */
funnelPathsFilter?: FunnelPathsFilter
}
/** A step source defines which events can become path items in a paths v2 query. */
export type PathsV2StepSource = {
/** Name of the event this source matches. */
event: string
/**
* Event property whose value labels the path item, e.g. `$pathname` for pageviews.
* Team path cleaning rules are applied to the value. Without a naming property,
* the event itself is the path item.
*/
namingProperty?: string
}
/** Identity of a journey grid node: the step source's event plus the label value. */
export type PathsV2Item = {
/** Event of the step source this item belongs to. */
event: string
/**
* Label value from the source's naming property, after path cleaning. An empty string when
* the property is missing on the event. Null for sources without a naming property.
*/
label?: string | null
}
/** One row of a journey grid column: a path item and its unique-actor count. */
export type PathsV2Row = {
item: PathsV2Item
/** Unique actors with a journey whose item at this step is this path item. */
count: number
}
/** One journey grid column: the top path items at a step, plus other-row and drop-off counts. */
export type PathsV2Step = {
/** 0-based step index (column) in the journey grid. */
stepIndex: integer
/** Top path items at this step, ordered by unique-actor count descending. */
rows: PathsV2Row[]
/** Unique actors at this step whose path item is beyond the top rows. */
otherCount: number
/** Unique actors whose journey ends at this step. */
dropOffCount: number
}
/** A displayed transition between path items at adjacent journey grid columns. */
export type PathsV2Edge = {
/** 0-based step index of the source column; the target sits at `stepIndex + 1`. */
stepIndex: integer
/** Source path item, or null for the source column's "other" row. */
source: PathsV2Item | null
/** Target path item, or null for the target column's "other" row. */
target: PathsV2Item | null
/** Unique actors with a journey that transitions from source to target between these steps. */
count: number
/**
* Unique actors who transition from source to target at any step of any of their whole
* journeys, the position-free count behind "went source → target at any step". Equals the
* two-step item-strict funnel's converted count. Only set in open mode on edges between two
* named items.
*/
anyStepCount?: number
}
/**
* A concrete anchored chain from the anchor and the unique actors whose single sequence begins with
* exactly these path items. Powers the hover funnel preview over the journey grid.
*/
export type PathsV2Prefix = {
/** The chain's path items in order, starting at the anchor. */
items: PathsV2Item[]
/** Unique actors whose anchored sequence begins with exactly these items. */
count: number
}
export type PathsV2Results = {
steps: PathsV2Step[]
edges: PathsV2Edge[]
/**
* Concrete anchored chains with per-chain unique-actor counts, ordered by descending count. Empty
* in open mode; in anchored mode it carries the counts the hover funnel preview reads per chain.
* Only chains the grid displays in full are carried: chains through the other bucket are omitted,
* so the response never exposes labels the chart hides.
*/
prefixes: PathsV2Prefix[]
}
export interface PathsV2QueryResponse extends AnalyticsQueryResponseBase {
results: PathsV2Results
}
export type CachedPathsV2QueryResponse = CachedQueryResponse<PathsV2QueryResponse>
/** Whether an anchored chart is built around the journeys' start or their end. */
export enum PathsV2AnchorType {
Start = 'start',
End = 'end',
}
/** The start or end point an anchored-mode chart is built around. */
export type PathsV2Anchor = {
/**
* `start` runs each actor's single sequence forward from the anchor item; `end` runs it up to the
* anchor item. Either way the anchor is the grid's single 100% node.
*/
type: PathsV2AnchorType
/** The path item the chart anchors on. Its event must be one of the step sources. */
item: PathsV2Item
}
export type PathsV2Filter = {
/**
* Step sources defining which events can become path items. Defaults to the pageviews
* preset: `$pageview` named by `$pathname`.
* @minItems 1
* @maxItems 20
*/
stepSources?: PathsV2StepSource[]
/**
* Anchor selecting anchored mode. When set, each actor contributes exactly one sequence bounded by
* the conversion window, so every displayed segment equals a plain funnel. Absent selects open
* mode, which splits an actor's events into journeys on the inactivity gap instead.
*/
anchor?: PathsV2Anchor
/**
* Anchored mode's single conversion window W, anchored at the anchor and reused verbatim as the
* emitted funnel's window. Bounds per unit are validated server-side against
* CONVERSION_WINDOW_INTERVAL_BOUNDS, the same funnel conversion window bounds as the gap.
* @asType integer
* @default 30
*/
conversionWindowInterval?: number
/** @default minute */
conversionWindowIntervalUnit?: FunnelConversionWindowTimeUnit
/**
* Number of journey steps (columns) shown.
* @asType integer
* @default 5
* @minimum 2
* @maximum 20
*/
maxSteps?: number
/**
* Number of path item rows per step; items beyond this go into the "other" row.
* @asType integer
* @default 3
* @minimum 1
* @maximum 10
*/
maxRowsPerStep?: number
/**
* Inactivity gap that splits an actor's events into journeys. Bounds per unit are validated
* server-side against CONVERSION_WINDOW_INTERVAL_BOUNDS, the funnel conversion window bounds.
* @asType integer
* @default 30
*/
gapInterval?: number
/** @default minute */
gapIntervalUnit?: FunnelConversionWindowTimeUnit
/**
* Merge immediate repeats of the same path item within a journey.
* @default true
*/
collapseRepeats?: boolean
/**
* Path items dropped from the item universe: events deriving to one of these items are ignored
* as if their event were not a step source, on both the paths side and the "view as funnel" side.
* @maxItems 100
*/
excludedItems?: PathsV2Item[]
/**
* Apply the team's path cleaning rules to naming property values before they become path items.
* @default true
*/
applyTeamPathCleaning?: boolean
/** Path cleaning rules for this insight only, applied after the team's rules. */
localPathCleaningFilters?: PathCleaningFilter[]
}
export interface PathsV2Query extends Omit<
InsightsQueryBase<PathsV2QueryResponse>,
'samplingFactor' | 'aggregation_group_type_index'
> {
kind: NodeKind.PathsV2Query
/** Properties specific to the paths v2 insight */
pathsV2Filter?: PathsV2Filter
}
export type StickinessOperator =
| PropertyOperator.GreaterThanOrEqual
| PropertyOperator.LessThanOrEqual
| PropertyOperator.Exact
export const StickinessComputationModes = {
NonCumulative: 'non_cumulative',
Cumulative: 'cumulative',
} as const
export type StickinessComputationMode = (typeof StickinessComputationModes)[keyof typeof StickinessComputationModes]
export interface StickinessCriteria {
operator: StickinessOperator
value: positive_integer
}
export type StickinessFilter = {
display?: ChartDisplayType
showLegend?: boolean
/** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.
* @default bottom */
legendPosition?: 'top' | 'bottom' | 'left' | 'right'
showValuesOnSeries?: boolean
showMultipleYAxes?: boolean
hiddenLegendIndexes?: integer[]
stickinessCriteria?: StickinessCriteria
computedAs?: StickinessComputationMode
/**
* Whether result datasets are associated by their values or by their order.
* @default value
**/
resultCustomizationBy?: ResultCustomizationBy
/** Customizations for the appearance of result datasets. */
resultCustomizations?:
| Record<string, ResultCustomizationByValue>
| Record<numerical_key, ResultCustomizationByPosition>
/** Chart rendering style overrides (line shape). */
chartStyle?: ChartStyle
}
export const STICKINESS_FILTER_PROPERTIES = new Set<keyof StickinessFilter>([
'display',
'showLegend',
'legendPosition',
'showValuesOnSeries',
'hiddenLegendIndexes',
'chartStyle',
])
export interface StickinessQueryResponse extends AnalyticsQueryResponseBase {
results: Record<string, any>[]
/**
* The name of each action the query's series reference, keyed by action id. A series saved without a `name`
* displays this name, because the query holds only the action's id.
*/
action_names?: Record<string, string>
}
export type CachedStickinessQueryResponse = CachedQueryResponse<StickinessQueryResponse>
// Two-level alias so the JSDoc `@discriminator` tag survives ts-json-schema-generator's
// dedup — same workaround pattern as `FunnelsQuerySeriesNodeUnion = FunnelsQuerySeriesNode`.
/**
* @discriminator kind
*/
export type StickinessQuerySeriesNodeUnion = EventsNode | ActionsNode | DataWarehouseNode
export type StickinessQuerySeriesNode = StickinessQuerySeriesNodeUnion
export interface StickinessQuery extends Omit<
InsightsQueryBase<StickinessQueryResponse>,
'aggregation_group_type_index'
> {
kind: NodeKind.StickinessQuery
/**
* Granularity of the response. Can be one of `hour`, `day`, `week` or `month`
* @default day
*/
interval?: IntervalType
/**
* How many intervals comprise a period. Only used for cohorts, otherwise default 1.
*/
intervalCount?: positive_integer
/**
* Events and actions to include
* @maxItems 200
*/
series: StickinessQuerySeriesNode[]
/** Properties specific to the stickiness insight */
stickinessFilter?: StickinessFilter
/** Compare to date range */
compareFilter?: CompareFilter
}
export type LifecycleFilter = {
showValuesOnSeries?: boolean
/** Append per-band percentage to each value label (e.g. `580 (42%)`). Requires
* `showValuesOnSeries` — on its own it has no visible effect. */
showPercentagesOnSeries?: boolean
toggledLifecycles?: LifecycleToggle[]
/** @default false */
showLegend?: boolean
/** Where the in-chart legend sits relative to the plot. Only applies to the in-chart legend.
* @default bottom */
legendPosition?: 'top' | 'bottom' | 'left' | 'right'
/** @default true */
stacked?: boolean
}
// See posthog/hogql_queries/query_runner.py `ExecutionMode` for details on what the types mean
export type RefreshType =
| 'async'
| 'async_except_on_cache_miss'
| 'blocking'
| 'force_async'
| 'force_blocking'
| 'force_cache'
| 'lazy_async'
/** Query types supported by endpoints. Excludes FunnelsQuery, PathsQuery, and StickinessQuery. */
export type EndpointQueryNode = TrendsQuery | RetentionQuery | LifecycleQuery | WebStatsTableQuery | WebOverviewQuery
export interface EndpointRequest {
name?: string
description?: string
query?: HogQLQuery | EndpointQueryNode
is_active?: boolean
/** How fresh the data should be, in seconds. Controls cache TTL and materialization sync frequency. */
data_freshness_seconds?: integer
/** Whether this endpoint's query results are materialized to S3 */
is_materialized?: boolean
derived_from_insight?: string
/** Target a specific version for updates (optional, defaults to current version) */
version?: integer
/** Per-column bucket function overrides for range variable materialization. Keys are column names, values are bucket keys (hour, day, week, month). */
bucket_overrides?: Record<string, string>
/** Set to true to soft-delete this endpoint */
deleted?: boolean
/** Tag names to associate with this endpoint. Replaces any existing tags. Omit to leave tags untouched. */
tags?: string[]
/**
* Breakdown property names that may be omitted on /run. Omitted ones return data aggregated across all values of
* that breakdown.
*/
optional_breakdown_properties?: string[]
}
/**
* Controls how endpoint results are fetched.
* - `cache` (default): If available, return cached results. Otherwise, either return the materialized results or run the query against raw data, depending on whether the endpoint is materialized.
* - `force`: Forcefully bypass cached results, and either return materialized results or run the query against raw data, depending on whether the endpoint is materialized.
* - `direct`: Only valid for a materialized endpoint. Bypass the materialized results and run the query against raw data.
*/
export type EndpointRefreshMode = 'cache' | 'force' | 'direct'
export interface EndpointRunRequest {
/** Client provided query ID. Can be used to retrieve the status or cancel the query. */
client_query_id?: string
/** @default 'cache' */
refresh?: EndpointRefreshMode
/**
* Variables to parameterize the endpoint query. The key is the variable name and the value is the variable value.
*
* For HogQL endpoints:
* Keys must match a variable `code_name` defined in the query (referenced as `{variables.code_name}`).
* Example: `{"event_name": "$pageview"}`
*
* For non-materialized insight endpoints (e.g. TrendsQuery):
* - `date_from` and `date_to` are built-in variables that filter the date range.
* Example: `{"date_from": "2024-01-01", "date_to": "2024-01-31"}`
*
* For materialized insight endpoints:
* - Use the breakdown property name as the key to filter by breakdown value.
* Example: `{"$browser": "Chrome"}`
* - `date_from`/`date_to` are not supported on materialized insight endpoints.
*
* Unknown variable names will return a 400 error.
*/
variables?: Record<string, any>
/**
* @deprecated Use `variables` instead. Will be removed in a future release.
*
* Override dashboard filters for insight endpoints (TrendsQuery, FunnelsQuery, etc.).
* Not allowed for HogQL endpoints.
*
* For date filtering, use variables: `{"date_from": "2024-01-01", "date_to": "2024-01-31"}`
*/
filters_override?: DashboardFilter
/** Specific endpoint version to execute. If not provided, the latest version is used. */
version?: integer
/**
* Whether to include debug information (such as the executed HogQL) in the response.
* @default false
*/
debug?: boolean
/** Maximum number of results to return. If not provided, returns all results. */
limit?: integer
/** Number of results to skip. Must be used together with limit. Only supported for HogQL endpoints. */
offset?: integer
}
export interface EndpointLastExecutionTimesRequest {
names: string[]
}
export interface QueryRequest {
/** Client provided query ID. Can be used to retrieve the status or cancel the query. */
client_query_id?: string
// Sync the `refresh` description here with the two instances in posthog/api/insight.py
/**
* 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
* - `'lazy_async'` - kick off background calculation, UNLESS there are somewhat fresh results in the cache
* - `'force_blocking'` - calculate synchronously, even if fresh results are already cached
* - `'force_async'` - kick off background calculation, even if fresh results are already cached
* - `'force_cache'` - return cached data or a cache miss; always completes immediately as it never calculates
* Background calculation can be tracked using the `query_status` response field.
* @default 'blocking'
*/
refresh?: RefreshType
/** @deprecated Use `refresh` instead. */
async?: boolean
/**
* Submit a JSON string representing a query for PostHog data analysis,
* for example a HogQL query.
*
* Example payload:
*
* ```
*
* {"query": {"kind": "HogQLQuery", "query": "select * from events limit 100"}}
*
* ```
*
* For more details on HogQL queries,
* see the [PostHog HogQL documentation](/docs/hogql#api-access).
*/
query: QuerySchema
filters_override?: DashboardFilter
variables_override?: Record<string, Record<string, any>>
/**
* Name given to a query. It's used to identify the query in the UI.
* Up to 128 characters for a name.
*/
name?: string
/**
* Limit context for the query. Only 'posthog_ai' is allowed as a client-provided value.
*/
limit_context?: 'posthog_ai' | null
}
export interface QueryUpgradeRequest {
query: QuerySchema
}
export interface QueryUpgradeResponse {
query: QuerySchema
}
/**
* All analytics query responses must inherit from this.
*/
/** A connector-synced data warehouse source referenced by a query. */
export interface DataWarehouseSourceUsage {
/** ExternalDataSource id */
id: string
/** Connector type of the source (e.g. Stripe, Postgres), if known */
source_type?: string
/** Warehouse table name that was referenced */
table_name: string
/** Whether the query read a history table of this source */
uses_history_table?: boolean
}
export interface AnalyticsQueryResponseBase {
results: any
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[]
/** Generated HogQL query. */
hogql?: string
/** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
error?: string
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus
/** The date range used for the query */
resolved_date_range?: ResolvedDateRangeResponse
/** The resolved previous/comparison period date range, when comparing against another period */
resolved_compare_date_range?: ResolvedDateRangeResponse
/**
* 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,
* and a breakdown warning when the query ran without its requested breakdown.
*/
warnings?: (DataWarehouseSyncWarning | AccessControlFilterWarning | BreakdownNotAppliedWarning)[]
/** Connector-synced data warehouse sources referenced by this query, if any. */
used_data_warehouse_sources?: DataWarehouseSourceUsage[]
}
interface CachedQueryResponseMixin {
is_cached: boolean
/** @format date-time */
last_refresh: string
/** @format date-time */
next_allowed_client_refresh: string
/** @format date-time */
cache_target_age?: string
cache_key: string
timezone: string
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus
/** What triggered the calculation of the query, leave empty if user/immediate */
calculation_trigger?: string
query_metadata?: object
/** The rows and time of the run that produced these results, with its analysis once it is stored. */
query_scan?: QueryScanSummary
}
type CachedQueryResponse<T> = T & CachedQueryResponseMixin
export type GenericCachedQueryResponse = CachedQueryResponse<Record<string, any>>
export interface QueryStatusResponse {
query_status: QueryStatus
}
/** @deprecated Only exported for use in test_query_runner.py! Don't use anywhere else. */
export interface TestBasicQueryResponse extends AnalyticsQueryResponseBase {
results: any[]
}
/** @deprecated Only exported for use in test_query_runner.py! Don't use anywhere else. */
export type TestCachedBasicQueryResponse = CachedQueryResponse<TestBasicQueryResponse>
export interface CacheMissResponse {
cache_key: string | null
query_status?: QueryStatus
}
export type ClickhouseQueryProgress = {
bytes_read: integer
rows_read: integer
estimated_rows_total: integer
time_elapsed: integer
active_cpu_time: integer
}
export type QueryStatus = {
id: string
/**
* ONLY async queries use QueryStatus.
* @default true
*/
query_async: true
team_id: integer
insight_id?: integer
dashboard_id?: integer
/**
* If the query failed, this will be set to true.
* More information can be found in the error_message field.
* @default false
*/
error: boolean
/**
* Whether the query is still running. Will be true if the query is complete, even if it errored.
* Either result or error will be set.
* @default false
*/
complete: boolean
/** @default null */
error_message: string | null
/**
* Stable machine-readable code for the error, when known: the DRF exception code, the ClickHouse error name,
* the HogQL error code, or `unhandled_<exception class>` for a failure that no handler classified.
* @default null
*/
error_code: string | null
results?: any
/**
* When was the query execution task picked up by a worker.
* @format date-time
*/
pickup_time?: string
/**
* When was query execution task enqueued.
* @format date-time
*/
start_time?: string
/**
* When did the query execution task finish (whether successfully or not).
* @format date-time
*/
end_time?: string
/** @format date-time */
expiration_time?: string
task_id?: string
query_progress?: ClickhouseQueryProgress
labels?: string[]
bytes_read?: integer
budget_remaining_bytes?: integer
/** Cache key of the run that failed, so clients can ask for its query scan. */
cache_key?: string
query_scan?: QueryScanSummary
}
export interface LifecycleQueryResponse extends AnalyticsQueryResponseBase {
results: Record<string, any>[]
/**
* The name of each action the query's series reference, keyed by action id. A series saved without a `name`
* displays this name, because the query holds only the action's id.
*/
action_names?: Record<string, string>
}
export type CachedLifecycleQueryResponse = CachedQueryResponse<LifecycleQueryResponse>
// Two-level alias so the JSDoc `@discriminator` tag survives ts-json-schema-generator's
// dedup — same workaround pattern as `FunnelsQuerySeriesNodeUnion = FunnelsQuerySeriesNode`.
/**
* @discriminator kind
*/
export type LifecycleQuerySeriesNodeUnion = EventsNode | ActionsNode | LifecycleDataWarehouseNode
export type LifecycleQuerySeriesNode = LifecycleQuerySeriesNodeUnion
export interface LifecycleQuery extends InsightsQueryBase<LifecycleQueryResponse> {
kind: NodeKind.LifecycleQuery
/**
* Granularity of the response. Can be one of `hour`, `day`, `week` or `month`
* @default day
*/
interval?: IntervalType
/** Events and actions to include */
series: LifecycleQuerySeriesNode[]
/** Properties specific to the lifecycle insight */
lifecycleFilter?: LifecycleFilter
/** For data warehouse based lifecycle insights when the aggregation target can't be mapped to persons or groups. */
customAggregationTarget?: boolean
}
export interface ActorsQueryResponse extends AnalyticsQueryResponseBase {
results: any[][]
columns: any[]
types?: string[]
hogql: string
hasMore?: boolean
limit: integer
offset: integer
missing_actors_count?: integer
}
export type CachedActorsQueryResponse = CachedQueryResponse<ActorsQueryResponse>
export interface ActorsQuery extends DataNode<ActorsQueryResponse> {
kind: NodeKind.ActorsQuery
source?:
| InsightActorsQuery
| FunnelsActorsQuery
| ExperimentActorsQuery
| StickinessActorsQuery
| PathsV2ActorsQuery
| AccountUsersQuery
| HogQLQuery
select?: HogQLExpression[]
search?: string
/**
* Exclude persons matching the team's "internal and test account" filters.
* Only person-scoped filters (person properties, cohorts) are applied. Event-scoped
* test account filters have no meaning in a persons query and are ignored.
*/
filterTestAccounts?: boolean
/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */
properties?: AnyPersonScopeFilter[] | PropertyGroupFilterValue
/** Currently only person filters supported. No filters for querying groups. See `filter_conditions()` in actor_strategies.py. */
fixedProperties?: AnyPersonScopeFilter[]
orderBy?: string[]
limit?: integer
offset?: integer
}
export type CachedGroupsQueryResponse = CachedQueryResponse<GroupsQueryResponse>
export interface GroupsQueryResponse extends AnalyticsQueryResponseBase {
results: any[][]
kind: NodeKind.GroupsQuery
columns: any[]
types: string[]
hogql: string
hasMore?: boolean
limit: integer
offset: integer
}
export interface GroupsQuery extends DataNode<GroupsQueryResponse> {
kind: NodeKind.GroupsQuery
select?: HogQLExpression[]
search?: string
properties?: AnyGroupScopeFilter[]
group_type_index: integer
orderBy?: string[]
limit?: integer
offset?: integer
}
export type CachedAccountsQueryResponse = CachedQueryResponse<AccountsQueryResponse>
export interface AccountsQueryResponse extends AnalyticsQueryResponseBase {
results: any[][]
kind: NodeKind.AccountsQuery
columns: any[]
types: string[]
hogql: string
hasMore?: boolean
limit: integer
offset: integer
/** When `metrics` is set on the query, the aggregated values in the same order. */
metricsResults?: (number | null)[]
}
export interface AccountsQuery extends DataNode<AccountsQueryResponse> {
kind: NodeKind.AccountsQuery
select?: HogQLExpression[]
/** Aggregation expressions evaluated against the filtered account set; one value per metric is returned in `metricsResults`. When `metrics` is set without a `select`, the runner skips the regular row fetch and returns only the aggregated values. */
metrics?: HogQLExpression[]
search?: string
tagNames?: string[]
/** Match accounts where any of these user ids actively holds any relationship (CSM, Account executive, or a custom definition). Drives the "My accounts" shortcut (the current user's id) and the shareable "Assigned to" filter — the ids are explicit so a shared URL resolves identically for every viewer. */
assignedToUserIds?: integer[]
/** Match accounts with no active relationship of any definition. */
allRolesUnassigned?: boolean
/** Match accounts with at least one active relationship of any definition. */
assignedOnly?: boolean
/** Optional HogQL boolean expression AND-ed into the WHERE clause. Used by the overview tile click-to-filter affordance. */
filterExpression?: HogQLExpression
/** Include ignored accounts. Ignored accounts are hidden by default. */
includeIgnored?: boolean
orderBy?: string[]
limit?: integer
offset?: integer
}
export enum AccountsTableAccountField {
Name = 'name',
ExternalId = 'external_id',
CreatedAt = 'created_at',
UpdatedAt = 'updated_at',
ChurnedAt = 'churned_at',
IgnoredAt = 'ignored_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
/**
* A typed column that supports server-side sorting.
* @discriminator kind
*/
export type AccountsTableSortableColumn =
| AccountsTableAccountFieldColumn
| AccountsTableTagsColumn
| AccountsTableNoteCountColumn
| AccountsTableRelationshipColumn
| AccountsTableCustomPropertyColumn
export enum AccountsTableSortDirection {
Ascending = 'asc',
Descending = 'desc',
}
export enum AccountsTableAggregation {
Sum = 'sum',
Average = 'avg',
Minimum = 'min',
Maximum = 'max',
Median = 'median',
}
export enum AccountsTableThresholdOperator {
GreaterThan = 'gt',
GreaterThanOrEqual = 'gte',
LessThan = 'lt',
LessThanOrEqual = 'lte',
Equal = 'exact',
NotEqual = 'is_not',
}
export interface AccountsTableCountMetric {
kind: 'count'
}
export interface AccountsTableAggregateMetric {
kind: 'aggregate'
aggregation: AccountsTableAggregation
column: AccountsTableCustomPropertyColumn
scale?: number
}
export interface AccountsTableCountThresholdMetric {
kind: 'count_threshold'
column: AccountsTableCustomPropertyColumn
operator: AccountsTableThresholdOperator
value: number
}
/**
* A typed aggregate evaluated against the filtered account set.
* @discriminator kind
*/
export type AccountsTableMetric =
| AccountsTableCountMetric
| AccountsTableAggregateMetric
| AccountsTableCountThresholdMetric
export interface AccountsTableSort {
column: AccountsTableSortableColumn
direction: AccountsTableSortDirection
}
export interface AccountsTableSearchFilter {
kind: 'search'
query: string
}
export interface AccountsTableTagsFilter {
kind: 'tags'
/** Match accounts carrying any of these tag names. */
tagNames: string[]
}
export interface AccountsTableAssignedToFilter {
kind: 'assigned_to'
/** Match accounts where any listed user actively holds any relationship. */
userIds: integer[]
}
export interface AccountsTableAssignedFilter {
kind: 'assigned'
}
export interface AccountsTableUnassignedFilter {
kind: 'unassigned'
}
export enum AccountsTableRelationshipOperator {
Exact = 'exact',
IsNot = 'is_not',
IsSet = 'is_set',
IsNotSet = 'is_not_set',
}
export interface AccountsTableRelationshipFilter {
kind: 'relationship'
definitionId: string
operator: AccountsTableRelationshipOperator
userIds?: integer[]
}
export interface AccountsTableAccountIdFilter {
kind: 'account_id'
accountId: string
}
export enum AccountsTableAccountFieldOperator {
Exact = 'exact',
IsNot = 'is_not',
Contains = 'icontains',
DoesNotContain = 'not_icontains',
IsSet = 'is_set',
IsNotSet = 'is_not_set',
DateExact = 'is_date_exact',
DateBefore = 'is_date_before',
DateAfter = 'is_date_after',
}
export interface AccountsTableAccountFieldFilter {
kind: 'account_field'
field: AccountsTableAccountField
operator: AccountsTableAccountFieldOperator
values?: string[]
}
export enum AccountsTableCustomPropertyOperator {
Exact = 'exact',
IsNot = 'is_not',
Contains = 'icontains',
DoesNotContain = 'not_icontains',
Regex = 'regex',
NotRegex = 'not_regex',
GreaterThan = 'gt',
GreaterThanOrEqual = 'gte',
LessThan = 'lt',
LessThanOrEqual = 'lte',
IsSet = 'is_set',
IsNotSet = 'is_not_set',
DateExact = 'is_date_exact',
DateBefore = 'is_date_before',
DateAfter = 'is_date_after',
}
export interface AccountsTableCustomPropertyFilter {
kind: 'custom_property'
definitionId: string
operator: AccountsTableCustomPropertyOperator
/** Values interpreted according to the custom property definition's display type. */
values?: (string | number | boolean)[]
}
/**
* A typed filter applied to the Postgres-backed Accounts table.
* @discriminator kind
*/
export type AccountsTableFilter =
| AccountsTableSearchFilter
| AccountsTableTagsFilter
| AccountsTableAssignedToFilter
| AccountsTableAssignedFilter
| AccountsTableUnassignedFilter
| AccountsTableRelationshipFilter
| AccountsTableAccountIdFilter
| AccountsTableAccountFieldFilter
| AccountsTableCustomPropertyFilter
export type AccountsTablePropertyFilter =
| AccountsTableAccountFieldFilter
| AccountsTableRelationshipFilter
| AccountsTableCustomPropertyFilter
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
/** Bare hostname the row's logo is rendered from. Null when no source resolved one. */
logoDomain?: 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 type AccountsTableCustomPropertyDisplayType =
| 'text'
| 'link'
| 'number'
| 'currency'
| 'percent'
| 'date'
| 'datetime'
| 'boolean'
| 'select'
export interface AccountsTableCustomPropertySource {
id: string
}
export interface AccountsTableCustomPropertyOption {
id?: string | null
label: string
color: string
}
export interface AccountsTableCustomPropertyDefinition {
id: string
name: string
description?: string | null
display_type: AccountsTableCustomPropertyDisplayType
is_big_number?: boolean
is_canonical: boolean
has_workflow_reference: boolean
source?: AccountsTableCustomPropertySource | null
options?: AccountsTableCustomPropertyOption[] | null
}
export interface AccountsTableRelationshipDefinition {
id: string
name: string
description?: string | null
is_single_holder?: boolean
is_controlled: boolean
}
/** @discriminator kind */
export type AccountsTableResolvedColumn =
| AccountsTableAccountFieldColumn
| AccountsTableTagsColumn
| AccountsTableNoteCountColumn
| AccountsTableRelationshipColumn
| AccountsTableCustomPropertyColumn
| AccountsTableCustomPropertyHistoryColumn
export interface AccountsTableQueryResponse extends AnalyticsQueryResponseBase {
kind: NodeKind.AccountsTableQuery
results: AccountsTableRow[]
columns?: AccountsTableResolvedColumn[]
customPropertyDefinitions?: AccountsTableCustomPropertyDefinition[]
relationshipDefinitions?: AccountsTableRelationshipDefinition[]
hasMore: boolean
limit: integer
offset: integer
/** Aggregated values in the same order as the requested metrics. */
metricsResults?: (number | null)[]
}
export interface AccountsTableQuery extends DataNode<AccountsTableQueryResponse> {
kind: NodeKind.AccountsTableQuery
/** Include churned accounts. Churned accounts are hidden by default. */
includeChurned?: boolean
/** Include ignored accounts. Ignored accounts are hidden by default. */
includeIgnored?: boolean
/** Columns to load for each account. Account identity fields are always returned. */
columns: AccountsTableColumn[]
useDefaultColumns?: boolean
/** Omit missing definitions and custom-property filters incompatible with their current types. */
ignoreMissingDefinitions?: boolean
/** Filters are combined with AND. Values within tag and assignment filters use OR. */
filters?: AccountsTableFilter[]
/** Nonempty property-filter groups are ORed together; filters within each group use AND. Global filters still apply. */
filterGroups?: AccountsTablePropertyFilter[][]
/** Aggregates to evaluate against the filtered account set. A metrics query skips row loading. */
metrics?: AccountsTableMetric[]
sort?: AccountsTableSort
limit?: positive_integer
offset?: integer
}
/** The persons who use an account. Only valid as an `ActorsQuery` source. */
export interface AccountUsersQuery extends DataNode<ActorsQueryResponse> {
kind: NodeKind.AccountUsersQuery
/** ID of the account whose users to list. */
accountId: string
}
export interface TimelineEntry {
/** Session ID. None means out-of-session events */
sessionId?: string
events: EventType[]
/** Duration of the recording in seconds. */
recording_duration_s?: number
}
export interface SessionsTimelineQueryResponse extends AnalyticsQueryResponseBase {
results: TimelineEntry[]
hasMore?: boolean
}
export type CachedSessionsTimelineQueryResponse = CachedQueryResponse<SessionsTimelineQueryResponse>
export interface SessionsTimelineQuery extends DataNode<SessionsTimelineQueryResponse> {
kind: NodeKind.SessionsTimelineQuery
/** Fetch sessions only for a given person */
personId?: string
/** Only fetch sessions that started after this timestamp (default: '-24h') */
after?: string
/** Only fetch sessions that started before this timestamp (default: '+5s') */
before?: string
}
export type WebAnalyticsPropertyFilter =
| EventPropertyFilter
| PersonPropertyFilter
| SessionPropertyFilter
| CohortPropertyFilter
export type WebAnalyticsPropertyFilters = WebAnalyticsPropertyFilter[]
export type ActionConversionGoal = {
properties?: WebAnalyticsPropertyFilters
actionId: integer
}
export type CustomEventConversionGoal = {
properties?: WebAnalyticsPropertyFilters
customEventName: string
}
export type WebAnalyticsConversionGoal = ActionConversionGoal | CustomEventConversionGoal
export type WebAnalyticsOrderByDirection = 'ASC' | 'DESC'
export enum WebAnalyticsOrderByFields {
Visitors = 'Visitors',
Views = 'Views',
AvgTimeOnPage = 'AvgTimeOnPage',
Clicks = 'Clicks',
BounceRate = 'BounceRate',
AverageScrollPercentage = 'AverageScrollPercentage',
ScrollGt80Percentage = 'ScrollGt80Percentage',
TotalConversions = 'TotalConversions',
UniqueConversions = 'UniqueConversions',
ConversionRate = 'ConversionRate',
ConvertingUsers = 'ConvertingUsers',
RageClicks = 'RageClicks',
DeadClicks = 'DeadClicks',
Errors = 'Errors',
}
export type WebAnalyticsOrderBy = [WebAnalyticsOrderByFields, WebAnalyticsOrderByDirection]
export type WebAnalyticsSampling = {
enabled?: boolean
forceSamplingRate?: SamplingRate
}
export interface WebAnalyticsQueryModifiers {
/** Serve web overview and stats table queries from the dimensional precompute tables when they hold ready data for the whole date range. Falls back to the normal path otherwise. */
useDimensionalTables?: boolean
}
interface WebAnalyticsQueryBase<R extends Record<string, any>> extends DataNode<R> {
/** Per-request switches for how web analytics serves this query. */
webQueryModifiers?: WebAnalyticsQueryModifiers
dateRange?: DateRange
properties: WebAnalyticsPropertyFilters
conversionGoal?: WebAnalyticsConversionGoal | null
compareFilter?: CompareFilter
doPathCleaning?: boolean
/** @deprecated Use samplingFactor instead */
sampling?: WebAnalyticsSampling
/** Sampling rate */
samplingFactor?: number | null
filterTestAccounts?: boolean
/** @deprecated ignored, always treated as disabled */
includeRevenue?: boolean
/** Interval for date range calculation (affects date_to rounding for hour vs day ranges) */
interval?: IntervalType
/** Groups aggregation - not used in Web Analytics but required for type compatibility */
aggregation_group_type_index?: integer | null
/** Colors used in the insight's visualization - not used in Web Analytics but required for type compatibility */
dataColorTheme?: number | null
orderBy?: WebAnalyticsOrderBy
/** @deprecated ignored, always treated as enabled **/
useSessionsTable?: boolean
}
export interface WebOverviewQuery extends WebAnalyticsQueryBase<WebOverviewQueryResponse> {
kind: NodeKind.WebOverviewQuery
/** Opt this specific query into the web_overview_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. **/
useWebAnalyticsPrecompute?: boolean
}
export type WebAnalyticsItemKind = 'unit' | 'duration_s' | 'percentage' | 'currency'
export interface WebAnalyticsItemBase<T> {
key: string
value?: T
previous?: T
kind: WebAnalyticsItemKind
changeFromPreviousPct?: number
isIncreaseBad?: boolean
}
export interface WebOverviewItem extends WebAnalyticsItemBase<number> {}
/** Which read path served a web analytics response. */
export enum WebAnalyticsPreComputeStrategy {
/** Served from the v2 continuously-maintained pre-aggregated tables. */
PreAggregated = 'pre_aggregated',
/** Served from the on-demand lazy precompute tables. */
LazyPrecompute = 'lazy_precompute',
/** Computed live from raw events (no precompute). */
Live = 'live',
}
export interface SamplingRate {
numerator: number
denominator?: number
}
export interface WebOverviewQueryResponse extends AnalyticsQueryResponseBase {
results: WebOverviewItem[]
samplingRate?: SamplingRate
dateFrom?: string
dateTo?: string
preComputeStrategy?: WebAnalyticsPreComputeStrategy
/** Why a live response skipped precompute: the eligibility-gate reason that refused it. Unset when the query was eligible. */
preComputeIneligibleReason?: string
/** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
preComputeStale?: boolean
/** When the oldest precomputed window this response used was computed. Unset for live responses. */
preComputedAt?: string
}
export type CachedWebOverviewQueryResponse = CachedQueryResponse<WebOverviewQueryResponse>
/** One tool's call count within one interval bucket. */
export interface MCPToolCallBreakdownItem {
/** Bucket start as a project-timezone wall clock ("YYYY-MM-DD HH:mm:ss"), never zone-stamped, so
* the client can join it against generated axis keys without reinterpreting it as an instant. */
bucket: string
tool: string
calls: integer
}
export type MCPAnalyticsPropertyFilter = EventPropertyFilter | PersonPropertyFilter | SessionPropertyFilter
export interface MCPToolCallBreakdownQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolCallBreakdownItem[]
}
/** Interval-bucketed call counts per tool, powering the dashboard's "Tool call breakdown" chart. */
export interface MCPToolCallBreakdownQuery extends DataNode<MCPToolCallBreakdownQueryResponse> {
kind: NodeKind.MCPToolCallBreakdownQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */
interval?: IntervalType
}
export type CachedMCPToolCallBreakdownQueryResponse = CachedQueryResponse<MCPToolCallBreakdownQueryResponse>
/** One interval bucket of MCP tool-call activity, split into successful and failed calls. */
export interface MCPToolCallsAndErrorsItem {
/** Bucket start as a project-timezone wall clock ("YYYY-MM-DD HH:mm:ss"), never zone-stamped, so
* the client can join it against generated axis keys without reinterpreting it as an instant. */
bucket: string
successes: integer
errors: integer
}
export interface MCPToolCallsAndErrorsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolCallsAndErrorsItem[]
}
/** Interval-bucketed success/error split powering the dashboard's "Tool calls and errors" chart. */
export interface MCPToolCallsAndErrorsQuery extends DataNode<MCPToolCallsAndErrorsQueryResponse> {
kind: NodeKind.MCPToolCallsAndErrorsQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */
interval?: IntervalType
}
export type CachedMCPToolCallsAndErrorsQueryResponse = CachedQueryResponse<MCPToolCallsAndErrorsQueryResponse>
/** One row of the MCP harness (client) breakdown: a resolved customer label and its activity. */
export interface MCPHarnessBreakdownItem {
/** Customer-facing harness label, e.g. "Claude Agent SDK", "OpenAI Codex", "Cursor", "Other". */
harness: string
total_calls: integer
errors: integer
error_rate_pct: number
sessions: integer
/** Distinct sessions in this harness across all tools, in the same window and filters. The denominator for the tool's session share within the harness. Set only when the query has toolName. */
harness_sessions?: integer
}
export interface MCPHarnessBreakdownQueryResponse extends AnalyticsQueryResponseBase {
results: MCPHarnessBreakdownItem[]
}
/** MCP tool-call activity grouped by the resolved client harness, over $mcp_tool_call events. */
export interface MCPHarnessBreakdownQuery extends DataNode<MCPHarnessBreakdownQueryResponse> {
kind: NodeKind.MCPHarnessBreakdownQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** When set, scope to a single effective tool's new-SDK calls (the per-tool "By harness" table). */
toolName?: string
}
export type CachedMCPHarnessBreakdownQueryResponse = CachedQueryResponse<MCPHarnessBreakdownQueryResponse>
/** One model's share of MCP tool calls. */
export interface MCPModelBreakdownItem {
model: string
total_calls: integer
}
export interface MCPModelBreakdownQueryResponse extends AnalyticsQueryResponseBase {
/** Whether another page of individual model identifiers is available. */
hasMore?: boolean
results: MCPModelBreakdownItem[]
}
/** MCP tool-call activity grouped by captured model identity. */
export interface MCPModelBreakdownQuery extends DataNode<MCPModelBreakdownQueryResponse> {
kind: NodeKind.MCPModelBreakdownQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** Return individual reported models, excluding Unknown, instead of the top-six grouping. */
includeAllModels?: boolean
/**
* Page size when includeAllModels is enabled.
* @minimum 1
* @maximum 100
*/
limit?: integer
/**
* Number of individual models to skip when includeAllModels is enabled.
* @minimum 0
*/
offset?: integer
}
export type CachedMCPModelBreakdownQueryResponse = CachedQueryResponse<MCPModelBreakdownQueryResponse>
/** One MCP protocol revision's share of tool calls. */
export interface MCPProtocolVersionBreakdownItem {
protocol_version: string
/** On the stateless 2026-07-28 revision or later, or the rolling draft. */
is_current: boolean
total_calls: integer
}
export interface MCPProtocolVersionBreakdownQueryResponse extends AnalyticsQueryResponseBase {
results: MCPProtocolVersionBreakdownItem[]
}
/** MCP tool-call activity grouped by negotiated protocol revision. */
export interface MCPProtocolVersionBreakdownQuery extends DataNode<MCPProtocolVersionBreakdownQueryResponse> {
kind: NodeKind.MCPProtocolVersionBreakdownQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPProtocolVersionBreakdownQueryResponse =
CachedQueryResponse<MCPProtocolVersionBreakdownQueryResponse>
/** One row of the per-tool "Top users" table: a user and their activity on a tool. */
export interface MCPToolTopUserItem {
distinct_id: string
/** JSON-encoded person.properties for the most recent call, for display. */
person_properties: string
calls: integer
errors: integer
error_rate_pct: number
/** Resolved harness labels seen for this user, deduped and sorted. */
harnesses: string[]
last_seen: string
}
export interface MCPToolTopUsersQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolTopUserItem[]
}
/** Top users of a single MCP tool over the last 7 days, with server-resolved harness labels. */
export interface MCPToolTopUsersQuery extends DataNode<MCPToolTopUsersQueryResponse> {
kind: NodeKind.MCPToolTopUsersQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolTopUsersQueryResponse = CachedQueryResponse<MCPToolTopUsersQueryResponse>
/** One row of the per-tool "Failures" table: a failure bucket (error type/status) for a tool. */
export interface MCPToolFailureItem {
/** Failure label composed from $mcp_error_type and, when present, $mcp_error_status (e.g. "api_5xx (HTTP 500)"). */
message: string
/** Raw $mcp_error_type bucket ("unknown" when the event carries none) — pass to MCPToolFailureOccurrencesQuery. */
error_type: string
/** Raw $mcp_error_status as a string; empty when the bucket has no HTTP status. */
error_status: string
occurrences: integer
last_seen: string
/** Resolved harness labels seen for this failure, deduped and sorted. */
harnesses: string[]
}
export interface MCPToolFailuresQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolFailureItem[]
}
/** Errored calls of a single MCP tool grouped by error type/status, with server-resolved harness labels. */
export interface MCPToolFailuresQuery extends DataNode<MCPToolFailuresQueryResponse> {
kind: NodeKind.MCPToolFailuresQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolFailuresQueryResponse = CachedQueryResponse<MCPToolFailuresQueryResponse>
/** One individual errored call of a single MCP tool within a failure bucket. */
export interface MCPToolFailureOccurrenceItem {
timestamp: string
distinct_id: string
/** Conversation id: $mcp_session_id, falling back to $session_id; empty when neither is set. */
session_id: string
/** Resolved harness label for the call. */
harness: string
/** JSON-encoded intent payload as reported by the client; empty when absent. */
intent: string
/** Sanitized error message captured on the event; empty when the event predates message capture. */
error_message: string
/** Raw $mcp_error_status as a string; empty when absent. */
error_status: string
}
export interface MCPToolFailureOccurrencesQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolFailureOccurrenceItem[]
}
/** Individual errored calls of a single MCP tool within one failure bucket, newest first. */
export interface MCPToolFailureOccurrencesQuery extends DataNode<MCPToolFailureOccurrencesQueryResponse> {
kind: NodeKind.MCPToolFailureOccurrencesQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
/** Raw $mcp_error_type bucket; "unknown" selects errored events without an error type. */
errorType: string
/** When set, only events with this HTTP status match; when unset, only events without a status match. */
errorStatus?: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolFailureOccurrencesQueryResponse = CachedQueryResponse<MCPToolFailureOccurrencesQueryResponse>
/** Summary scalars for a single MCP tool: activity, latency, reach, and intent coverage. */
export interface MCPToolStatsItem {
calls: integer
errors: integer
p50_ms: number | null
p95_ms: number | null
users: integer
conversations: integer
/** Calls carrying a non-empty intent payload; the coverage denominator is `calls`. */
with_intent: integer
/** Calls to any tool in the same window and filters. The denominator for the tool's call share. */
total_calls: integer
/** Conversations with a call to any tool in the same window and filters. The denominator for the tool's session share. */
total_conversations: integer
}
export interface MCPToolStatsQueryResponse extends AnalyticsQueryResponseBase {
/** Zero or one row; empty when the tool had no calls in the window. */
results: MCPToolStatsItem[]
}
/** Summary scalars and intent coverage for a single MCP tool over the last 7 days. */
export interface MCPToolStatsQuery extends DataNode<MCPToolStatsQueryResponse> {
kind: NodeKind.MCPToolStatsQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolStatsQueryResponse = CachedQueryResponse<MCPToolStatsQueryResponse>
/** One day of activity for a single MCP tool. */
export interface MCPToolDailyStatItem {
day: string
calls: integer
errors: integer
p50: number
p95: number
users: integer
sessions: integer
}
export interface MCPToolDailyStatsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolDailyStatItem[]
}
/** Per-bucket activity series for a single MCP tool over the selected window. */
export interface MCPToolDailyStatsQuery extends DataNode<MCPToolDailyStatsQueryResponse> {
kind: NodeKind.MCPToolDailyStatsQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** Bucket granularity for the series. The frontend passes getDefaultInterval so a sub-day window
* buckets by hour/minute instead of collapsing to a single day point. Defaults to day. */
interval?: IntervalType
}
export type CachedMCPToolDailyStatsQueryResponse = CachedQueryResponse<MCPToolDailyStatsQueryResponse>
/** Per-tool quality metrics for the Tool quality tab table. */
export interface MCPToolQualityRowItem {
tool: string
total_calls: integer
/** Calls in the previous period: the same length of time right before the window, or for a to-date range ("This month") the same part of the previous unit. */
previous_calls: integer
errors: integer
error_rate_pct: number
p50_duration_ms: number
p95_duration_ms: number
p99_duration_ms: number
users: integer
sessions: integer
first_seen: string
last_seen: string
/** Sort key ranking growth relative to volume, so a small tool's spike doesn't outrank a
* large tool's surge. Not a percentage; only meaningful for ordering. */
trend_score: number
/** Errored calls in the previous period. */
previous_errors: integer
/** p95 duration in the previous period, or null when no previous call carried a duration. */
previous_p95_duration_ms: number | null
/** Distinct sessions that called the tool in the previous period. */
previous_sessions: integer
}
export type MCPToolQualitySortColumn =
| 'total_calls'
| 'error_rate_pct'
| 'p50_duration_ms'
| 'p95_duration_ms'
| 'p99_duration_ms'
| 'users'
| 'sessions'
| 'last_seen'
| 'trend_score'
export type MCPToolQualitySortDirection = 'ASC' | 'DESC'
export interface MCPToolQualityRowsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolQualityRowItem[]
/** Number of tools matching the date, category, and search filters. */
totalCount: integer
/** Distinct sessions with any tool call in the window, ignoring category and search filters. The denominator for each row's session share. */
totalSessions: integer
/** The same total for the previous period, the denominator for each row's previous session share. */
previousTotalSessions: integer
}
/** One row per effective MCP tool name, with server-side search, sorting, and pagination. */
export interface MCPToolQualityRowsQuery extends DataNode<MCPToolQualityRowsQueryResponse> {
kind: NodeKind.MCPToolQualityRowsQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */
categories?: string[]
/** Case-insensitive substring search on the effective tool name. */
search?: string
/** Aggregate column used to order tools. Defaults to total_calls. */
sortColumn?: MCPToolQualitySortColumn
/** Sort direction. Defaults to DESC. */
sortDirection?: MCPToolQualitySortDirection
/** Page size. The server defaults to 50 and caps this at 100. */
limit?: integer
/** Number of matching tools to skip. */
offset?: integer
}
export type CachedMCPToolQualityRowsQueryResponse = CachedQueryResponse<MCPToolQualityRowsQueryResponse>
/** One bucket of aggregate activity across tools on the Tool quality tab. */
export interface MCPToolQualityDailyStatItem {
day: string
calls: integer
errors: integer
p50: number
p95: number
p99: number
/** Latency spread for the box plot view. Optional so responses cached before these fields existed still parse. */
min?: number | null
p25?: number | null
mean?: number | null
p75?: number | null
max?: number | null
}
export interface MCPToolQualityDailyStatsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolQualityDailyStatItem[]
}
/** Interval-bucketed activity series for the Tool quality tab (optionally scoped to one tool). */
export interface MCPToolQualityDailyStatsQuery extends DataNode<MCPToolQualityDailyStatsQueryResponse> {
kind: NodeKind.MCPToolQualityDailyStatsQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
/** Bucket granularity; the frontend passes getDefaultInterval. Defaults to day. */
interval?: IntervalType
/** Restrict to these $mcp_tool_category values; empty or omitted means all categories. */
categories?: string[]
/** Restrict to a single $mcp_tool_name; omitted means the aggregate across all tools. */
toolName?: string
}
export type CachedMCPToolQualityDailyStatsQueryResponse = CachedQueryResponse<MCPToolQualityDailyStatsQueryResponse>
/** Call count for one $mcp_tool_category, powering the tab's share-of-usage headline. */
export interface MCPToolCategoryCountItem {
category: string
calls: integer
}
export interface MCPToolCategoryCountsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolCategoryCountItem[]
}
/** Per-category call counts over the window (empty category = uncategorized traffic). */
export interface MCPToolCategoryCountsQuery extends DataNode<MCPToolCategoryCountsQueryResponse> {
kind: NodeKind.MCPToolCategoryCountsQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolCategoryCountsQueryResponse = CachedQueryResponse<MCPToolCategoryCountsQueryResponse>
/** One distinct $mcp_tool_category value seen in the window. */
export interface MCPToolCategoryItem {
category: string
}
export interface MCPToolCategoriesQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolCategoryItem[]
}
/** Distinct $mcp_tool_category values seen in the window, sorted — powers the scope selector. */
export interface MCPToolCategoriesQuery extends DataNode<MCPToolCategoriesQueryResponse> {
kind: NodeKind.MCPToolCategoriesQuery
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolCategoriesQueryResponse = CachedQueryResponse<MCPToolCategoriesQueryResponse>
/** One tool paired with one $mcp_tool_category it was called under. */
export interface MCPToolCategoryMapItem {
tool: string
category: string
}
export interface MCPToolCategoryMapQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolCategoryMapItem[]
}
/**
* Which categories each tool was called under. The intent clustering snapshot is precomputed and
* stores tool names without categories, so this is what lets that tab scope by category. A tool
* recategorised mid-window appears once per category, rather than one row silently winning.
*/
export interface MCPToolCategoryMapQuery extends DataNode<MCPToolCategoryMapQueryResponse> {
kind: NodeKind.MCPToolCategoryMapQuery
dateRange?: DateRange
}
export type CachedMCPToolCategoryMapQueryResponse = CachedQueryResponse<MCPToolCategoryMapQueryResponse>
/** One distinct description seen for a single MCP tool, with the last time it was reported. */
export interface MCPToolDescriptionItem {
description: string
last_seen: string
}
export interface MCPToolDescriptionsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolDescriptionItem[]
}
/** Distinct descriptions reported for a single MCP tool over the last 30 days, most recent first. */
export interface MCPToolDescriptionsQuery extends DataNode<MCPToolDescriptionsQueryResponse> {
kind: NodeKind.MCPToolDescriptionsQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolDescriptionsQueryResponse = CachedQueryResponse<MCPToolDescriptionsQueryResponse>
/** One sampled call of a single MCP tool that carried a non-empty intent. */
export interface MCPToolSampleIntentItem {
timestamp: string
/** JSON-encoded intent payload as reported by the client. */
intent: string
intent_source: string
/** Resolved harness label for the call. */
harness: string
}
export interface MCPToolSampleIntentsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolSampleIntentItem[]
}
/** Recent sampled intents for a single MCP tool over the last 7 days, with a resolved harness label. */
export interface MCPToolSampleIntentsQuery extends DataNode<MCPToolSampleIntentsQueryResponse> {
kind: NodeKind.MCPToolSampleIntentsQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolSampleIntentsQueryResponse = CachedQueryResponse<MCPToolSampleIntentsQueryResponse>
/** One tool frequently called adjacent to the target tool within the same conversation. */
export interface MCPToolNeighborItem {
neighbor_tool: string
co_occurrences: integer
}
export interface MCPToolNeighborsQueryResponse extends AnalyticsQueryResponseBase {
results: MCPToolNeighborItem[]
}
/** Tools most often called immediately before or after a single MCP tool within a conversation. */
export interface MCPToolNeighborsQuery extends DataNode<MCPToolNeighborsQueryResponse> {
kind: NodeKind.MCPToolNeighborsQuery
/** The effective tool name to scope to (matched against the single-exec-resolved tool name). */
toolName: string
/** Whether to count tools called immediately before or after the target tool. */
neighborDirection: 'before' | 'after'
dateRange?: DateRange
properties?: MCPAnalyticsPropertyFilter[]
filterTestAccounts?: boolean
}
export type CachedMCPToolNeighborsQueryResponse = CachedQueryResponse<MCPToolNeighborsQueryResponse>
/** One missing-capability report: a capability an agent asked for and could not get. */
export interface MCPMissingCapabilitiesItem {
timestamp: string
/** The agent's own words for the capability it wanted, from $mcp_intent. */
intent: string
/** Resolved client label, the client's own self-reported name when unrecognized, or
* "Unidentified client" when the report carried no client identity at all. */
harness: string
/** Conversation id: $mcp_session_id, falling back to $session_id; empty when neither is set. */
session_id: string
distinct_id: string
/** JSON-encoded person email/name for display; "{}" when neither resolved. */
person_properties: string
}
export interface MCPMissingCapabilitiesQueryResponse extends AnalyticsQueryResponseBase {
results: MCPMissingCapabilitiesItem[]
/** Whether more reports exist past this page. */
has_next: boolean
}
/** Chronological feed of capabilities that agents asked for but could not access. */
export interface MCPMissingCapabilitiesQuery extends DataNode<MCPMissingCapabilitiesQueryResponse> {
kind: NodeKind.MCPMissingCapabilitiesQuery
dateRange?: DateRange
/** Exclude reports from the project's internal and test users. */
filterTestAccounts?: boolean
/** Case-insensitive substring match over the report text. */
search?: string
/** Page size; defaults to 100, capped at 500. */
limit?: integer
/** Reports to skip before returning results. Combine with limit to page through them;
* the response's has_next flag indicates whether more remain. */
offset?: integer
}
export type CachedMCPMissingCapabilitiesQueryResponse = CachedQueryResponse<MCPMissingCapabilitiesQueryResponse>
export enum WebStatsBreakdown {
Page = 'Page',
InitialPage = 'InitialPage',
ExitPage = 'ExitPage', // not supported in the legacy version
ExitClick = 'ExitClick',
PreviousPage = 'PreviousPage', // $prev_pageview_pathname || $referrer
ScreenName = 'ScreenName',
InitialChannelType = 'InitialChannelType',
InitialReferringDomain = 'InitialReferringDomain',
InitialReferringURL = 'InitialReferringURL',
InitialUTMSource = 'InitialUTMSource',
InitialUTMCampaign = 'InitialUTMCampaign',
InitialUTMMedium = 'InitialUTMMedium',
InitialUTMTerm = 'InitialUTMTerm',
InitialUTMContent = 'InitialUTMContent',
InitialUTMSourceMediumCampaign = 'InitialUTMSourceMediumCampaign',
FirstPageviewChannelType = 'FirstPageviewChannelType',
FirstPageviewReferringDomain = 'FirstPageviewReferringDomain',
FirstPageviewUTMSource = 'FirstPageviewUTMSource',
FirstPageviewUTMCampaign = 'FirstPageviewUTMCampaign',
FirstPageviewUTMMedium = 'FirstPageviewUTMMedium',
FirstPageviewUTMTerm = 'FirstPageviewUTMTerm',
FirstPageviewUTMContent = 'FirstPageviewUTMContent',
FirstPageviewUTMSourceMediumCampaign = 'FirstPageviewUTMSourceMediumCampaign',
Browser = 'Browser',
InAppBrowser = 'InAppBrowser',
OS = 'OS',
Viewport = 'Viewport',
DeviceType = 'DeviceType',
Country = 'Country',
Region = 'Region',
City = 'City',
Timezone = 'Timezone',
Language = 'Language',
FrustrationMetrics = 'FrustrationMetrics',
}
export interface WebStatsTableQuery extends WebAnalyticsQueryBase<WebStatsTableQueryResponse> {
includeTrafficMetrics?: boolean
kind: NodeKind.WebStatsTableQuery
breakdownBy: WebStatsBreakdown
includeScrollDepth?: boolean // automatically sets includeBounceRate to true
includeBounceRate?: boolean
includeAvgTimeOnPage?: boolean
includeHost?: boolean
limit?: integer
offset?: integer
/** Opt this specific query into the web stats table precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. **/
useWebAnalyticsPrecompute?: boolean
}
export interface WebStatsTableQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
types?: unknown[]
columns?: unknown[]
hogql?: string
samplingRate?: SamplingRate
hasMore?: boolean
limit?: integer
offset?: integer
preComputeStrategy?: WebAnalyticsPreComputeStrategy
/** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
preComputeStale?: boolean
/** Why a live response skipped precompute: the eligibility-gate reason that refused it. Unset when the query was eligible. */
preComputeIneligibleReason?: string
/** When the oldest precomputed window this response used was computed. Unset for live responses. */
preComputedAt?: string
}
export type CachedWebStatsTableQueryResponse = CachedQueryResponse<WebStatsTableQueryResponse>
export interface WebExternalClicksTableQuery extends WebAnalyticsQueryBase<WebExternalClicksTableQueryResponse> {
kind: NodeKind.WebExternalClicksTableQuery
limit?: integer
stripQueryParams?: boolean
}
export interface WebExternalClicksTableQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
types?: unknown[]
columns?: unknown[]
hogql?: string
samplingRate?: SamplingRate
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedWebExternalClicksTableQueryResponse = CachedQueryResponse<WebExternalClicksTableQueryResponse>
export enum WebBotsBreakdown {
Crawler = 'Crawler',
Path = 'Path',
}
/** Bot analytics tables: crawler activity broken down by crawler or by most-crawled path. */
export interface WebBotsTableQuery extends WebAnalyticsQueryBase<WebBotsTableQueryResponse> {
kind: NodeKind.WebBotsTableQuery
breakdownBy: WebBotsBreakdown
limit?: integer
}
export interface WebBotsTableQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
types?: unknown[]
columns?: unknown[]
hogql?: string
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedWebBotsTableQueryResponse = CachedQueryResponse<WebBotsTableQueryResponse>
export enum WebAgentAnalyticsQueryType {
Overview = 'overview',
Issues = 'issues',
PageRequests = 'page_requests',
Transitions = 'transitions',
Demand = 'demand',
IssueVariants = 'issue_variants',
RequestAnatomy = 'request_anatomy',
JourneySummary = 'journey_summary',
Journeys = 'journeys',
JourneyDetail = 'journey_detail',
}
export enum WebAgentContentGrouping {
Exact = 'exact',
Normalized = 'normalized',
}
/** Agent traffic summaries and readiness diagnostics derived from web request events. */
export interface WebAgentAnalyticsQuery extends WebAnalyticsQueryBase<WebAgentAnalyticsQueryResponse> {
kind: NodeKind.WebAgentAnalyticsQuery
queryType: WebAgentAnalyticsQueryType
includeCrawlers?: boolean
contentGrouping?: WebAgentContentGrouping
llmsTxtUrl?: string
limit?: integer
offset?: integer
intentKey?: string
/** Opaque journey identifier returned by the journeys list, used to load one journey's timeline. */
journeyKey?: string
}
export interface WebAgentAnalyticsQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
types?: unknown[]
columns?: unknown[]
hogql?: string
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedWebAgentAnalyticsQueryResponse = CachedQueryResponse<WebAgentAnalyticsQueryResponse>
export enum WebPageDirectoryMetric {
Visitors = 'visitors',
GoogleSearch = 'google_search',
AiReferrals = 'ai_referrals',
AiCrawls = 'ai_crawls',
Conversions = 'conversions',
TimeOnPage = 'time_on_page',
BounceRate = 'bounce_rate',
}
export enum WebPageDirectorySortBy {
Page = 'page',
Visitors = 'visitors',
GoogleSearch = 'google_search',
AiReferrals = 'ai_referrals',
AiCrawls = 'ai_crawls',
Conversions = 'conversions',
TimeOnPage = 'time_on_page',
BounceRate = 'bounce_rate',
}
export interface WebPageDirectoryQuery extends WebAnalyticsQueryBase<WebPageDirectoryQueryResponse> {
kind: NodeKind.WebPageDirectoryQuery
search?: string
sortBy?: WebPageDirectorySortBy
sortDirection?: 'ASC' | 'DESC'
metrics?: WebPageDirectoryMetric[]
pageKeys?: string[]
includeSiteTotals?: boolean
excludeStaticAssets?: boolean
limit?: integer
offset?: integer
}
export interface WebPageDirectoryValue {
current: number
previous?: number | null
}
export interface WebPageDirectoryMetrics {
visitors?: WebPageDirectoryValue
googleSearch?: WebPageDirectoryValue
aiReferrals?: WebPageDirectoryValue
aiCrawls?: WebPageDirectoryValue
aiCrawlers?: integer | null
aiCrawlerNames?: string[] | null
conversions?: WebPageDirectoryValue
timeOnPageP90?: number | null
bounceRate?: number | null
}
export interface WebPageDirectoryRow extends WebPageDirectoryMetrics {
page: string
}
export interface WebPageDirectorySiteTotals extends WebPageDirectoryMetrics {
serverLogs: integer
}
export interface WebPageDirectoryQueryResponse extends AnalyticsQueryResponseBase {
results: WebPageDirectoryRow[]
siteTotals?: WebPageDirectorySiteTotals
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedWebPageDirectoryQueryResponse = CachedQueryResponse<WebPageDirectoryQueryResponse>
export interface WebGoalsQuery extends WebAnalyticsQueryBase<WebGoalsQueryResponse> {
kind: NodeKind.WebGoalsQuery
limit?: integer
/** Opt this specific query into the web_goals_query precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. **/
useWebAnalyticsPrecompute?: boolean
}
export interface WebGoalsQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
types?: unknown[]
columns?: unknown[]
hogql?: string
samplingRate?: SamplingRate
hasMore?: boolean
limit?: integer
offset?: integer
preComputeStrategy?: WebAnalyticsPreComputeStrategy
/** Why a live response skipped precompute: the eligibility-gate reason that refused it. Unset when the query was eligible. */
preComputeIneligibleReason?: string
/** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
preComputeStale?: boolean
/** When the oldest precomputed window this response used was computed. Unset for live responses. */
preComputedAt?: string
}
export type CachedWebGoalsQueryResponse = CachedQueryResponse<WebGoalsQueryResponse>
export type WebVitalsMetric = 'INP' | 'LCP' | 'CLS' | 'FCP'
export type WebVitalsPercentile = PropertyMathType.P75 | PropertyMathType.P90 | PropertyMathType.P99
export type WebVitalsMetricBand = 'good' | 'needs_improvements' | 'poor'
export interface WebVitalsQuery<T = InsightQueryNode> extends WebAnalyticsQueryBase<WebGoalsQueryResponse> {
kind: NodeKind.WebVitalsQuery
source: T
}
export interface WebVitalsItemAction {
custom_name: WebVitalsMetric
math: WebVitalsPercentile
}
export interface WebVitalsItem {
data: number[]
days: string[]
/** The index of the row's series in the query. */
order: integer
/**
* @deprecated The runner no longer writes this field. Only responses cached before 2026-10-30 carry it, and it goes
* once those entries expire. Read the series from the query at `order` instead.
*/
action?: WebVitalsItemAction
}
export interface WebVitalsQueryResponse extends AnalyticsQueryResponseBase {
results: WebVitalsItem[]
}
export type CachedWebVitalsQueryResponse = CachedQueryResponse<WebVitalsQueryResponse>
export interface WebVitalsPathBreakdownQuery extends WebAnalyticsQueryBase<WebVitalsPathBreakdownQueryResponse> {
kind: NodeKind.WebVitalsPathBreakdownQuery
percentile: WebVitalsPercentile
metric: WebVitalsMetric
// Threshold for this specific metric, these are stored in the frontend only
// so let's send them back to the backend to be used in the query
// This tuple represents a [good, poor] threshold, where values below good are good and values above poor are poor
// Values in between the two values are the threshold for needs_improvements
thresholds: [number, number]
/** Opt this specific query into the web vitals path breakdown precompute path. Requires the `web-analytics-precompute-toggle` PostHog feature flag to be on for the team's organization for the gate to pass. **/
useWebAnalyticsPrecompute?: boolean
}
export type WebVitalsPathBreakdownResultItem = { path: string; value: number }
export type WebVitalsPathBreakdownResult = Record<WebVitalsMetricBand, WebVitalsPathBreakdownResultItem[]>
// NOTE: The response is an array of results because pydantic requires it, but this will always have a single entry
// hence the tuple type rather than a single object.
export interface WebVitalsPathBreakdownQueryResponse extends AnalyticsQueryResponseBase {
results: [WebVitalsPathBreakdownResult]
preComputeStrategy?: WebAnalyticsPreComputeStrategy
/** Why a live response skipped precompute: the eligibility-gate reason that refused it. Unset when the query was eligible. */
preComputeIneligibleReason?: string
/** Whether a lazy-precompute read was served from expired-within-grace (stale) jobs instead of recomputing inline. */
preComputeStale?: boolean
/** When the oldest precomputed window this response used was computed. Unset for live responses. */
preComputedAt?: string
}
export type CachedWebVitalsPathBreakdownQueryResponse = CachedQueryResponse<WebVitalsPathBreakdownQueryResponse>
export enum SessionAttributionGroupBy {
ChannelType = 'ChannelType',
Medium = 'Medium',
Source = 'Source',
Campaign = 'Campaign',
AdIds = 'AdIds',
ReferringDomain = 'ReferringDomain',
InitialURL = 'InitialURL',
}
export interface SessionAttributionExplorerQuery extends DataNode<SessionAttributionExplorerQueryResponse> {
kind: NodeKind.SessionAttributionExplorerQuery
groupBy: SessionAttributionGroupBy[]
filters?: {
properties?: SessionPropertyFilter[]
dateRange?: DateRange
}
limit?: integer
offset?: integer
}
export interface SessionAttributionExplorerQueryResponse extends AnalyticsQueryResponseBase {
results: unknown
hasMore?: boolean
limit?: integer
offset?: integer
types?: unknown[]
columns?: unknown[]
}
export type CachedSessionAttributionExplorerQueryResponse = CachedQueryResponse<SessionAttributionExplorerQueryResponse>
/* Error Tracking */
/** @title ErrorTrackingOrderBy */
export type ErrorTrackingOrderBy = 'last_seen' | 'first_seen' | 'occurrences' | 'users' | 'sessions' | 'severity'
/** @title ErrorTrackingQueryIssueSeverity */
export type ErrorTrackingQueryIssueSeverity = 'low' | 'medium' | 'high' | 'critical'
/** Client-side pending fingerprint issue state update UNIONed into the argMax subquery to hide Kafka->CH sync lag after mutations. This has to be kept in sync with the CH schema */
export interface ErrorTrackingPendingFingerprintIssueStateUpdate {
fingerprint: string
issue_id: string
issue_name: string | null
issue_description: string | null
issue_status: string
issue_severity: ErrorTrackingQueryIssueSeverity | null
assigned_user_id: integer | null
assigned_role_id: string | null
/** ISO 8601 datetime string. */
first_seen: string
is_deleted: integer
/** Client-stamped monotonic version (`Date.now()` ms at mutation success). */
version: integer
}
export interface ErrorTrackingQuery extends DataNode<ErrorTrackingQueryResponse> {
kind: NodeKind.ErrorTrackingQuery
/** Filter to a specific error tracking issue by ID. */
issueId?: ErrorTrackingIssue['id']
/** Field to sort results by. */
orderBy: ErrorTrackingOrderBy
/** Sort direction. */
orderDirection?: 'ASC' | 'DESC'
/** Date range to filter results. */
dateRange: DateRange
/** Filter by issue status. */
status?: ErrorTrackingQueryStatus
/** Filter by issue severity. */
severity?: ErrorTrackingQueryIssueSeverity | null
assignee?: ErrorTrackingIssueAssignee | null
filterGroup?: PropertyGroupFilter
/** Whether to filter out test accounts. */
filterTestAccounts?: boolean
/** Free-text search across exception type, message, and stack frames. */
searchQuery?: string
volumeResolution: integer
withAggregations?: boolean
withFirstEvent?: boolean
withLastEvent?: boolean
limit?: integer
offset?: integer
personId?: string
groupKey?: string
groupTypeIndex?: integer
/** @deprecated Ignored — V2 query path was removed. Kept so requests from older clients still validate. */
useQueryV2?: boolean
/** @deprecated Ignored — V3 is the only query path. Kept so requests from older clients still validate. */
useQueryV3?: boolean
/**
* Pending fingerprint issue state updates UNIONed into the fingerprint issue state subquery.
* The backend caps the list at 50 entries; extras are dropped silently.
* @type array
*/
pendingFingerprintIssueStateUpdates?: ErrorTrackingPendingFingerprintIssueStateUpdate[]
}
export interface ErrorTrackingSimilarIssuesQuery extends DataNode<ErrorTrackingSimilarIssuesQueryResponse> {
kind: NodeKind.ErrorTrackingSimilarIssuesQuery
issueId: ErrorTrackingIssue['id']
modelName?: EmbeddingModelName
rendering?: string
maxDistance?: number
dateRange?: DateRange
limit?: integer
offset?: integer
}
export interface ErrorTrackingFingerprintProjectionQuery extends DataNode<ErrorTrackingFingerprintProjectionQueryResponse> {
kind: NodeKind.ErrorTrackingFingerprintProjectionQuery
issueId: ErrorTrackingIssue['id']
modelName?: EmbeddingModelName
rendering?: string
}
export interface ErrorTrackingBreakdownsQuery extends DataNode<ErrorTrackingBreakdownsQueryResponse> {
kind: NodeKind.ErrorTrackingBreakdownsQuery
issueId: ErrorTrackingIssue['id']
breakdownProperties: string[]
dateRange?: DateRange
filterGroup?: PropertyGroupFilter
filterTestAccounts?: boolean
maxValuesPerProperty?: integer
}
export type ErrorTrackingReleasesOrderBy = 'latest' | 'occurrences'
export interface ErrorTrackingReleasesQuery extends DataNode<ErrorTrackingReleasesQueryResponse> {
kind: NodeKind.ErrorTrackingReleasesQuery
issueId: ErrorTrackingIssue['id']
dateRange?: DateRange
filterGroup?: PropertyGroupFilter
filterTestAccounts?: boolean
/** Only count exceptions from this app namespace. */
appNamespace?: string
/** How many releases to return on their own; the rest fold into `other`. */
maxReleases?: integer
/** `latest` puts the release that first appeared most recently in the range on top, `occurrences` orders by volume. */
orderBy?: ErrorTrackingReleasesOrderBy
/** Number of time buckets across the date range. */
resolution?: integer
}
export interface ErrorTrackingReleaseSeries {
/** Occurrences per bucket, aligned with the response's `buckets`. */
counts: integer[]
total: integer
first_seen: string | null
last_seen: string | null
}
export interface ErrorTrackingIssueRelease extends ErrorTrackingReleaseSeries {
namespace: string | null
version: string | null
build: string | null
}
export interface ErrorTrackingReleasesQueryResponse extends AnalyticsQueryResponseBase {
/** The releases returned on their own, in the requested order. */
results: ErrorTrackingIssueRelease[]
date_from: string
date_to: string
/** ISO start of each bucket. The first one can start before `date_from`. */
buckets: string[]
bucket_seconds: integer
/** Releases past `maxReleases`, summed. */
other: ErrorTrackingReleaseSeries | null
other_release_count: integer
/** Exceptions without an app namespace or version. */
unattributed: ErrorTrackingReleaseSeries | null
/** Distinct releases in the range for the selected app, before folding. */
release_count: integer
/** Set when the query hit its row cap, so `release_count`, `other` and `total` are lower bounds. */
release_count_truncated: boolean
/** Every app namespace in the range, regardless of `appNamespace`. */
namespaces: string[]
total: integer
}
export type CachedErrorTrackingReleasesQueryResponse = CachedQueryResponse<ErrorTrackingReleasesQueryResponse>
export interface ErrorTrackingIssueCorrelationQuery extends DataNode<ErrorTrackingIssueCorrelationQueryResponse> {
kind: NodeKind.ErrorTrackingIssueCorrelationQuery
events: string[]
}
export interface ErrorTrackingIssueCorrelationQueryResponse extends AnalyticsQueryResponseBase {
results: ErrorTrackingCorrelatedIssue[]
hasMore?: boolean
limit?: integer
offset?: integer
columns?: string[]
}
export type CachedErrorTrackingIssueCorrelationQueryResponse =
CachedQueryResponse<ErrorTrackingIssueCorrelationQueryResponse>
/** The exceptions of one issue, optionally only the ones with a recording. */
export interface ErrorTrackingIssueEventsQuery extends DataNode<ErrorTrackingIssueEventsQueryResponse> {
kind: NodeKind.ErrorTrackingIssueEventsQuery
issueId: string
/** The issue's exceptions list. It must order by `timestamp DESC`, the default, so that pages continue from a cursor. */
source: EventsQuery
/** Keep only the exceptions whose session has a recording the player can open. */
onlyWithRecording?: boolean
}
export interface ErrorTrackingIssueEventsQueryResponse extends AnalyticsQueryResponseBase {
results: any[][]
columns: any[]
types: string[]
hasMore?: boolean
/** Where the next page starts. */
nextCursor?: string
}
export type CachedErrorTrackingIssueEventsQueryResponse = CachedQueryResponse<ErrorTrackingIssueEventsQueryResponse>
export interface ErrorTrackingIssueFilteringToolOutput extends Pick<
ErrorTrackingQuery,
'orderBy' | 'orderDirection' | 'status' | 'searchQuery'
> {
newFilters?: AnyPropertyFilter[]
removedFilterIndexes?: integer[]
dateRange?: DateRange
filterTestAccounts?: boolean
}
export interface ErrorTrackingIssueImpactToolOutput {
events: string[]
}
export type ErrorTrackingIssueAssigneeType = 'user' | 'role'
export interface ErrorTrackingIssueAssignee {
type: ErrorTrackingIssueAssigneeType
id: integer | string
}
export interface ErrorTrackingIssueAggregations {
occurrences: number
sessions: number
users: number
volumeRange?: number[] // Deprecated
volume_buckets: { label: string; value: number }[]
}
export type ErrorTrackingExternalReferenceIntegration = Pick<IntegrationType, 'id' | 'kind' | 'display_name'>
export interface ErrorTrackingExternalReference {
id: string
external_url: string
external_id: string
title: string
integration: ErrorTrackingExternalReferenceIntegration
}
export interface ErrorTrackingIssueCohort {
id: number
name: string
}
export type QuickFilterType = 'manual-options' | 'auto-discovery'
export enum QuickFilterContext {
Dashboards = 'dashboards',
ErrorTrackingIssueFilters = 'error-tracking-issue-filters',
LogsFilters = 'logs-filters',
}
/** @title ErrorTrackingIssueStatus */
export type ErrorTrackingIssueStatus = 'archived' | 'active' | 'resolved' | 'pending_release' | 'suppressed'
/** @title ErrorTrackingQueryStatus */
export type ErrorTrackingQueryStatus = ErrorTrackingIssueStatus | 'all'
export interface ErrorTrackingRelationalIssue {
id: string
name: string | null
description: string | null
assignee: ErrorTrackingIssueAssignee | null
status: ErrorTrackingIssueStatus
severity?: ErrorTrackingQueryIssueSeverity | null
/** @format date-time */
first_seen: string
external_issues?: ErrorTrackingExternalReference[]
cohort?: ErrorTrackingIssueCohort
}
export type ErrorTrackingIssue = ErrorTrackingRelationalIssue & {
/** @format date-time */
last_seen: string
source?: string
function?: string
first_event?: {
uuid: string
distinct_id: string
timestamp: string
properties: string
}
last_event?: {
uuid: string
distinct_id: string
timestamp: string
properties: string
}
aggregations?: ErrorTrackingIssueAggregations
library: string | null
}
export type ErrorTrackingCorrelatedIssue = ErrorTrackingRelationalIssue & {
/** @format date-time */
last_seen: string
library: string | null
event: string
odds_ratio: number
population: {
both: number
success_only: number
exception_only: number
neither: number
}
}
export interface ErrorTrackingQueryResponse extends AnalyticsQueryResponseBase {
results: ErrorTrackingIssue[]
hasMore?: boolean
limit?: integer
offset?: integer
columns?: string[]
}
export type CachedErrorTrackingQueryResponse = CachedQueryResponse<ErrorTrackingQueryResponse>
export type SimilarIssue = {
id: string
name: string
description: string
library: string | null
status: string
first_seen: string
distance: number
}
export type BreakdownValue = {
value: string
count: number
}
export interface ErrorTrackingSimilarIssuesQueryResponse extends AnalyticsQueryResponseBase {
results: SimilarIssue[]
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedErrorTrackingSimilarIssuesQueryResponse = CachedQueryResponse<ErrorTrackingSimilarIssuesQueryResponse>
export interface ErrorTrackingFingerprintProjectionPoint {
fingerprint: string
x: number
y: number
}
export interface ErrorTrackingFingerprintProjectionQueryResponse extends AnalyticsQueryResponseBase {
results: ErrorTrackingFingerprintProjectionPoint[]
hasMore?: boolean
}
export type CachedErrorTrackingFingerprintProjectionQueryResponse =
CachedQueryResponse<ErrorTrackingFingerprintProjectionQueryResponse>
export interface ErrorTrackingBreakdownsQueryResponse extends AnalyticsQueryResponseBase {
results: Record<string, { values: BreakdownValue[]; total_count: number }>
}
export type CachedErrorTrackingBreakdownsQueryResponse = CachedQueryResponse<ErrorTrackingBreakdownsQueryResponse>
export type EmbeddingModelName = 'text-embedding-3-small-1536' | 'text-embedding-3-large-3072'
export interface DocumentSimilarityQuery extends DataNode<DocumentSimilarityQueryResponse> {
// Query metadata
kind: NodeKind.DocumentSimilarityQuery
// Standard
dateRange: DateRange
order_direction: 'asc' | 'desc'
order_by: 'distance' | 'timestamp'
limit?: integer
offset?: integer
// Embedding-specifics
// To what point are all distances being measured?
origin: EmbeddedDocument // | string -- TODO, we should support ad-hoc querying too, but it requires a modification of the cross join
distance_func: 'L1Distance' | 'L2Distance' | 'cosineDistance' // How is the distance being measured?
threshold?: number // Some distance under-or-over which results will be excluded - useful mainly if sorting by timestamp
model: string // Model to do the query with. Only documents embedded with this model will be considered.
// TODO - these are a hack, and we should expose them as proper HogQL filterables instead, but
// I don't want to go to war in the taxonomic filter mines right now
products: string[] // Limit the results to specific products. Empty means all.
document_types: string[] // Limit the results to specific document types. Empty means all.
renderings: string[] // Limit the results to specific renderings. Empty means all.
}
// A single embedded document, which is a collection of all the ways
// the document has been embedded, across different models and renderings
export interface EmbeddedDocument {
product: string
document_type: string
document_id: string
/** @format date-time */
timestamp: string
}
// A specific embedding of a document, with a specific model and rendering
export type EmbeddingRecord = EmbeddedDocument & {
model_name: EmbeddingModelName
rendering: string
}
export interface EmbeddingDistance {
result: EmbeddingRecord
origin?: EmbeddingRecord
distance: number // How far was this particular embedding from the query
}
export interface DocumentSimilarityQueryResponse extends AnalyticsQueryResponseBase {
results: EmbeddingDistance[]
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedDocumentSimilarityQueryResponse = CachedQueryResponse<DocumentSimilarityQueryResponse>
export type LogSeverityLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'fatal'
export interface LogMessage {
uuid: string
trace_id: string
span_id: string
body: string
attributes: Record<string, any>
/** @format date-time */
timestamp: string
/** @format date-time */
observed_timestamp: string
severity_text: LogSeverityLevel
severity_number: number
level: LogSeverityLevel
resource_attributes: any
instrumentation_scope: string
event_name: string
/** @format date-time */
live_logs_checkpoint?: string
new?: boolean
}
/** Field to break down sparkline data by */
export type LogsSparklineBreakdownBy = 'severity' | 'service'
/** Metric the sparkline ranks breakdown values by before collapsing the tail into an "other" bucket */
export type LogsSparklineRankBy = 'count' | 'bytes'
/** @title LogsOrderBy */
export type LogsOrderBy = 'latest' | 'earliest'
/** Columns the trace list can be ordered by (allowlisted — fed straight into `ORDER BY`). */
export type TraceOrderColumn = 'timestamp' | 'duration'
/**
* Filter criteria for a logs alert configuration. Subset of LogsViewerFilters
* (excludes dateRange). At least one of `severityLevels`, `serviceNames`, or
* `filterGroup` must be set on a live (enabled=true) alert.
*/
export interface LogsAlertFilters {
severityLevels?: LogSeverityLevel[]
serviceNames?: string[]
filterGroup?: PropertyGroupFilter
}
export interface LogsQuery extends DataNode<LogsQueryResponse> {
kind: NodeKind.LogsQuery
dateRange: DateRange
limit?: integer
offset?: integer
orderBy?: LogsOrderBy
searchTerm?: string
severityLevels: LogSeverityLevel[]
filterGroup: PropertyGroupFilter
serviceNames: string[]
liveLogsCheckpoint?: string
/** Cursor for fetching the next page of results */
after?: string
/** Field to break down sparkline data by (used only by sparkline endpoint) */
sparklineBreakdownBy?: LogsSparklineBreakdownBy
/**
* Metric used to rank breakdown values before the tail is collapsed into a single "other"
* bucket, so the returned row count stays bounded (used only by sparkline endpoint).
* Defaults to ranking by log count.
*/
sparklineRankBy?: LogsSparklineRankBy
resourceFingerprint?: string
/** Omit the per-log `attributes` and `resource_attributes` maps from results to keep payloads compact */
excludeAttributes?: boolean
/** Show logs for a given person */
personId?: string
/** Show logs for a given session ID */
sessionId?: string
/**
* Custom column expressions evaluated per log row. Each entry is either a source-prefixed
* shorthand (`attributes.<key>`, `resource_attributes.<key>`, `body.<json.path>`) or a scalar
* HogQL expression (`upper(level)`, `coalesce(attributes['a'], attributes['b'])`).
* Values come back on each result row keyed by the aliases in `LogsQueryResponse.columns`.
*/
customColumns?: string[]
}
export interface LogsQueryResponse extends AnalyticsQueryResponseBase {
results: unknown // TODO: Type this to LogMessage[] and fix the issues it creates on the backend
hasMore?: boolean
limit?: integer
offset?: integer
columns?: string[]
/** Cursor for fetching the next page of results */
nextCursor?: string
}
export interface LogAttributesQuery extends DataNode<LogAttributesQueryResponse> {
kind: NodeKind.LogAttributesQuery
dateRange?: DateRange
limit?: integer
offset?: integer
search?: string
/** When true, the search query also matches attribute values (not just keys). */
searchValues?: boolean
severityLevels?: LogSeverityLevel[]
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
attributeType: string
/** Return only attribute keys that exactly match an entry in this list. */
attributeKeys?: string[]
}
export interface LogAttributeResult {
name: string
/** Either 'log_attribute' or 'log_resource_attribute'. */
propertyFilterType: string
/** Whether this row matched the search by attribute key or by attribute value. */
matchedOn: 'key' | 'value'
/** Sample value that matched the search — only set when matchedOn is 'value'. */
matchedValue?: string
}
export interface LogAttributesQueryResponse extends AnalyticsQueryResponseBase {
results: LogAttributeResult[]
count: number
}
export interface LogValueResult {
id: string
name: string
/** Number of log records with this attribute value, over the current date range, service, and resource filters. */
count?: integer
}
export interface LogValuesQueryResponse extends AnalyticsQueryResponseBase {
results: LogValueResult[]
}
export interface LogValuesQuery extends DataNode<LogValuesQueryResponse> {
kind: NodeKind.LogValuesQuery
dateRange?: DateRange
limit?: integer
offset?: integer
search?: string
severityLevels?: LogSeverityLevel[]
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
attributeKey: string
attributeType: string
}
/** Which attribute map a metric label key lives in; `auto` resolves resource attributes first, then datapoint attributes. */
export type MetricsAttributeScope = 'resource' | 'attribute' | 'auto'
export type MetricsFilterOp = 'eq' | 'neq' | 'regex' | 'not_regex'
/** OTel metric type; matches what ingest writes to `metric_type` */
export type MetricsOtelType = 'gauge' | 'sum' | 'histogram' | 'exponential_histogram' | 'summary'
export type MetricsAggregation =
| 'sum'
| 'avg'
| 'count'
| 'min'
| 'max'
| 'quantile'
| 'rate'
| 'increase'
| 'histogram_quantile'
/** Counter-aware transform applied to each series before any aggregation */
export type MetricsRangeFunction = 'rate' | 'increase'
export interface MetricsQueryFilter {
key: string
op: MetricsFilterOp
value: string
scope?: MetricsAttributeScope
}
/** Where a metrics dashboard variable gets its options. */
export type MetricsDashboardVariableSource = 'custom' | 'promql' | 'sql' | 'textbox'
export interface MetricsDashboardVariableSelection {
/** The selected values. Empty when `all` is true: All stands for every option of the variable. */
values: string[]
all?: boolean
}
/** The value of one variable in a metrics query, set from the dashboard that shows the query. */
export interface MetricsVariableValue {
values: string[]
/** True when the variable is set to All. PromQL gets `allValue` or `.*`, builder filters drop the
* filter, and SQL gets every option of the variable. */
all?: boolean
allValue?: string | null
/** The definition of a variable set to All, so that a SQL query can load its options. */
definition?: MetricsDashboardVariable | null
}
/** A Grafana-style dashboard variable. Metrics tiles refer to it as `$name`, `${name}` or `${name:format}`. */
export interface MetricsDashboardVariable {
/** Letters, digits and underscores. Tiles refer to it as `$name`. */
name: string
/** Shown in the dashboard filter bar. The name is shown when it is empty. */
label?: string | null
source: MetricsDashboardVariableSource
/** The options when `source` is `custom`. */
customValues?: string[] | null
/** The options query when `source` is `promql` or `sql`. It can refer to other variables.
* PromQL supports `label_values(label)`, `label_values(selector, label)`, `label_names()`,
* `metrics(regex)` and `query_result(expr)`. SQL returns the options in its first column. */
query?: string | null
/** RE2 pattern that options must match. When it has a capture group, the option is the first group. */
regex?: string | null
multi?: boolean | null
includeAll?: boolean | null
/** The text that All puts in a PromQL query. `.*` when it is empty. */
allValue?: string | null
current?: MetricsDashboardVariableSelection | null
}
export interface MetricsQueryGroupBy {
key: string
scope?: MetricsAttributeScope
}
export interface MetricsQueryClause {
/** Alias a formula refers to (e.g. "a"); must be unique within the query */
name: string
metricName: string
/** Omit to get one line per series (at most 100), without combining them */
aggregation?: MetricsAggregation
/** Applied to each series before `aggregation`, like `rate()` in PromQL */
rangeFunction?: MetricsRangeFunction
/** Series identity includes the OTel type — one name can exist as e.g. both a
* counter and a gauge — so a clause pins it to avoid blending distinct series. */
metricType?: MetricsOtelType
filters?: MetricsQueryFilter[]
groupBy?: MetricsQueryGroupBy[]
/** In (0, 1); required for `quantile` / `histogram_quantile` aggregations */
quantile?: number
}
export interface MetricsQueryPoint {
/** Bucket start, ISO 8601 */
time: string
/** The bucket's aggregate; null when it isn't representable (a gap). */
value: number | null
}
export interface MetricsQuerySeries {
/** Label values identifying this series; empty for an ungrouped query */
labels: Record<string, string>
points: MetricsQueryPoint[]
metricName?: string
/** Clause alias that produced this series (`formula` for the formula result) */
clause?: string
/** UCUM unit of the returned values, e.g. "By", "ms", "1/s". It is the ingested unit, except that a count of series has no unit and a rate is per second. Empty when the values have no unit. */
unit?: string
/** Bucket upper edges a histogram quantile series was estimated from. The true quantile can be anywhere between two edges. */
histogramBounds?: number[]
}
export interface MetricsQueryResponse extends AnalyticsQueryResponseBase {
results: MetricsQuerySeries[]
}
export type CachedMetricsQueryResponse = CachedQueryResponse<MetricsQueryResponse>
/** Histogram bucket counts per time bucket, for a latency-over-time heatmap. A separate node
* from `MetricsQuery` because the response is a grid, not series — a display type must not
* change what the runner reads (the cache key excludes display). */
export interface MetricsHistogramQuery extends DataNode<MetricsHistogramQueryResponse> {
kind: NodeKind.MetricsHistogramQuery
metricName: string
/** Pins the OTel type, as on a MetricsQuery clause: one name can exist as more than one
* type, and the heatmap must grid only the distribution series. */
metricType?: MetricsOtelType
filters?: MetricsQueryFilter[]
/** Defaults to the last 24 hours when omitted; dashboard date filters override it */
dateRange?: DateRange
/** Bucket size; auto-picked from the range when omitted. A dashboard variable reference such as `$window`
* pins the interval to its single duration value (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w).
* Variable intervals that exceed 500 buckets require a larger value or shorter date range. */
interval?: string
/** UCUM unit for the y-axis bounds, e.g. "s", "ms". Presentation only. */
unit?: string
/** Values of the dashboard variables that the filters or interval refer to as `$name`. */
variables?: Record<string, MetricsVariableValue>
}
export interface MetricsHistogramQueryResponse extends AnalyticsQueryResponseBase {
/** The grid lives in `times`/`bounds`/`counts`; the base `results` array is unused and the
* runner returns it as null. */
/** Bucket start per column (x axis), ISO 8601, ascending. */
times: string[]
/** Upper bound per row (y axis), ascending. */
bounds: number[]
/** Observation count per cell: counts[row][column], row = bound, column = time. */
counts: number[][]
}
export type CachedMetricsHistogramQueryResponse = CachedQueryResponse<MetricsHistogramQueryResponse>
/** How a metrics result is charted. `stat` is a single headline value plus sparkline, not a time series. */
export type MetricsDisplayType = 'line' | 'area' | 'bar' | 'stat' | 'gauge' | 'bargauge' | 'table' | 'heatmap'
/** Matches quill's `YAxisConfig.scale` verbatim, so no vocabulary translation is needed.
* Deliberately not `YAxisSettings['scale']` ('logarithmic') or `TrendsFilter['yAxisScaleType']` ('log10'). */
export type MetricsAxisScale = 'linear' | 'log'
/** Which summary the `stat` display's headline value shows.
* @deprecated Use `MetricsDisplaySettings.reduce`. Kept so saved insights keep working. */
export type MetricsStatSummary = 'latest' | 'average' | 'total'
/** How a series collapses to one number for the scalar panels and legend calcs. */
export type MetricsReducer = 'last' | 'mean' | 'min' | 'max' | 'sum' | 'delta'
/** A threshold band: `color` applies from `value` up to the next step. */
export interface MetricsThreshold {
/** Lower bound of this band. The lowest step is the base color below every other step. */
value: number
/** A named color token (e.g. "green", "red"), never raw hex, so light and dark themes both work. */
color: string
}
/** How a null bucket renders on a time-series chart. */
export type MetricsNullMode = 'gap' | 'zero' | 'connect'
export interface MetricsYAxisSettings {
/** @default linear */
scale?: MetricsAxisScale
/** When false the axis floats to the data range instead of starting at zero. Ignored on a
* logarithmic scale, and on the bar display, where a bar's length encodes magnitude from zero.
* @default true */
startAtZero?: boolean
/** Pins the bottom of the axis; unset means automatic. Ignored while `startAtZero` is on. */
min?: number
/** Pins the top of the axis; unset means automatic. Pinning both ends drops the automatic
* stretch that keeps an off-scale goal line on-plot. */
max?: number
}
/** Presentation only. The query engine never reads this, and it's stripped from the result cache
* key, so changing any of it re-renders without re-running the query. */
export interface MetricsDisplaySettings {
/** @default line */
type?: MetricsDisplayType
goalLines?: GoalLine[]
yAxis?: MetricsYAxisSettings
/** `stat` display only: which summary the headline value shows.
* @default latest
* @deprecated Use `reduce`. */
statSummary?: MetricsStatSummary
/** How scalar panels and legend calcs collapse a series to one number.
* @default last */
reduce?: MetricsReducer
/** UCUM unit string as OTel writes it, e.g. "By", "ms", "%". Defaults from the response unit. */
unit?: string
/** Color bands for the scalar panels. Sorted by `value` at read time, so entry order does not matter. */
thresholds?: MetricsThreshold[]
/** How a null bucket renders on a time-series chart.
* @default gap */
nullMode?: MetricsNullMode
/** Time-series panels only: which reducers the legend table shows. Empty means no legend calcs. */
legendCalcs?: MetricsReducer[]
}
/** How a metrics query is written. All three run through the metrics query runner, with its caching and limits. */
export type MetricsQueryLanguage = 'builder' | 'promql' | 'sql'
export interface MetricsQuery extends DataNode<MetricsQueryResponse> {
kind: NodeKind.MetricsQuery
/** Empty when `language` is `promql` or `sql`. */
clauses: MetricsQueryClause[]
/** How the query is written; the builder when unset. */
language?: MetricsQueryLanguage
/** PromQL expression, run as a range query. Used when `language` is `promql`. */
promql?: string
/** HogQL SELECT over the posthog.metric* tables. Used when `language` is `sql`. It must return a `time` and a
* `value` column; every other column is a series label. `{date_from}`, `{date_to}`, `{interval}` and
* `{interval_seconds}` are filled in from the date range and interval. */
sql?: string
/** Defaults to the last 24 hours when omitted; dashboard date filters override it */
dateRange?: DateRange
/** Bucket size, one of: second_15, second_30, minute, minute_5, minute_15, minute_30, hour, hour_6, day, week;
* auto-picked from the range when omitted. Fixed intervals are coarsened above 500 buckets.
* A dashboard variable reference such as `$window` pins the interval to its single duration value
* (15s, 30s, 1m, 5m, 15m, 30m, 1h, 6h, 1d, 1w). Variable intervals that exceed 500 buckets require
* a larger value or shorter date range, so the step stays consistent with PromQL lookbacks using that variable. */
interval?: string
/** Arithmetic over clause aliases (e.g. "a / b"); when set, only the formula series are returned */
formula?: string
/** Chart presentation. A node without it renders as a line chart. */
display?: MetricsDisplaySettings
/** Values of the dashboard variables that the PromQL, SQL, filters or interval refer to as `$name`. */
variables?: Record<string, MetricsVariableValue>
}
export interface SessionEventsItem {
/** Session ID these events belong to */
session_id: string
/** List of events for this session, each event is a list of field values matching the query columns */
events: [][]
}
export interface SessionBatchEventsQuery
extends Omit<EventsQuery, 'kind' | 'response'>, DataNode<SessionBatchEventsQueryResponse> {
kind: NodeKind.SessionBatchEventsQuery
/** Whether to group results by session_id in the response */
group_by_session?: boolean
/** List of session IDs to fetch events for. Will be translated to $session_id IN filter. */
session_ids: string[]
response?: SessionBatchEventsQueryResponse
}
export interface SessionBatchEventsQueryResponse extends EventsQueryResponse {
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus
results: any[][]
/** Events grouped by session ID. Only populated when group_by_session=True. */
session_events?: SessionEventsItem[]
/** List of session IDs that had no matching events */
sessions_with_no_events?: string[]
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[]
}
export type CachedSessionBatchEventsQueryResponse = CachedEventsQueryResponse & {
/** Query status indicates whether next to the provided data, a query is still running. */
query_status?: QueryStatus
results: any[][]
/** Events grouped by session ID. Only populated when group_by_session=True. */
session_events?: SessionEventsItem[]
/** List of session IDs that had no matching events */
sessions_with_no_events?: string[]
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[]
}
export type CachedLogsQueryResponse = CachedQueryResponse<LogsQueryResponse>
export interface TraceSpansQuery extends DataNode<TraceSpansQueryResponse> {
kind: NodeKind.TraceSpansQuery
dateRange?: DateRange
limit?: integer
offset?: integer
/** Column to order by. Defaults to timestamp. `timestamp` paginates via keyset cursor (`after`); other columns via `offset`. */
orderBy?: TraceOrderColumn
/** Order direction. Defaults to DESC. */
orderDirection?: 'ASC' | 'DESC'
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
statusCodes?: integer[]
traceId?: string
rootSpans?: boolean
/**
* Return the matching spans themselves, one row per span (root and child), instead of the
* whole-trace grouping. Streams the matches under `ORDER BY … LIMIT` rather than grouping every
* matching span by trace, so a filter on a hot child attribute (e.g. `code.filepath`) stays
* bounded. Distinct from `rootSpans`, which scopes whole-trace selection. The single-trace
* waterfall never sets this.
*/
flatSpans?: boolean
/** Cursor for fetching the next page of results */
after?: string
/** Prefetch up to this many spans per trace and include them in results */
prefetchSpans?: integer
/** Omit the per-span `attributes` map from results to keep payloads compact */
excludeAttributes?: boolean
}
export interface TraceSpansQueryResponse extends AnalyticsQueryResponseBase {
results: unknown
hasMore?: boolean
limit?: integer
offset?: integer
/** Cursor for fetching the next page of results */
nextCursor?: string
}
export type CachedTraceSpansQueryResponse = CachedQueryResponse<TraceSpansQueryResponse>
export type SpanHealthStatus = 'silent' | 'regressed' | 'degraded' | 'new' | 'recovered' | 'improved' | 'ok'
/** One aggregated span row keyed by `(service_name, name)`. Used by the delta-table view. */
export interface AggregatedSpanRow {
service_name: string
name: string
count: integer
total_duration_nano: number
avg_duration_nano: number
p50_duration_nano: number
p95_duration_nano: number
p99_duration_nano: number
p999_duration_nano: number
error_count: integer
/** Set only when the query asked for `includeImpact`. `sessions` and `users` are uniq() estimates; the two span counts are exact. */
sessions?: integer
users?: integer
spans_with_session_id?: integer
spans_with_distinct_id?: integer
/** Set only when the query asked for `includeHealth`. Same statuses as the service health check. */
health_status?: SpanHealthStatus
/** Short reason for `health_status`, such as `error rate 0.2% → 4.1%`. Empty when the status is `ok`. */
health_reason?: string
}
export interface TraceSpansAggregationQuery extends DataNode<TraceSpansAggregationQueryResponse> {
kind: NodeKind.TraceSpansAggregationQuery
dateRange: DateRange
/** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */
compareFilter?: CompareFilter
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
/** Also aggregate sessions and people per operation. Off by default: it reads the attribute maps. */
includeImpact?: boolean
/**
* Group HTTP server spans by `METHOD route` in place of the span name. Spans without a route keep their name.
* Spans that are not HTTP server spans are left out.
*/
groupByEndpoint?: boolean
/**
* Classify each row against the comparison window, or the previous period when `compareFilter` is off.
* Fills `health_status` and `health_reason`. Runs a second window query.
*/
includeHealth?: boolean
}
export interface TraceSpansAggregationQueryResponse extends AnalyticsQueryResponseBase {
results: AggregatedSpanRow[]
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AggregatedSpanRow[]
}
export type CachedTraceSpansAggregationQueryResponse = CachedQueryResponse<TraceSpansAggregationQueryResponse>
/**
* One node in an aggregated span call tree. The `(service_name, name)` pair identifies
* the node; `(parent_service, parent_name)` links it to its parent. Spans without a
* matching parent in the window get `parent_name = '<ROOT>'` so orphans surface explicitly.
*/
export interface SpanTreeNode {
parent_service: string
parent_name: string
service_name: string
name: string
count: integer
total_duration_nano: number
avg_duration_nano: number
p50_duration_nano: number
p95_duration_nano: number
p99_duration_nano: number
p999_duration_nano: number
error_count: integer
/**
* Average nanoseconds from the parent span's start to this span's start. Zero for
* root spans. Used to order children left-to-right by typical start time in the
* flame graph.
*/
avg_start_offset_nano: number
/**
* How many times this child runs per parent invocation (edge count / parent span
* count). Separates fan-out volume from per-call cost: a child can dominate
* total_duration_nano purely by running many times per parent. Null for root edges
* (no parent invocation to ratio against).
*/
calls_per_parent_invocation?: number | null
}
export interface TraceSpansTreeQuery extends DataNode<TraceSpansTreeQueryResponse> {
kind: NodeKind.TraceSpansTreeQuery
dateRange: DateRange
/**
* Span name to scope the matched trace set. Required because the
* `(trace_id, parent_span_id)` self-join is prohibitive without bounding the
* matched traces — at high name cardinality the query becomes unsafe to run.
*/
spanName: string
/**
* Service name that scopes the returned tree. Applied to the spans CTE so the
* call-tree only contains spans from this service, even when matched traces
* span multiple services.
*/
serviceName: string
/** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */
compareFilter?: CompareFilter
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
}
export interface TraceSpansTreeQueryResponse extends AnalyticsQueryResponseBase {
results: SpanTreeNode[]
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: SpanTreeNode[]
}
export type CachedTraceSpansTreeQueryResponse = CachedQueryResponse<TraceSpansTreeQueryResponse>
/**
* One row of a span attribute breakdown: the spans matching the filters, grouped by one
* attribute's value. Spans without the attribute group under `value = ''`.
*/
export interface AttributeBreakdownRow {
value: string
count: integer
error_count: integer
p50_duration_nano: number
p95_duration_nano: number
}
export type TraceSpanBreakdownType = 'span' | 'span_attribute' | 'span_resource_attribute'
export type TraceSpanBreakdownOrderBy = 'count' | 'error_count'
export interface TraceSpansAttributeBreakdownQuery extends DataNode<TraceSpansAttributeBreakdownQueryResponse> {
kind: NodeKind.TraceSpansAttributeBreakdownQuery
dateRange: DateRange
/**
* Attribute key to group by (e.g. `http.response.status_code`, `server.address`).
* For the `span` breakdown type, must be an allowlisted top-level column (`service_name`, `status_code`).
*/
breakdownKey: string
/** Where the key lives: an allowlisted top-level span column, span-level attributes, or resource-level attributes. */
breakdownType: TraceSpanBreakdownType
/** Order rows by span count or error count, descending. Defaults to count. */
orderBy?: TraceSpanBreakdownOrderBy
/** Optional comparison window — when `compare` is true, the runner returns an extra `compare` result set. */
compareFilter?: CompareFilter
filterGroup?: PropertyGroupFilter
serviceNames?: string[]
/**
* Drop filters targeting the breakdown key itself (including `serviceNames` for a `service_name`
* breakdown) so a facet's value list stays complete while one of its values is selected.
*/
excludeBreakdownFilter?: boolean
/**
* Type-ahead filter over the breakdown field's own values (case-insensitive substring match).
* Lets a facet's value search reach past the row limit.
*/
facetSearch?: string
}
export interface TraceSpansAttributeBreakdownQueryResponse extends AnalyticsQueryResponseBase {
results: AttributeBreakdownRow[]
/** Result rows for the comparison period when `compareFilter.compare` is true. */
compare?: AttributeBreakdownRow[]
}
export type CachedTraceSpansAttributeBreakdownQueryResponse =
CachedQueryResponse<TraceSpansAttributeBreakdownQueryResponse>
/**
* A source symbol (typically a function) the client wants production latency for, identified by its
* declaration line range. The client supplies these from its own AST/LSP — the server does not infer
* function boundaries (OTel `code.function.name` is frequently absent, and `code.line.number` may be a
* call site inside the body rather than the declaration line).
*/
export interface SourceSymbol {
/** Opaque identifier (e.g. the function name) echoed back on the matching result row. */
name?: string
/** First line of the symbol's range, inclusive (1-based). */
startLine: positive_integer
/** Last line of the symbol's range, inclusive (1-based). */
endLine: positive_integer
}
/** Aggregated metrics for a symbol over a single time period. Used for the prior-period comparison. */
export interface SymbolStatsPeriod {
/** Number of spans attributed to this symbol in the period. */
count: integer
/** Spans whose OTel status is Error (`status_code = 2`). */
error_count: integer
/** Total wall-clock span duration in the period, in nanoseconds (additive across spans). */
sum_duration_nano: number
/** Median wall-clock span duration, in nanoseconds. */
p50_duration_nano: number
/** 95th-percentile wall-clock span duration, in nanoseconds. */
p95_duration_nano: number
/** 99th-percentile wall-clock span duration, in nanoseconds. */
p99_duration_nano: number
/** Spans in the period carrying an active/busy time attribute. 0 means busy_* are not meaningful. */
busy_count: integer
/** Median active (busy) time, in nanoseconds. Excludes time awaiting children. */
p50_busy_nano: number
/** 95th-percentile active (busy) time, in nanoseconds. */
p95_busy_nano: number
/** 99th-percentile active (busy) time, in nanoseconds. */
p99_busy_nano: number
}
/**
* Production latency for one bucket of a source file: spans carrying OpenTelemetry `code.*` location
* attributes, aggregated by line (no `symbols`) or into a symbol's line range (`symbols` supplied). The
* flat fields are the current period; `previous` is the immediately-preceding equal-length window. One
* row per bucket with spans in either period.
*/
export interface SymbolStatsRow {
/** The bucket's anchor line: the source line in line mode, or the symbol's `startLine` in symbol mode. */
line: integer
/** Echoed `name` from the requested symbol. Symbol mode only. */
name?: string
/** `endLine` of the matched symbol's range. Symbol mode only. */
end_line?: integer
/** Number of spans attributed to this bucket. */
count: integer
/** Spans whose OTel status is Error (`status_code = 2`). */
error_count: integer
/** Total wall-clock span duration in this symbol, in nanoseconds (additive across spans). */
sum_duration_nano: number
/** Median wall-clock span duration, in nanoseconds. */
p50_duration_nano: number
/** 95th-percentile wall-clock span duration, in nanoseconds. */
p95_duration_nano: number
/** 99th-percentile wall-clock span duration, in nanoseconds. */
p99_duration_nano: number
/** Spans in this symbol carrying an active/busy time attribute. 0 means busy_* are not meaningful. */
busy_count: integer
/** Median active (busy) time, in nanoseconds. Excludes time awaiting children. */
p50_busy_nano: number
/** 95th-percentile active (busy) time, in nanoseconds. */
p95_busy_nano: number
/** 99th-percentile active (busy) time, in nanoseconds. */
p99_busy_nano: number
/** The same metrics over the immediately-preceding equal-length period. */
previous: SymbolStatsPeriod
/**
* Percentage change in count vs the previous period (180 = +180%). Null when there is no baseline
* (previous count 0); use `previous.count`, not a null here, to detect a brand-new symbol.
*/
count_pct_change: number | null
/**
* Percentage change in p50 duration vs the previous period (180 = +180%). Null when the previous p50
* is 0 (no comparable baseline), which can happen even when previous.count > 0 — do not read null as "new".
*/
p50_duration_pct_change: number | null
/**
* Percentage change in p95 duration vs the previous period (180 = +180%). Null when the previous p95
* is 0 (no comparable baseline), which can happen even when previous.count > 0 — do not read null as "new".
*/
p95_duration_pct_change: number | null
/**
* Percentage change in p99 duration vs the previous period (180 = +180%). Null when the previous p99
* is 0 (no comparable baseline), which can happen even when previous.count > 0 — do not read null as "new".
*/
p99_duration_pct_change: number | null
/**
* Percentage change in error rate (`error_count / count` per window) vs the previous period. Null when
* the previous error rate is 0 — i.e. the previous window had no errors or no traffic. This includes a
* 0→N new-error spike, which surfaces as null rather than a delta.
*/
error_rate_pct_change: number | null
}
export interface TraceSpansSymbolStatsQuery extends DataNode<TraceSpansSymbolStatsQueryResponse> {
kind: NodeKind.TraceSpansSymbolStatsQuery
dateRange: DateRange
/**
* Repo-relative path of the source file to aggregate (e.g. `src/flags/flag_matching.rs`).
* Matched as a path suffix against the recorded `code.file.path` / `code.filepath`, so a
* recorded path carrying an extra crate/workspace prefix still matches.
*/
filePath: string
/**
* Optional symbol (function) ranges to aggregate spans into. When supplied, each span is attributed
* to the smallest range that encloses its recorded line (one row per symbol). When omitted (or an
* empty list), spans are aggregated per source line (one row per instrumented line) — pass a single
* whole-file range for a file-level total.
*/
symbols?: SourceSymbol[]
}
/** Bucketing applied to a symbol-stats result: per source line, or per requested symbol range. */
export type SymbolStatsGranularity = 'line' | 'symbol'
export interface TraceSpansSymbolStatsQueryResponse extends AnalyticsQueryResponseBase {
/** One row per bucket, ordered by line ascending. */
results: SymbolStatsRow[]
/** Which bucketing was applied: `line` when no symbols were supplied, `symbol` otherwise. */
granularity: SymbolStatsGranularity
}
export type CachedTraceSpansSymbolStatsQueryResponse = CachedQueryResponse<TraceSpansSymbolStatsQueryResponse>
export interface FileSystemCount {
count: number
entries: FileSystemEntry[]
has_more: boolean
}
export interface FileSystemEntry {
/** Unique UUID for tree entry */
id: string
/** Object's name and folder */
path: string
/** Type of object, used for icon, e.g. feature_flag, insight, etc */
type?: string
/** Object's ID or other unique reference */
ref?: string
/** Object's URL */
href?: string
/** Metadata */
meta?: Record<string, any>
/** Timestamp when file was added. Used to check persistence */
created_at?: string
/** Timestamp when the file system entry was last viewed */
last_viewed_at?: string | null
/** Whether this is a shortcut or the actual item */
shortcut?: boolean
/** Used to indicate pending actions, frontend only */
_loading?: boolean
/** Tag for the product 'beta' / 'alpha' */
tags?: ('alpha' | 'beta')[]
/** Order of object in tree */
visualOrder?: number
/** Access level the user has for the referenced object ('none' means no access); null/absent when access controls don't apply */
user_access_level?: string | null
}
export type FileSystemIconType =
| 'default_icon_type'
| 'dashboard'
| 'canvas'
| 'llm_analytics'
| 'product_analytics'
| 'revenue_analytics'
| 'revenue_analytics_metadata'
| 'marketing_settings'
| 'marketing_analytics'
| 'customer_analytics'
| 'managed_viewsets'
| 'endpoints'
| 'sql_editor'
| 'business_intelligence'
| 'web_analytics'
| 'error_tracking'
| 'heatmap'
| 'session_replay'
| 'replay_vision'
| 'session_profile'
| 'survey'
| 'product_tour'
| 'early_access_feature'
| 'experiment'
| 'feature_flag'
| 'feature_flag_off'
| 'data_modeling'
| 'data_pipeline'
| 'data_pipeline_metadata'
| 'data_warehouse'
| 'task'
| 'logs'
| 'tracing'
| 'metrics'
| 'uptime_monitoring'
| 'workflows'
| 'broadcasts'
| 'transactional'
| 'notebook'
| 'action'
| 'activity'
| 'comment'
| 'annotation'
| 'event'
| 'event_definition'
| 'property_definition'
| 'ingestion_warning'
| 'persons'
| 'user'
| 'cohort'
| 'group'
| 'insight/funnels'
| 'insight/trends'
| 'insight/retention'
| 'insight/paths'
| 'insight/lifecycle'
| 'insight/stickiness'
| 'insight/hog'
| 'team_activity'
| 'home'
| 'tools'
| 'live'
| 'chat'
| 'search'
| 'folder'
| 'folder_open'
| 'conversations'
| 'toolbar'
| 'visual_review'
| 'code_review'
| 'stamphog'
| 'settings'
| 'health'
| 'inbox'
| 'sdk_health'
| 'pipeline_status'
| 'llm_evaluations'
| 'llm_tags'
| 'llm_datasets'
| 'llm_playground'
| 'llm_prompts'
| 'llm_clusters'
| 'mcp_analytics'
| 'exports'
| 'pulse'
| 'skill'
| 'wizard'
| 'data_catalog'
| 'warehouse_destination'
| 'warehouse_property'
| 'data_source'
| 'data_destination'
| 'data_transformation'
| 'event_filter'
| 'managed_migration'
| 'web_script'
| 'core_event'
| 'property_group'
| 'mcp_server'
| 'streamlit_app'
| 'sql_variable'
| 'business_knowledge'
export interface FileSystemImport extends Omit<FileSystemEntry, 'id'> {
id?: string
iconType?: FileSystemIconType
flag?: string
/** Other flags that also show the item. The item is shown when `flag` or any of these is on. */
alternativeFlags?: string[]
/** Order of object in tree */
visualOrder?: number
/** Tag for the product 'beta' / 'alpha' */
tags?: ('alpha' | 'beta')[]
/** Protocol of the item, defaults to "project://" */
protocol?: string
/** Category label to place this under */
category?: string
/** Color of the icon */
iconColor?: FileSystemIconColor
/** Match this with the a base scene key or a specific one */
sceneKey?: string
/** List of all scenes exported by the app */
sceneKeys?: string[]
/** Product key(s) that generate interest in this item when intent is triggered */
intents?: ProductKey[]
/** Display label override — when set, shown in the nav instead of the last segment of `path` */
displayLabel?: string
/** Synonyms that find this item in search; a word that names a tab belongs on that tab's row instead */
searchKeywords?: string[]
/** Tabs with their own URL that search lists as separate rows, below products and people */
searchTabs?: FileSystemSearchTab[]
}
export interface FileSystemSearchTab {
name: string
href: string
flag?: string
searchKeywords?: string[]
}
export interface FileSystemViewLogEntry {
type: string
ref: string
viewed_at: string
}
export type DataWarehouseManagedViewsetKind = 'revenue_analytics'
export type InsightQueryNode =
| TrendsQuery
| FunnelsQuery
| RetentionQuery
| PathsQuery
| PathsV2Query
| StickinessQuery
| LifecycleQuery
| WebStatsTableQuery
| WebOverviewQuery
export type ProductAnalyticsInsightQueryNode = Exclude<InsightQueryNode, WebStatsTableQuery | WebOverviewQuery>
export interface MaxExperimentVariantResultBayesian {
key: string
chance_to_win: number | null
credible_interval: number[] | null
delta: number | null
significant: boolean
}
export interface MaxExperimentVariantResultFrequentist {
key: string
p_value: number | null
confidence_interval: number[] | null
delta: number | null
significant: boolean
}
export interface MaxExperimentMetricResult {
name: string
goal: 'increase' | 'decrease' | null
variant_results: (MaxExperimentVariantResultBayesian | MaxExperimentVariantResultFrequentist)[]
}
export interface MaxExperimentSummaryContext {
experiment_id: ExperimentIdType
experiment_name: string
description: string | null
exposures: Record<string, number> | null
variants: string[]
primary_metrics_results: MaxExperimentMetricResult[]
secondary_metrics_results: MaxExperimentMetricResult[]
stats_method: ExperimentStatsMethod
}
/** Stored shape of a legacy experiment metric. It no longer runs, so it is kept only to list and migrate legacy experiments. */
export interface ExperimentFunnelsQuery {
kind: NodeKind.ExperimentFunnelsQuery
uuid?: string
name?: string
experiment_id?: integer
funnels_query: FunnelsQuery
fingerprint?: string
}
/** Stored shape of a legacy experiment metric. It no longer runs, so it is kept only to list and migrate legacy experiments. */
export interface ExperimentTrendsQuery {
kind: NodeKind.ExperimentTrendsQuery
uuid?: string
name?: string
experiment_id?: integer
count_query: TrendsQuery
exposure_query?: TrendsQuery
fingerprint?: string
}
export type ExperimentExposureConfig =
| ExperimentEventExposureConfig
| ActionsNode
| ExperimentWarehouseNativeExposureConfig
export interface ExperimentExposureCriteria {
filterTestAccounts?: boolean
exposure_config?: ExperimentExposureConfig
/** Additional event (or action) an entity must emit at/after their first default exposure
* event before they count as exposed; exposure time becomes this event's timestamp.
* Only valid with the default exposure event, not a custom `exposure_config`. Warehouse-native
* activation has no defined semantics yet, so only events and actions apply here. */
activation_config?: ExperimentEventExposureConfig | ActionsNode
multiple_variant_handling?: 'exclude' | 'first_seen'
}
export interface ExperimentEventExposureConfig extends Node {
kind: NodeKind.ExperimentEventExposureConfig
event: string
properties: AnyPropertyFilter[]
}
/** What the `entity_id` column of a warehouse-native query identifies. Exposures and outcomes join on
* `entity_id` inside the warehouse, and the same connection does not make two queries compatible:
* one can return account ids and another customer ids. Every warehouse-native source stores its
* binding so a saved metric keeps it when it is attached to another experiment, and so attachment
* can compare bindings instead of guessing from SQL. Equal labels are required for compatibility
* but cannot prove the SQL returns the same identities; the author confirms that. */
export interface ExperimentWarehouseNativeUnitBinding {
/** What was randomized, as a stable project-scoped label such as `customer` or `account`. */
unit_type: string
/** Which ids represent that unit, such as `billing_customer_id`. */
id_namespace: string
}
/** Exposures that live in the customer's warehouse, read through a direct connection. An experiment
* with this exposure runs entirely in the warehouse, so every metric source must be an
* `ExperimentWarehouseNativeNode` on the same connection with the same unit binding. */
export interface ExperimentWarehouseNativeExposureConfig extends Node {
kind: NodeKind.ExperimentWarehouseNativeExposureConfig
/** The direct-query source (an ExternalDataSource id) the SQL is written for. */
connection_id: string
/** Read-only SQL in the warehouse's dialect, returning one row per exposure with `entity_id`,
* `variant` and `timestamp` columns. PostHog keeps the first exposure per entity and applies
* the experiment's date range and multiple-variant handling. */
query: string
unit: ExperimentWarehouseNativeUnitBinding
}
// ── Slim API types for experiment create/update ──────────────────────
// Simplified versions of the full query types: they drop the nested
// metric/node machinery (EventsNode, ExperimentMeanMetric, …) the
// create/update payloads never need.
//
// Property-filter typing is intentionally asymmetric. AnyPropertyFilter is
// an 18-subtype union that the OpenAPI/MCP codegen inlines (not $ref's) at
// every use site, so each use expands the generated schema.
// - Exposure config uses AnyPropertyFilter: targeting exposure by
// person/group/cohort is a real case the runtime validator already
// accepts, and EventPropertyFilter[] silently dropped those filters.
// - Metric event sources keep EventPropertyFilter[]: the source is inlined
// across every metric field (source, numerator, denominator, start/
// completion event) in every experiment tool, so widening it multiplies
// the expansion — not worth it until metrics need non-event filters.
/** Slim event/action source for experiment API payloads. */
export interface ExperimentApiEventSource {
kind: 'EventsNode' | 'ActionsNode'
/** Event name, e.g. '$pageview'. Required for EventsNode. */
event?: string
/** Action ID. Required for ActionsNode. */
id?: integer
/** How to aggregate this source. Defaults to 'total' (event count). Use 'sum' together with
* math_property to aggregate a numeric property — e.g. a ratio numerator of revenue per order.
* Other options: 'avg', 'min', 'max', 'unique_session', 'dau', 'unique_group', 'hogql'. */
math?: ExperimentMetricMathType
/** Numeric event property to aggregate when math is 'sum', 'avg', 'min', or 'max' (e.g. 'revenue'). */
math_property?: string
/** HogQL aggregation expression. Required when math is 'hogql' — without it the metric silently
* falls back to a plain count/sum. */
math_hogql?: string
/** Group type index to aggregate over. Required when math is 'unique_group'. */
math_group_type_index?: 0 | 1 | 2 | 3 | 4
/** Event property filters to narrow which events are counted. */
properties?: EventPropertyFilter[]
}
/** Slim start source for retention metrics in API payloads. kind stays required so a
* payload without it fails validation instead of silently becoming an exposure start. */
export interface ExperimentApiRetentionStart extends Omit<ExperimentApiEventSource, 'kind'> {
/** Pass 'ExperimentExposureNode' to start retention from the experiment's own exposure
* event; the other fields then stay unset. */
kind: 'EventsNode' | 'ActionsNode' | 'ExperimentExposureNode'
}
/** 'all_events' is excluded: the experiment funnel query rejects it. */
export type ExperimentApiBreakdownAttributionType = 'first_touch' | 'last_touch' | 'step'
export type ExperimentApiPropertyBreakdownType = 'event' | 'person' | 'session'
/** Breakdown by an event, person or session property. */
export interface ExperimentApiPropertyBreakdown {
/** Property name to break down by. */
property: string
/** Where the property lives. Defaults to 'event'. */
type?: ExperimentApiPropertyBreakdownType
}
/** Breakdown by a group property. */
export interface ExperimentApiGroupBreakdown {
/** Property name to break down by. */
property: string
type: 'group'
/** Which group type the property belongs to. */
group_type_index: 0 | 1 | 2 | 3 | 4
}
/** Slim breakdown entry for experiment API payloads. Narrower than the full
* Breakdown type: the experiment query only resolves event, person, session
* and group properties, so the other breakdown types are not accepted here. */
export type ExperimentApiBreakdown = ExperimentApiPropertyBreakdown | ExperimentApiGroupBreakdown
/** Slim breakdown config for experiment API payloads. Only the fields the
* experiment query runner reads; the full BreakdownFilter's other knobs
* (breakdown, breakdown_type, attribution, …) are ignored for experiment
* metrics, so exposing them would only invite no-op input. */
export interface ExperimentApiBreakdownFilter {
/** Properties to break the metric results down by.
* @maxItems 3 */
breakdowns?: ExperimentApiBreakdown[]
/** Maximum number of breakdown values to compute results for. */
breakdown_limit?: integer
}
/** Experiment metric for API create/update. All metric-type-specific
* fields are optional; discriminated by metric_type at runtime. */
export interface ExperimentApiMetric {
kind: NodeKind.ExperimentMetric
metric_type: ExperimentMetricType
/** Human-readable metric name. */
name?: string
/** Unique identifier. Auto-generated if omitted. */
uuid?: string
/** Whether higher or lower values indicate success. */
goal?: ExperimentMetricGoal
/** Only count metric events within this many units after the user's first exposure. Requires
* conversion_window_unit: a window without a unit is ignored and the metric counts events until
* the experiment ends. Omit both to count until the experiment ends. */
conversion_window?: integer
/** Unit for conversion_window: 'second', 'minute', 'hour', 'day', 'week' or 'month'. Required when
* conversion_window is set. */
conversion_window_unit?: FunnelConversionWindowTimeUnit
/** For mean metrics: event source. */
source?: ExperimentApiEventSource
/** For funnel metrics: array of EventsNode/ActionsNode steps. */
series?: ExperimentApiEventSource[]
/** For funnel metrics: how the steps must occur. 'ordered' (default) or 'unordered'. Do not use
* 'strict': experiment funnels give wrong counts with it. */
funnel_order_type?: StepOrderValue
/** For ratio metrics: numerator source. */
numerator?: ExperimentApiEventSource
/** For ratio metrics: denominator source. */
denominator?: ExperimentApiEventSource
/** For mean metrics: winsorization lower percentile bound, as a fraction in [0, 1] (e.g. 0.01
* for the 1st percentile). Per-user values below this percentile are clamped to it before
* aggregation.
* @minimum 0
* @maximum 1 */
lower_bound_percentile?: number
/** For mean metrics: winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99
* for the 99th percentile). Per-user values above this percentile are clamped to it before
* aggregation.
* @minimum 0
* @maximum 1 */
upper_bound_percentile?: number
/** For mean metrics: exclude zero values when computing the winsorization percentile thresholds. */
ignore_zeros?: boolean
/** For mean metrics: when set, reports the percentage of users whose per-user summed/counted value
* reaches or exceeds this threshold. Only meaningful for sum/count math types. */
threshold?: number
/** For ratio metrics: winsorization applied to the numerator aggregate, independently of the
* denominator and each with its own percentile thresholds. */
numerator_outlier_handling?: ExperimentMetricOutlierHandling
/** For ratio metrics: winsorization applied to the denominator aggregate. Leave unset for a
* binomial-style denominator, which is never clamped. */
denominator_outlier_handling?: ExperimentMetricOutlierHandling
/** For retention metrics: start event. Pass {"kind": "ExperimentExposureNode"} to start retention
* from the experiment's exposure event; a conversion window or 'last_seen' start_handling is
* rejected then, because the start is always the user's first exposure. */
start_event?: ExperimentApiRetentionStart
/** For retention metrics: completion event. */
completion_event?: ExperimentApiEventSource
retention_window_start?: integer
retention_window_end?: integer
retention_window_unit?: FunnelConversionWindowTimeUnit
start_handling?: 'first_seen' | 'last_seen'
/** Break the metric results down by up to 3 event, person, session or group properties. */
breakdownFilter?: ExperimentApiBreakdownFilter
/** For funnel metrics with breakdowns: which step the breakdown value is read from.
* 'all_events' is not supported for experiment funnels. */
breakdownAttributionType?: ExperimentApiBreakdownAttributionType
/** When breakdownAttributionType is 'step', the 0-indexed step to attribute from. */
breakdownAttributionValue?: integer
}
export interface ExperimentParameters {
/** Minimum detectable effect as a percentage. Lower values need more users but catch smaller changes. Suggest 20–30% for most experiments. */
minimum_detectable_effect?: number
/** Free-text notes per variant, keyed by variant key. Use to document what each variant does or its reroute URL. */
variant_notes?: Record<string, string>
}
/** Exposure estimate settings for the experiment running-time calculator. */
export interface ExperimentExposureEstimateConfig {
/** 'manual' when the baseline value and exposure rate were entered by hand, 'automatic' when derived from live experiment data. */
conversionRateInputType: 'manual' | 'automatic'
/** Metric type the manual baseline value refers to. Only used in manual mode. */
manualMetricType?: 'funnel' | 'mean_count' | 'mean_sum_or_avg'
/** Manually entered baseline metric value (a conversion percentage for funnel metrics). Only used in manual mode. */
manualBaselineValue?: number
/** Manually entered estimate of users exposed to the experiment per day. Only used in manual mode. */
manualExposureRate?: number
}
/** Running-time calculator state for an experiment. Canonical home for keys that historically lived in `parameters`. */
export interface ExperimentRunningTimeCalculation {
/** Minimum detectable effect as a percentage. Lower values need more users but catch smaller changes. */
minimum_detectable_effect?: number
/** Estimated number of days needed to reach the recommended sample size. */
recommended_running_time?: number
/** Recommended number of exposed users needed for statistical significance. */
recommended_sample_size?: number
/** How the exposure estimate is configured: manual user-entered values or automatic from live experiment data. */
exposure_estimate_config?: ExperimentExposureEstimateConfig | null
}
/** Slim exposure config for experiment API payloads. Discriminated by `kind`:
* 'ExperimentEventExposureConfig' tracks exposure via a custom event,
* 'ActionsNode' tracks exposure via an action. */
export interface ExperimentApiExposureConfig {
/** Defaults to 'ExperimentEventExposureConfig' when omitted. Pass 'ActionsNode' for an action-based exposure. */
kind?: 'ExperimentEventExposureConfig' | 'ActionsNode'
/** Custom exposure event name. Required when kind is 'ExperimentEventExposureConfig'. */
event?: string
/** Action ID. Required when kind is 'ActionsNode'. */
id?: integer
/** Property filters (event, person, and other supported types). Pass an empty array if no filters needed. */
properties: AnyPropertyFilter[]
}
/** Exposure criteria for experiment API payloads. */
export interface ExperimentApiExposureCriteria {
filterTestAccounts?: boolean
exposure_config?: ExperimentApiExposureConfig
/** Additional event (or action) an entity must emit at/after their first default exposure
* event before they count as exposed; exposure time becomes this event's timestamp.
* Only valid with the default exposure event, not a custom `exposure_config`. */
activation_config?: ExperimentApiExposureConfig
/** How to handle entities exposed to multiple variants. 'exclude' (default) drops them from
* the analysis; 'first_seen' assigns them to the variant from their earliest exposure. */
multiple_variant_handling?: 'exclude' | 'first_seen'
}
export const enum ExperimentMetricType {
FUNNEL = 'funnel',
MEAN = 'mean',
RATIO = 'ratio',
RETENTION = 'retention',
}
export interface ExperimentMetricBaseProperties extends Node {
kind: NodeKind.ExperimentMetric
uuid?: string
fingerprint?: string // # SHA256 hash of metric definition + experiment config
name?: string
conversion_window?: integer
conversion_window_unit?: FunnelConversionWindowTimeUnit
goal?: ExperimentMetricGoal
isSharedMetric?: boolean
sharedMetricId?: number
breakdownFilter?: BreakdownFilter
}
export type ExperimentMetricOutlierHandling = {
/** Winsorization lower percentile bound, as a fraction in [0, 1] (e.g. 0.01 for the 1st percentile).
* @minimum 0
* @maximum 1 */
lower_bound_percentile?: number
/** Winsorization upper percentile bound, as a fraction in [0, 1] (e.g. 0.99 for the 99th percentile).
* @minimum 0
* @maximum 1 */
upper_bound_percentile?: number
ignore_zeros?: boolean
}
export interface ExperimentDataWarehouseNode extends EntityNode {
kind: NodeKind.ExperimentDataWarehouseNode
table_name: string
timestamp_field: string
events_join_key: string
data_warehouse_join_key: string
}
/** The subset of `ExperimentMetricMathType` a warehouse-native source supports, with the same values. */
export enum ExperimentWarehouseNativeMathType {
TotalCount = 'total',
Sum = 'sum',
}
/** Outcome rows that live in the customer's warehouse, read through a direct connection. PostHog joins
* them to the experiment's exposures and aggregates them inside the warehouse, so the SQL never
* mentions variants or exposures and only per-variant aggregates leave the warehouse. Distinct from
* `ExperimentDataWarehouseNode`, which reads tables synced into PostHog. It does not extend
* `EntityNode`: property filters and the other event settings cannot apply to SQL PostHog does not
* parse, so the shape lists every supported field. Only mean and ratio metrics accept it. */
export interface ExperimentWarehouseNativeNode extends Node {
kind: NodeKind.ExperimentWarehouseNativeNode
/** The direct-query source (an ExternalDataSource id) the SQL is written for. */
connection_id: string
/** Read-only SQL in the warehouse's dialect, returning one row per outcome with `entity_id` and
* `timestamp` columns plus any numeric columns a metric can measure. */
query: string
unit: ExperimentWarehouseNativeUnitBinding
/** How to aggregate the rows per entity. Defaults to `total` (row count). */
math?: ExperimentWarehouseNativeMathType
/** The numeric column `math` reads. Required when `math` is `sum`. One SQL relation can serve
* several metrics, each reading a different column. */
math_property?: string
custom_name?: string
}
// Named separately from `ExperimentMetricSource` so the JSDoc `@discriminator` tag
// can attach without tripping ts-json-schema-generator's dedup (same workaround
// pattern as `ExperimentMetricUnion = ExperimentMetric`). The alias is the public
// type — callers continue to use `ExperimentMetricSource`.
/**
* @discriminator kind
*/
export type ExperimentMetricSourceUnion =
| EventsNode
| ActionsNode
| ExperimentDataWarehouseNode
| ExperimentWarehouseNativeNode
export type ExperimentMetricSource = ExperimentMetricSourceUnion
/**
* @discriminator kind
*/
export type ExperimentFunnelMetricStepUnion = EventsNode | ActionsNode | ExperimentDataWarehouseNode
export type ExperimentFunnelMetricStep = ExperimentFunnelMetricStepUnion
/** Sentinel start source for retention metrics. It carries no event of its own:
* at query time it resolves to the experiment's exposure, so one shared metric
* anchors correctly on any experiment regardless of that experiment's exposure event. */
export interface ExperimentExposureNode extends Node {
kind: NodeKind.ExperimentExposureNode
}
export const isExperimentExposureNode = (node: { kind: NodeKind }): node is ExperimentExposureNode =>
node.kind === NodeKind.ExperimentExposureNode
/**
* @discriminator kind
*/
export type ExperimentRetentionStartUnion =
| EventsNode
| ActionsNode
| ExperimentDataWarehouseNode
| ExperimentExposureNode
export type ExperimentRetentionStart = ExperimentRetentionStartUnion
/**
* @discriminator kind
*/
export type ExperimentRetentionCompletionUnion = EventsNode | ActionsNode | ExperimentDataWarehouseNode
export type ExperimentRetentionCompletion = ExperimentRetentionCompletionUnion
export type ExperimentMeanMetric = ExperimentMetricBaseProperties &
ExperimentMetricOutlierHandling & {
metric_type: ExperimentMetricType.MEAN
source: ExperimentMetricSource
/** When set, reports the percentage of users whose per-user summed/counted value
* reaches or exceeds this threshold. Only meaningful for sum/count math types. */
threshold?: number
}
export const isExperimentMeanMetric = (metric: ExperimentMetric): metric is ExperimentMeanMetric =>
metric.metric_type === ExperimentMetricType.MEAN
export type ExperimentFunnelMetric = ExperimentMetricBaseProperties & {
metric_type: ExperimentMetricType.FUNNEL
series: ExperimentFunnelMetricStep[]
funnel_order_type?: StepOrderValue
/** How to attribute the breakdown value across funnel steps. @default first_touch */
breakdownAttributionType?: BreakdownAttributionType
/** When breakdownAttributionType is `step`, the 0-indexed step to attribute from. @asType integer */
breakdownAttributionValue?: integer
}
export const isExperimentFunnelMetric = (metric: ExperimentMetric): metric is ExperimentFunnelMetric =>
metric.metric_type === ExperimentMetricType.FUNNEL
export type ExperimentRatioMetric = ExperimentMetricBaseProperties & {
metric_type: ExperimentMetricType.RATIO
numerator: ExperimentMetricSource
denominator: ExperimentMetricSource
// Winsorization is applied to the numerator and denominator independently,
// each with its own percentile bounds and computed thresholds. There is no
// per-user ratio to cap, so capping operates on the two component aggregates.
numerator_outlier_handling?: ExperimentMetricOutlierHandling
denominator_outlier_handling?: ExperimentMetricOutlierHandling
}
export const isExperimentRatioMetric = (metric: ExperimentMetric): metric is ExperimentRatioMetric =>
metric.metric_type === ExperimentMetricType.RATIO
export type ExperimentRetentionMetric = ExperimentMetricBaseProperties & {
metric_type: ExperimentMetricType.RETENTION
// Event that defines the start of the retention window. An ExperimentExposureNode
// start resolves to the experiment's own exposure event at query time.
start_event: ExperimentRetentionStart
// Event that defines the completion of the retention window
completion_event: ExperimentRetentionCompletion
// Start of the retention window
retention_window_start: integer
// End of the retention window
retention_window_end: integer
retention_window_unit: FunnelConversionWindowTimeUnit
// How to handle the start of the retention window. Must be 'first_seen' for an
// ExperimentExposureNode start, which always anchors on the first exposure.
start_handling: 'first_seen' | 'last_seen'
}
export const isExperimentRetentionMetric = (metric: ExperimentMetric): metric is ExperimentRetentionMetric =>
metric.metric_type === ExperimentMetricType.RETENTION
export type ExperimentMeanMetricTypeProps = Omit<ExperimentMeanMetric, keyof ExperimentMetricBaseProperties>
export type ExperimentFunnelMetricTypeProps = Omit<ExperimentFunnelMetric, keyof ExperimentMetricBaseProperties>
export type ExperimentRatioMetricTypeProps = Omit<ExperimentRatioMetric, keyof ExperimentMetricBaseProperties>
export type ExperimentRetentionMetricTypeProps = Omit<ExperimentRetentionMetric, keyof ExperimentMetricBaseProperties>
export type ExperimentMetricTypeProps =
| ExperimentMeanMetricTypeProps
| ExperimentFunnelMetricTypeProps
| ExperimentRatioMetricTypeProps
| ExperimentRetentionMetricTypeProps
// Named separately from `ExperimentMetric` so the JSDoc `@discriminator` tag below
// can attach without colliding with the `NodeKind.ExperimentMetric` enum value
// (which trips ts-json-schema-generator's deduplication). The alias is the public
// type — callers continue to use `ExperimentMetric`.
/**
* @discriminator metric_type
*/
export type ExperimentMetricUnion =
| ExperimentMeanMetric
| ExperimentFunnelMetric
| ExperimentRatioMetric
| ExperimentRetentionMetric
export type ExperimentMetric = ExperimentMetricUnion
export interface ExperimentQuery extends DataNode<ExperimentQueryResponse> {
kind: NodeKind.ExperimentQuery
metric: ExperimentMetric
experiment_id?: integer
name?: string
precomputation_mode?: 'precomputed' | 'direct'
}
export interface ExperimentExposureQuery extends DataNode<ExperimentExposureQueryResponse> {
kind: NodeKind.ExperimentExposureQuery
experiment_id?: integer
experiment_name: string
exposure_criteria?: ExperimentExposureCriteria
// Generic type as FeatureFlagBasicType is recursive and the schema:build breaks
feature_flag: Record<string, any>
start_date: string | null
end_date: string | null
holdout?: ExperimentHoldoutType
}
export interface ExperimentQueryResponse {
kind?: NodeKind.ExperimentQuery
baseline?: ExperimentStatsBaseValidated
variant_results?: ExperimentVariantResultFrequentist[] | ExperimentVariantResultBayesian[]
// Breakdown fields
/** Results grouped by breakdown value. When present, baseline and variant_results contain aggregated data. */
breakdown_results?: ExperimentBreakdownResult[]
clickhouse_sql?: string
hogql?: string
/** Whether exposures were served from the precomputation system */
is_precomputed?: boolean
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
export interface ExperimentActorsQuery extends InsightActorsQueryBase {
kind: NodeKind.ExperimentActorsQuery
source: ExperimentQuery
/** Index of the step for which we want to get actors for, per experiment variant.
* Positive for converted persons, negative for dropped off persons. */
funnelStep?: integer
/** The variant key for filtering actors. For experiments, this filters by feature flag variant (e.g., 'control', 'test'). */
funnelStepBreakdown?: BreakdownKeyType
/** Exposure configuration for filtering events. Defines when users were first exposed to the experiment. */
exposureConfig?: ExperimentExposureConfig
/** How to handle users with multiple variant exposures. */
multipleVariantHandling?: 'exclude' | 'first_seen'
/** Feature flag key for breakdown filtering. */
featureFlagKey?: string
}
export interface SessionData {
person_id: string
session_id: string
event_uuid: string
timestamp: string
}
export interface ExperimentStatsBase {
key: string
number_of_samples: integer
sum: number
sum_squares: number
covariate_sum?: number
covariate_sum_squares?: number
covariate_sum_product?: number
denominator_sum?: number
denominator_sum_squares?: number
numerator_denominator_sum_product?: number
step_counts?: integer[]
step_sessions?: SessionData[][]
}
export enum ExperimentStatsValidationFailure {
NotEnoughExposures = 'not-enough-exposures',
BaselineMeanIsZero = 'baseline-mean-is-zero',
NotEnoughMetricData = 'not-enough-metric-data',
}
export interface ExperimentStatsBaseValidated extends ExperimentStatsBase {
validation_failures?: ExperimentStatsValidationFailure[]
}
export interface ExperimentVariantResultFrequentist extends ExperimentStatsBaseValidated {
method: 'frequentist'
significant?: boolean
p_value?: number
confidence_interval?: [number, number]
}
export interface ExperimentVariantResultBayesian extends ExperimentStatsBaseValidated {
method: 'bayesian'
significant?: boolean
chance_to_win?: number
credible_interval?: [number, number]
}
/**
* Represents experiment results for a single breakdown combination.
* Each breakdown is treated as an independent A/B test with its own baseline and variants.
* For multiple breakdowns, values are in the same order as breakdownFilter.breakdowns.
*/
export interface ExperimentBreakdownResult {
/**
* The breakdown values as an array (e.g., ["MacOS", "Chrome"] for multi-breakdown, ["Chrome"] for single)
* Although `BreakdownKeyType` could be an array, we only use the array form for the breakdown_value.
* The way `BreakdownKeyType` is defined is problematic. It should be treated as a primitive and allow
* for the types using it to define if it's and array or an optional value.
*/
breakdown_value: (integer | string | number)[]
/** Control variant stats for this breakdown */
baseline: ExperimentStatsBaseValidated
/** Test variant results with statistical comparisons for this breakdown */
variants: ExperimentVariantResultFrequentist[] | ExperimentVariantResultBayesian[]
}
export interface NewExperimentQueryResponse {
clickhouse_sql?: string
hogql?: string
baseline: ExperimentStatsBaseValidated
variant_results: ExperimentVariantResultFrequentist[] | ExperimentVariantResultBayesian[]
breakdown_results?: ExperimentBreakdownResult[]
/** Whether exposures were served from the precomputation system */
is_precomputed?: boolean
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
export interface ExperimentExposureTimeSeries {
variant: string
days: string[]
exposure_counts: number[]
}
export interface SampleRatioMismatch {
expected: Record<string, number>
p_value: number
}
/**
* Empirically observed multi-variant exclusion bias risk: uneven split + `EXCLUDE`
* handling + observed `$multiple` share above the threshold. Present on the response
* only when the experiment is currently at risk.
*/
export interface BiasRisk {
/** Observed share of users assigned to `$multiple`, as a percentage (0-100). */
multiple_variant_percentage: number
}
export type ExperimentExposureHealthFindingCode =
| 'zero_exposures'
| 'srm'
| 'bias_risk_multiple_excluded'
| 'multiple_variants_share'
| 'test_account_filter_removes_exposures'
export type ExperimentExposureHealthFindingSeverity = 'critical' | 'warning' | 'info'
export type ExperimentExposureHealthFindingActionKind =
| 'open_feature_flag'
| 'edit_exposure_criteria'
| 'adjust_distribution'
| 'use_first_seen_variant'
/** A problem that a health check found in the exposure answer. Same shape as the experiment's `health.findings`. */
export interface ExperimentExposureHealthFinding {
/** Stable identifier of the problem. Each code has one meaning across every surface that reports it. */
code: ExperimentExposureHealthFindingCode
/** The case within the code, when a code covers several. Null when the code has one case. */
subcode: string | null
/** A stable qualifier below the subcode, for example where a sample ratio mismatch is located. Null when the finding names none. */
reason: string | null
/** How much the problem affects the results: critical, warning, or info. */
severity: ExperimentExposureHealthFindingSeverity
/** One-line summary of the problem. */
title: string
/** What is wrong, what it does to the experiment, and how to fix it. */
detail: string
/** The values behind the finding, such as the p-value of the sample ratio test. The keys depend on the code. */
evidence: Record<string, string | number | null>
/** The actions that fix the problem, in order of preference. */
actions: ExperimentExposureHealthFindingActionKind[]
/** The id of the matching diagnostic in the diagnosing-experiment-health skill, for example 'A2'. Null when the skill has none. */
diagnostic_ref: string | null
/** The key of the check in `health_checks` that reported the finding. Missing on an answer cached before the field existed. */
check?: ExperimentExposureHealthCheckKey
}
export type ExperimentExposureHealthCheckKey =
| 'zero_exposures'
| 'srm'
| 'bias_risk_multiple_excluded'
| 'multiple_variants_share'
| 'test_account_filter_removes_exposures'
export type ExperimentExposureHealthCheckStatus = 'passed' | 'finding' | 'not_applicable' | 'not_checked'
/** The keys in the `values` of an exposure check. Same meaning as in the experiment's `health.checks`. */
export type ExperimentExposureHealthValueKey =
| 'exposed_count'
| 'compared_count'
| 'multiple_variant_count'
| 'multiple_variant_percentage'
| 'multiple_variant_handling'
| 'p_value'
| 'since_launch_hours'
| 'exposed_without_test_account_filter_count'
| 'kept_by_test_account_filter_percentage'
export type ExperimentExposureHealthRuleSide = 'above' | 'below'
export type ExperimentExposureHealthRuleTest = 'chi_squared'
/** What an exposure check needs before it judges. */
export interface ExperimentExposureHealthRuleMinimum {
/** The key in `values` that must reach the threshold before the check judges. */
value: ExperimentExposureHealthValueKey
/** The value that the key must reach. Below it, the check reports no finding. */
threshold: number
}
/** How an exposure check decides. Same shape as the `rule` of the experiment's `health.checks`. */
export interface ExperimentExposureHealthCheckRule {
/** The key in `values` that the check compares with the threshold. */
value: ExperimentExposureHealthValueKey
/** The threshold, in the unit that the suffix of the key gives. */
threshold: number
/** above: the check reports a finding when the value is above the threshold. below: when the value is below it. A value at the threshold passes. */
warns: ExperimentExposureHealthRuleSide
/** The statistical test that computes the value. Null for a count or a share. */
test: ExperimentExposureHealthRuleTest | null
/** What the check needs before it judges. Null when the check judges from the first value. */
minimum: ExperimentExposureHealthRuleMinimum | null
}
/** What one health check concluded on the exposure answer. Same shape as the experiment's `health.checks`. */
export interface ExperimentExposureHealthCheck {
/** Stable identifier of the check. */
key: ExperimentExposureHealthCheckKey
/** The problem the check looks for, as the health panel lists it. */
name: string
/** What the check looks for and why it matters. Missing on an answer cached before the field existed. */
description?: string
/** passed: no problem found. finding: a finding in `health_findings`. not_applicable: the check doesn't cover the experiment's state. not_checked: an input was missing or the check failed. */
status: ExperimentExposureHealthCheckStatus
/** Why the check did not look, for the statuses not_applicable and not_checked, for example 'Runs after launch'. Null for passed and finding. */
reason: string | null
/** What the check read on the experiment, for every status. The suffix of a key gives the unit: _count is a count, _percentage is on the 0-100 scale, _hours is hours. A key without a suffix is a setting. Missing on an answer cached before the field existed. */
values?: Record<string, string | number | boolean | null>
/** How the check decides, the same for every experiment. Null for a check without a numeric rule. Missing on an answer cached before the field existed. */
rule?: ExperimentExposureHealthCheckRule | null
}
export interface ExperimentExposureQueryResponse {
kind: NodeKind.ExperimentExposureQuery
timeseries: ExperimentExposureTimeSeries[]
total_exposures: Record<string, number>
date_range: DateRange
sample_ratio_mismatch?: SampleRatioMismatch
bias_risk?: BiasRisk
/** Health check diagnostics that read the exposures: zero exposures, a sample ratio mismatch, and bias. Empty when every check passed. */
health_findings?: ExperimentExposureHealthFinding[]
/** The result of each check behind `health_findings`, so that a check that did not run is not read as passed. */
health_checks?: ExperimentExposureHealthCheck[]
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
export type CachedExperimentQueryResponse = CachedQueryResponse<ExperimentQueryResponse>
export type CachedNewExperimentQueryResponse = CachedQueryResponse<NewExperimentQueryResponse>
export type CachedExperimentExposureQueryResponse = CachedQueryResponse<ExperimentExposureQueryResponse>
export interface ExperimentMetricTimeseries {
experiment_id: number
metric_uuid: string
status: 'pending' | 'completed' | 'partial' | 'failed'
timeseries: { [date: string]: ExperimentQueryResponse } | null
errors: { [date: string]: string } | null
computed_at: string | null
created_at: string
updated_at: string
recalculation_status?: string | null
recalculation_created_at?: string | null
}
/**
* @discriminator kind
*/
export type InsightQuerySource = InsightQueryNode
export type InsightNodeKind = InsightQueryNode['kind']
export type InsightFilterProperty =
| 'trendsFilter'
| 'funnelsFilter'
| 'retentionFilter'
| 'pathsFilter'
| 'pathsV2Filter'
| 'stickinessFilter'
| 'calendarHeatmapFilter'
| 'lifecycleFilter'
| 'properties'
export type InsightFilter =
| TrendsFilter
| FunnelsFilter
| RetentionFilter
| PathsFilter
| PathsV2Filter
| StickinessFilter
| LifecycleFilter
| CalendarHeatmapFilter
| WebAnalyticsPropertyFilters
export type Day = integer
export interface InsightActorsQueryBase extends DataNode<ActorsQueryResponse> {
includeRecordings?: boolean
modifiers?: HogQLQueryModifiers
}
export interface InsightActorsQuery<
S extends InsightsQueryBase<AnalyticsQueryResponseBase> = InsightQuerySource,
> extends InsightActorsQueryBase {
kind: NodeKind.InsightActorsQuery
source: S
day?: string | Day
status?: string
/** An interval selected out of available intervals in source query. */
interval?: integer
series?: integer
breakdown?: string | BreakdownValueInt | string[]
compare?: 'current' | 'previous'
}
export interface StickinessActorsQuery extends InsightActorsQueryBase {
kind: NodeKind.StickinessActorsQuery
source: StickinessQuery
operator?: StickinessOperator
day?: string | Day
series?: integer
compare?: 'current' | 'previous'
}
export interface FunnelsActorsQuery extends InsightActorsQueryBase {
kind: NodeKind.FunnelsActorsQuery
source: FunnelsQuery
/** Index of the step for which we want to get the timestamp for, per person.
* Positive for converted persons, negative for dropped of persons. */
funnelStep?: integer
/** The breakdown value for which to get persons for. This is an array for
* person and event properties, a string for groups and an integer for cohorts. */
funnelStepBreakdown?: BreakdownKeyType
funnelTrendsDropOff?: boolean
/** Used together with `funnelTrendsDropOff` for funnels time conversion date for the persons modal. */
funnelTrendsEntrancePeriodStart?: string
/** When the source funnel has compare-to-previous enabled, scopes the actors to a single
* period. The runner resolves `'previous'` to the shifted date range; `'current'` (or unset)
* uses the source's own date range. */
compare?: 'current' | 'previous'
}
/** The kind of journey grid element a PathsV2ActorsQuery drills into. */
export enum PathsV2ElementType {
Node = 'node',
Edge = 'edge',
DropOff = 'dropOff',
Other = 'other',
Chain = 'chain',
}
/**
* Selects the journey grid element whose actors a PathsV2ActorsQuery returns. The same journeys
* that produced the grid produce these actor sets, so each element's modal equals its displayed
* number by construction.
*/
export type PathsV2ElementSelector = {
elementType: PathsV2ElementType
/**
* 0-based step index (column) of the element; for an edge, its source column. Required for
* node, other, dropOff, and positional edge elements.
*/
stepIndex?: integer
/** The node card's path item. Node elements only. */
item?: PathsV2Item
/** The edge's source path item; omit for the source column's "other" row. Edge elements only. */
source?: PathsV2Item
/** The edge's target path item; omit for the target column's "other" row. Edge elements only. */
target?: PathsV2Item
/**
* Match the source → target transition at any step of any whole journey instead of at one step
* pair: the position-free set behind an edge's anyStepCount. Requires a named source and
* target and open mode. Edge elements only.
*/
anyStep?: boolean
/**
* The chain's path items in order from the anchor. Returns the actors whose anchored sequence
* begins with exactly these items, the set behind a hover preview's per-chain counts. Chain
* elements only, anchored mode only. Bounded by the step maximum: a longer chain can never
* match a displayed card.
* @maxItems 20
*/
chain?: PathsV2Item[]
}
export interface PathsV2ActorsQuery extends InsightActorsQueryBase {
kind: NodeKind.PathsV2ActorsQuery
source: PathsV2Query
element: PathsV2ElementSelector
}
/** @format date-time */
export type DatetimeDay = string
export type BreakdownValueInt = integer
export interface BreakdownItem {
label: string
value: string | BreakdownValueInt
}
export interface MultipleBreakdownOptions {
values: BreakdownItem[]
}
export interface InsightActorsQueryOptionsResponse {
day?: { label: string; value: string | DatetimeDay | Day }[]
status?: { label: string; value: string }[]
interval?: {
label: string
/**
* An interval selected out of available intervals in source query
*/
value: integer
}[]
breakdown?: BreakdownItem[]
breakdowns?: MultipleBreakdownOptions[]
series?: {
label: string
value: integer
}[]
compare?: {
label: string
value: string
}[]
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
export const insightActorsQueryOptionsResponseKeys: string[] = [
'day',
'status',
'interval',
'breakdown',
'breakdowns',
'series',
'compare',
]
export type CachedInsightActorsQueryOptionsResponse = CachedQueryResponse<InsightActorsQueryOptionsResponse>
export interface InsightActorsQueryOptions extends Node<InsightActorsQueryOptionsResponse> {
kind: NodeKind.InsightActorsQueryOptions
source: InsightActorsQuery | FunnelsActorsQuery | StickinessActorsQuery | ExperimentActorsQuery | PathsV2ActorsQuery
}
export interface DatabaseSchemaSchema {
id: string
name: string
should_sync: boolean
incremental: boolean
status?: string
last_synced_at?: string
}
export interface DatabaseSchemaSource {
id: string
status: string
source_type: string
prefix: string
last_synced_at?: string
access_method?: string
}
export interface DatabaseSchemaField {
name: string
hogql_value: string
type: DatabaseSerializedFieldType
schema_valid: boolean
table?: string
fields?: string[]
chain?: (string | integer)[]
id?: string
}
export type DatabaseSchemaTableType =
| 'posthog'
| 'system'
| 'data_warehouse'
| 'view'
| 'batch_export'
| 'materialized_view'
| 'managed_view'
| 'endpoint'
export type DatabaseSchemaTableCertificationStatus = 'certified' | 'deprecated'
export interface DatabaseSchemaTableCertification {
/** Settled data catalog trust mark: 'certified' (prefer this source) or 'deprecated' (avoid it). */
status: DatabaseSchemaTableCertificationStatus
notes?: string
certified_by?: string
certified_at?: string
}
export interface DatabaseSchemaTableCommon {
type: DatabaseSchemaTableType
id: string
name: string
fields: Record<string, DatabaseSchemaField>
row_count?: number
/** Present only when the table or view carries a settled data catalog certification. */
certification?: DatabaseSchemaTableCertification
}
export interface DatabaseSchemaViewTable extends DatabaseSchemaTableCommon {
type: 'view'
query: HogQLQuery
}
export enum DatabaseSchemaManagedViewTableKind {
REVENUE_ANALYTICS_CHARGE = 'revenue_analytics_charge',
REVENUE_ANALYTICS_CUSTOMER = 'revenue_analytics_customer',
REVENUE_ANALYTICS_MRR = 'revenue_analytics_mrr',
REVENUE_ANALYTICS_PRODUCT = 'revenue_analytics_product',
REVENUE_ANALYTICS_REVENUE_ITEM = 'revenue_analytics_revenue_item',
REVENUE_ANALYTICS_SUBSCRIPTION = 'revenue_analytics_subscription',
}
export enum DataWarehouseSavedQueryOrigin {
DATA_WAREHOUSE = 'data_warehouse',
ENDPOINT = 'endpoint',
MANAGED_VIEWSET = 'managed_viewset',
}
export interface DatabaseSchemaManagedViewTable extends DatabaseSchemaTableCommon {
query: HogQLQuery
type: 'managed_view'
kind: DatabaseSchemaManagedViewTableKind
source_id?: string
}
export interface DatabaseSchemaEndpointTable extends DatabaseSchemaTableCommon {
query: HogQLQuery
type: 'endpoint'
status?: string
}
export interface DatabaseSchemaMaterializedViewTable extends DatabaseSchemaTableCommon {
type: 'materialized_view'
query: HogQLQuery
last_run_at?: string
status?: string
}
export interface DatabaseSchemaPostHogTable extends DatabaseSchemaTableCommon {
type: 'posthog'
}
export interface DatabaseSchemaSystemTable extends DatabaseSchemaTableCommon {
type: 'system'
}
export interface DatabaseSchemaDataWarehouseTable extends DatabaseSchemaTableCommon {
type: 'data_warehouse'
/** Absent for a dual-mode source's virtual tables, which have no synced S3 backing. */
format?: string
/** Absent for a dual-mode source's virtual tables, which have no synced S3 backing. */
url_pattern?: string
schema?: DatabaseSchemaSchema
source?: DatabaseSchemaSource
/** Alternate names the table is queryable by (e.g. the flat underscore form), in addition to `name`. */
search_aliases?: string[]
}
export interface DatabaseSchemaBatchExportTable extends DatabaseSchemaTableCommon {
type: 'batch_export'
}
export type DatabaseSchemaTable =
| DatabaseSchemaPostHogTable
| DatabaseSchemaSystemTable
| DatabaseSchemaDataWarehouseTable
| DatabaseSchemaViewTable
| DatabaseSchemaManagedViewTable
| DatabaseSchemaBatchExportTable
| DatabaseSchemaMaterializedViewTable
| DatabaseSchemaEndpointTable
export interface DatabaseSchemaQueryResponse {
tables: Record<string, DatabaseSchemaTable>
joins: DataWarehouseViewLink[]
}
export interface DatabaseSchemaQuery extends DataNode<DatabaseSchemaQueryResponse> {
kind: NodeKind.DatabaseSchemaQuery
/** Select the native managed Trino catalog instead of the default PostHog catalog. */
executionTarget?: 'default' | 'managed_trino'
/** Optional direct external data source id for schema introspection */
connectionId?: string
/** Only serialize these tables (keys as returned in the response, e.g. `events` or `zendesk.groups`). Omit for all tables. */
tables?: string[]
/** When false, skip serializing each table's fields (`fields` comes back empty). Defaults to true. */
includeFields?: boolean
}
export type DatabaseSerializedFieldType =
| 'integer'
| 'float'
| 'decimal'
| 'string'
| 'datetime'
| 'date'
| 'boolean'
| 'array'
| 'json'
| 'lazy_table'
| 'virtual_table'
| 'field_traverser'
| 'expression'
| 'view'
| 'materialized_view'
| 'unknown'
export type HogQLExpression = string
// Various utility types below
export interface DateRange {
/**
* Start of the date range. Accepts ISO 8601 timestamps (e.g., 2024-01-15T00:00:00Z)
* or relative formats: -7d (7 days ago), -2w (2 weeks ago), -1m (1 month ago),
* -1h (1 hour ago), -1mStart (start of last month), -1yStart (start of last year).
*/
date_from?: string | null
/** End of the date range. Same format as date_from. Omit or null for "now".
* A calendar day without a time (2024-01-15) is inclusive: it rounds to the last moment
* of that day in the project timezone, unless explicitDate is set.
*/
date_to?: string | null
/** Whether the date_from and date_to should be used verbatim. Disables
* rounding to the start and end of period.
* @default false
* */
explicitDate?: boolean | null
/**
* Restrict the query to events occurring on these ISO days of week
* (1=Monday to 7=Sunday), evaluated in the project timezone.
* Omit or empty for all days. Only applied by insight queries.
*/
daysOfWeek?: (1 | 2 | 3 | 4 | 5 | 6 | 7)[] | null
/**
* Exclude the current, still-collecting period by clipping date_to to the
* end of the last complete interval (evaluated in the project timezone).
* No-op when the range contains no complete interval. Only applied by
* insight queries.
* @default false
*/
excludeIncompletePeriods?: boolean | null
}
export interface ResolvedDateRangeResponse {
/** @format date-time */
date_from: string
/** @format date-time */
date_to: string
/**
* The earliest timestamp the query reads, when only its first interval depends on rows from before date_from.
* Lifecycle sets it to the start of the interval before the range.
* @format date-time
*/
read_from?: string
}
export type MultipleBreakdownType =
| 'person'
| 'event'
| 'event_metadata'
| 'element'
| 'group'
| 'session'
| 'hogql'
| 'cohort'
| 'revenue_analytics'
| 'data_warehouse'
| 'data_warehouse_person_property'
export interface Breakdown {
type?: MultipleBreakdownType | null
property: string | integer
normalize_url?: boolean
group_type_index?: integer | null
histogram_bin_count?: integer // trends breakdown histogram bin
}
export interface BreakdownFilter {
// TODO: unclutter
/** @default event */
breakdown_type?: BreakdownType | null
breakdown_limit?: integer
breakdown?: string | integer | (string | integer)[] | null
breakdown_normalize_url?: boolean
breakdown_path_cleaning?: boolean
/**
* @type array
* @maxItems 3
*/
breakdowns?: Breakdown[] // We want to limit maximum count of breakdowns avoiding overloading.
breakdown_group_type_index?: integer | null
breakdown_histogram_bin_count?: integer // trends breakdown histogram bin
breakdown_hide_other_aggregation?: boolean | null // hides the "other" field for trends
}
// TODO: Rename to `DashboardFilters` for consistency with `HogQLFilters`
export interface DashboardFilter {
date_from?: string | null
date_to?: string | null
properties?: AnyPropertyFilter[] | null
breakdown_filter?: BreakdownFilter | null
explicitDate?: boolean
/** Time granularity forced onto every insight that supports one. Absent/null = inherit. */
interval?: IntervalType | null
/** Tri-state test-account override. Null/absent = inherit; true = force on; false = force off. */
filterTestAccounts?: boolean | null
/** Period comparison forced onto every insight that supports one. Absent/null = inherit. */
compareFilter?: CompareFilter | null
/** @deprecated Ignored. Kept so that dashboards saved with label filters still load. */
metricFilters?: MetricsQueryFilter[] | null
/** Variables that metrics tiles refer to as `$name`. Other tiles ignore them. */
metricVariables?: MetricsDashboardVariable[] | null
}
export interface TileFilters {
date_from?: string | null | undefined
date_to?: string | null | undefined
properties?: AnyPropertyFilter[] | null | undefined
breakdown_filter?: BreakdownFilter | null | undefined
explicitDate?: boolean | undefined
interval?: IntervalType | null | undefined
filterTestAccounts?: boolean | null | undefined
compareFilter?: CompareFilter | null | undefined
/** When true, this tile ignores every dashboard-level filter; the tile's own overrides still apply. */
ignoreDashboardFilters?: boolean | null | undefined
}
export interface InsightsThresholdBounds {
/** Alert fires when the value drops below this number. */
lower?: number
/** Alert fires when the value exceeds this number. */
upper?: number
}
export enum InsightThresholdType {
ABSOLUTE = 'absolute',
PERCENTAGE = 'percentage',
}
export interface InsightThreshold {
/** Whether bounds are compared as absolute values or as percentage change from the previous interval. */
type: InsightThresholdType
bounds?: InsightsThresholdBounds
}
export enum AlertConditionType {
ABSOLUTE_VALUE = 'absolute_value', // default alert, checks absolute value of current interval
RELATIVE_INCREASE = 'relative_increase', // checks increase in value during current interval compared to previous interval
RELATIVE_DECREASE = 'relative_decrease', // checks decrease in value during current interval compared to previous interval
}
export interface AlertCondition {
// Conditions in addition to the separate threshold
// TODO: Think about things like relative thresholds, rate of change, etc.
type: AlertConditionType
}
export enum AlertState {
FIRING = 'Firing',
NOT_FIRING = 'Not firing',
ERRORED = 'Errored',
SNOOZED = 'Snoozed',
}
export enum AlertCalculationInterval {
REAL_TIME = 'real_time',
EVERY_15_MINUTES = 'every_15_minutes',
HOURLY = 'hourly',
DAILY = 'daily',
WEEKLY = 'weekly',
MONTHLY = 'monthly',
}
export interface TrendsAlertConfig {
type: 'TrendsAlertConfig'
/** Zero-based index of the series in the insight's query to monitor. */
series_index: integer
/** When true, evaluate the current (still incomplete) time interval in addition to completed ones. */
check_ongoing_interval?: boolean
}
/** How a SQL alert reads the query result.
* `last_row` = the query is ordered oldest→newest and the last row is the current value;
* `first_row` = the query is ordered newest→oldest and the first row is the current value
* (this mode bounds the fetch with a LIMIT since only the head is read);
* `any_row` = every row is checked and the alert fires if any value breaches (absolute conditions only). */
export type HogQLAlertEvaluation = 'last_row' | 'first_row' | 'any_row'
/** Alert config for HogQL/SQL-backed insights. The query owns its own time window. */
export interface HogQLAlertConfig {
type: 'HogQLAlertConfig'
/** Name of the result column to evaluate. When unset, the single numeric column is used
* (an error if the result has more than one numeric column). */
column?: string | null
/** How to read the result rows — an explicit choice, no implicit default. */
evaluation: HogQLAlertEvaluation
/** Column whose value labels the evaluated row(s) in breach messages: every row in `any_row`
* mode, or the single evaluated row in `last_row`/`first_row`. When unset, the first
* non-evaluated column is used, falling back to the row number (any_row) or the value column
* name (last_row/first_row). */
label_column?: string | null
}
/** How a funnel alert measures conversion at its step.
* `conversion_from_start` = step count / first-step count; `conversion_from_previous` = step count / previous-step count. */
export type FunnelConversionMetric = 'conversion_from_start' | 'conversion_from_previous'
/** Alert config for funnel insights. Evaluates the conversion rate (as a percentage) at one step. */
export interface FunnelsAlertConfig {
type: 'FunnelsAlertConfig'
/** Zero-based step index to evaluate. Null = the last step (overall conversion). */
funnel_step?: integer | null
metric: FunnelConversionMetric
/** When true, evaluate the current (still in-progress) period; by default only completed periods are used. */
check_ongoing_interval?: boolean
}
/** Alert config for metrics insights. Every series the query returns is evaluated; the alert fires if any breaches. */
export interface MetricsAlertConfig {
type: 'MetricsAlertConfig'
/** When true, anchor on the trailing (possibly still accumulating) bucket instead of the last complete one. */
check_ongoing_interval?: boolean
/** Values for the `$name` variables in the insight's query. */
variables?: Record<string, MetricsDashboardVariableSelection>
}
/** One blocked period for quiet hours: 24-hour HH:MM in the project timezone; interval is half-open [start, end). */
export interface AlertScheduleRestrictionWindow {
start: string
end: string
}
/** Quiet hours: local time windows when the alert must not run. At most five windows after API normalization. */
export interface AlertScheduleRestriction {
blocked_windows: AlertScheduleRestrictionWindow[]
}
// Detector types for anomaly detection alerts
export enum DetectorType {
ZSCORE = 'zscore',
MAD = 'mad',
THRESHOLD = 'threshold',
IQR = 'iqr',
COPOD = 'copod',
ECOD = 'ecod',
ISOLATION_FOREST = 'isolation_forest',
KNN = 'knn',
HBOS = 'hbos',
LOF = 'lof',
OCSVM = 'ocsvm',
PCA = 'pca',
LLM = 'llm',
}
/** Preprocessing transforms applied to the time series before detection */
export interface PreprocessingConfig {
/** Order of differencing. 0 = raw values, 1 = first-order diffs (default: 0) */
diffs_n?: integer
/** Moving average window size. 0 = no smoothing, >1 = smooth over n points (default: 0) */
smooth_n?: integer
/** Number of lag features. 0 = none, >0 = include n lagged values (default: 0) */
lags_n?: integer
}
export interface ZScoreDetectorConfig {
type: 'zscore'
/** Anomaly probability threshold [0-1]. Points above this probability are flagged (default: 0.9) */
threshold?: number
/** Rolling window size for calculating mean/std (default: 30) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface MADDetectorConfig {
type: 'mad'
/** Anomaly probability threshold [0-1]. Points above this probability are flagged (default: 0.9) */
threshold?: number
/** Rolling window size for calculating median/MAD (default: 30) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface IQRDetectorConfig {
type: 'iqr'
/** IQR multiplier for fence calculation (default: 1.5, use 3.0 for far outliers) */
multiplier?: number
/** Rolling window size for calculating quartiles (default: 30) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface ThresholdDetectorConfig {
type: 'threshold'
/** Upper bound - values above this are anomalies */
upper_bound?: number
/** Lower bound - values below this are anomalies */
lower_bound?: number
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface ECODDetectorConfig {
type: 'ecod'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface COPODDetectorConfig {
type: 'copod'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface IsolationForestDetectorConfig {
type: 'isolation_forest'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Number of trees in the forest (default: 100) */
n_estimators?: integer
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface KNNDetectorConfig {
type: 'knn'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Number of neighbors to consider (default: 5) */
n_neighbors?: integer
/** Distance method: 'largest', 'mean', 'median' (default: 'largest') */
method?: 'largest' | 'mean' | 'median'
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface HBOSDetectorConfig {
type: 'hbos'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Number of histogram bins (default: 10) */
n_bins?: integer
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface LOFDetectorConfig {
type: 'lof'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Number of neighbors for LOF (default: 20) */
n_neighbors?: integer
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface OCSVMDetectorConfig {
type: 'ocsvm'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** SVM kernel type (default: "rbf") */
kernel?: string
/** Upper bound on training errors fraction (default: 0.1) */
nu?: number
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
export interface PCADetectorConfig {
type: 'pca'
/** Anomaly probability threshold (default: 0.9) */
threshold?: number
/** Rolling window size — how many historical data points to train on (default: based on calculation interval) */
window?: integer
/** Preprocessing transforms applied before detection */
preprocessing?: PreprocessingConfig
}
/**
* Hands the series to a model instead of a statistical test. Carries no preprocessing block:
* differencing or smoothing would hide from the model exactly what it is meant to read.
*/
export interface LLMDetectorConfig {
type: 'llm'
/**
* What counts as unusual or interesting for this metric, in your own words. Optional.
* @maxLength 2000
*/
instructions?: string
}
export enum EnsembleOperator {
AND = 'and',
OR = 'or',
}
/**
* A single (leaf) detector config
* @discriminator type
*/
export type SingleDetectorConfig =
| ZScoreDetectorConfig
| MADDetectorConfig
| IQRDetectorConfig
| ThresholdDetectorConfig
| ECODDetectorConfig
| COPODDetectorConfig
| IsolationForestDetectorConfig
| KNNDetectorConfig
| HBOSDetectorConfig
| LOFDetectorConfig
| OCSVMDetectorConfig
| PCADetectorConfig
| LLMDetectorConfig
export type EnsembleSubDetectorConfig = Exclude<SingleDetectorConfig, LLMDetectorConfig>
export interface EnsembleDetectorConfig {
type: 'ensemble'
/** How to combine sub-detector results */
operator: EnsembleOperator
/** Sub-detector configurations (minimum 2) */
detectors: EnsembleSubDetectorConfig[]
}
/**
* Detector configuration types
* @discriminator type
*/
export type DetectorConfig = SingleDetectorConfig | EnsembleDetectorConfig
export interface HogCompileResponse {
bytecode: any[]
locals: any[]
}
export interface SuggestedQuestionsQuery extends DataNode<SuggestedQuestionsQueryResponse> {
kind: NodeKind.SuggestedQuestionsQuery
}
export interface SuggestedQuestionsQueryResponse {
questions: string[]
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
export type CachedSuggestedQuestionsQueryResponse = CachedQueryResponse<SuggestedQuestionsQueryResponse>
export interface TeamTaxonomyItem {
event: string
count: integer
}
export type TeamTaxonomyResponse = TeamTaxonomyItem[]
export interface InboxUsageQuery extends DataNode<InboxUsageQueryResponse> {
kind: NodeKind.InboxUsageQuery
/** UTC date range. Use explicitDate for exact bounds; the end is exclusive. */
dateRange: DateRange
}
export interface InboxUsageCredits {
/** Recorded finalized credits, including exemptions. Decimal strings preserve fractional credits. */
total_credits: string
/** Billing-exempt subset of total_credits. */
exempt_credits: string
incomplete: boolean
}
export interface InboxUsageSource extends InboxUsageCredits {
source_product: string | null
source_type: string | null
processing_credits: string
research_credits: string
implementation_credits: string
}
export interface InboxUsageScout extends InboxUsageCredits {
scout_config_id: string | null
skill_name: string
display_name: string
run_count: integer
/** Distinct reports emitted by this scout; reports may be shared across scouts. */
reports_produced: integer
}
export interface InboxUsage extends InboxUsageCredits {
project_id: integer
/** @format date-time */
period_start: string
/** @format date-time */
period_end: string
/** @format date-time */
as_of: string
/** Unfinalized credits created in the selected range, excluded from total_credits. */
unsettled_credits: string
untracked_scout_run_count: integer
/** Missing source metadata is retained in a null-source bucket. */
attribution_incomplete: boolean
/** Processing, research and implementation. Excludes scout execution. */
sources: InboxUsageSource[]
/** Scout execution only. These totals and source totals sum to total_credits. */
scouts: InboxUsageScout[]
pricing: InboxUsagePricing
}
export interface InboxUsagePricing {
currency: 'USD'
/** Multiply credits by this value for recorded USD usage, before billing adjustments. */
usd_per_credit: string
}
export interface InboxUsageQueryResponse extends AnalyticsQueryResponseBase {
results: InboxUsage
}
export type CachedInboxUsageQueryResponse = CachedQueryResponse<InboxUsageQueryResponse>
export interface TeamTaxonomyQuery extends DataNode<TeamTaxonomyQueryResponse> {
kind: NodeKind.TeamTaxonomyQuery
/** Number of rows to return */
limit?: integer
/** Number of rows to skip before returning rows */
offset?: integer
}
export interface TeamTaxonomyQueryResponse extends AnalyticsQueryResponseBase {
results: TeamTaxonomyResponse
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedTeamTaxonomyQueryResponse = CachedQueryResponse<TeamTaxonomyQueryResponse>
export interface EventTaxonomyItem {
property: string
sample_values: string[]
sample_count: integer
}
export type EventTaxonomyResponse = EventTaxonomyItem[]
export interface EventTaxonomyQuery extends DataNode<EventTaxonomyQueryResponse> {
kind: NodeKind.EventTaxonomyQuery
event?: string
actionId?: integer
properties?: string[]
maxPropertyValues?: integer
/** Number of rows to return */
limit?: integer
/** Number of rows to skip before returning rows */
offset?: integer
}
export interface EventTaxonomyQueryResponse extends AnalyticsQueryResponseBase {
results: EventTaxonomyResponse
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedEventTaxonomyQueryResponse = CachedQueryResponse<EventTaxonomyQueryResponse>
export interface ActorsPropertyTaxonomyResponse {
// Values can be floats and integers
sample_values: (string | number | boolean | integer)[]
sample_count: integer
}
export interface ActorsPropertyTaxonomyQuery extends DataNode<ActorsPropertyTaxonomyQueryResponse> {
kind: NodeKind.ActorsPropertyTaxonomyQuery
properties: string[]
groupTypeIndex?: integer
maxPropertyValues?: integer
}
export interface ActorsPropertyTaxonomyQueryResponse extends AnalyticsQueryResponseBase {
results: ActorsPropertyTaxonomyResponse | ActorsPropertyTaxonomyResponse[]
}
export type CachedActorsPropertyTaxonomyQueryResponse = CachedQueryResponse<ActorsPropertyTaxonomyQueryResponse>
export interface VectorSearchResponseItem {
id: string
distance: number
}
export type VectorSearchResponse = VectorSearchResponseItem[]
export interface VectorSearchQuery extends DataNode<VectorSearchQueryResponse> {
kind: NodeKind.VectorSearchQuery
embedding: number[]
embeddingVersion?: number
}
export interface VectorSearchQueryResponse extends AnalyticsQueryResponseBase {
results: VectorSearchResponse
}
export type CachedVectorSearchQueryResponse = CachedQueryResponse<VectorSearchQueryResponse>
export enum CustomChannelField {
UTMSource = 'utm_source',
UTMMedium = 'utm_medium',
UTMCampaign = 'utm_campaign',
ReferringDomain = 'referring_domain',
URL = 'url',
Pathname = 'pathname',
Hostname = 'hostname',
}
export enum CustomChannelOperator {
Exact = 'exact',
IsNot = 'is_not',
IsSet = 'is_set',
IsNotSet = 'is_not_set',
IContains = 'icontains',
NotIContains = 'not_icontains',
Regex = 'regex',
NotRegex = 'not_regex',
}
export interface CustomChannelCondition {
key: CustomChannelField
value?: string | string[]
op: CustomChannelOperator
id: string // the ID is only needed for the drag and drop, so only needs to be unique with one set of rules
}
export interface CustomChannelRule {
items: CustomChannelCondition[]
combiner: FilterLogicalOperator
channel_type: string
id: string // the ID is only needed for the drag and drop, so only needs to be unique with one set of rules
}
/** The event properties a project's own bot rule can match on. */
export enum CustomBotField {
RawUserAgent = '$raw_user_agent',
IP = '$ip',
Lib = '$lib',
Host = '$host',
Pathname = '$pathname',
CurrentURL = '$current_url',
Browser = '$browser',
OS = '$os',
BrowserLanguage = '$browser_language',
ScreenWidth = '$screen_width',
ScreenHeight = '$screen_height',
CountryCode = '$geoip_country_code',
Referrer = '$referrer',
ReferringDomain = '$referring_domain',
}
export enum CustomBotMatcher {
Contains = 'contains',
Regex = 'regex',
/** Case-sensitive equality against the whole property value. */
Exact = 'exact',
/** Matches an IP against a network range, e.g. `192.0.2.0/24`. Only valid with `$ip`. */
Cidr = 'cidr',
}
/** One condition of a project's bot rule. */
export interface CustomBotCondition {
/** The event property this condition reads. */
key: CustomBotField
/** Matched against the property named by `key`. */
pattern: string
matcher: CustomBotMatcher
id: string // the ID is only needed for the settings editor, so only needs to be unique within one rule
}
/** A bot a project defines itself, on top of PostHog's built-in bot list. */
export interface CustomBotRule {
/** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */
name: string
/** Reported by `$virt_traffic_category`. Defaults to `custom`. */
category?: string
/** Whether every condition must match (AND) or any one of them (OR). */
combiner: FilterLogicalOperator
items: CustomBotCondition[]
id: string // the ID is only needed for the settings editor, so only needs to be unique within one set of rules
}
export enum DefaultChannelTypes {
CrossNetwork = 'Cross Network',
PaidSearch = 'Paid Search',
PaidSocial = 'Paid Social',
PaidVideo = 'Paid Video',
PaidShopping = 'Paid Shopping',
PaidUnknown = 'Paid Unknown',
Direct = 'Direct',
OrganicSearch = 'Organic Search',
OrganicSocial = 'Organic Social',
OrganicVideo = 'Organic Video',
OrganicShopping = 'Organic Shopping',
AI = 'AI',
Push = 'Push',
SMS = 'SMS',
Audio = 'Audio',
Email = 'Email',
Referral = 'Referral',
Affiliate = 'Affiliate',
Unknown = 'Unknown',
}
// IMPORTANT: Changes to AIEventType values impact usage reporting and billing
// These values are used in SQL queries to compute usage and exclude AI events from standard event counts
// Any changes here will be reflected in the Python schema and affect billing calculations
export type AIEventType =
| '$ai_generation'
| '$ai_embedding'
| '$ai_span'
| '$ai_trace'
| '$ai_metric'
| '$ai_feedback'
| '$ai_evaluation'
| '$ai_tag'
| '$ai_trace_summary'
| '$ai_generation_summary'
| '$ai_trace_clusters'
| '$ai_generation_clusters'
export interface LLMTraceEvent {
id: string
event: AIEventType | string // Allow both specific AI events and other event types
properties: Record<string, any>
createdAt: string
sentiment?: LLMSentimentResult
}
export interface LLMSentimentMessage {
label: string
score: number
scores?: Record<string, number>
}
export interface LLMSentimentResult {
label: string
score: number
scores?: Record<string, number>
messages?: Record<string, LLMSentimentMessage>
message_count?: number
}
// Snake-case here for the DataTable component.
export interface LLMTracePerson {
uuid: string
created_at: string
properties: Record<string, unknown>
distinct_id: string
}
export interface LLMTrace {
id: string
aiSessionId?: string
createdAt: string
distinctId: string
person?: LLMTracePerson
totalLatency?: number
inputTokens?: number
outputTokens?: number
inputCost?: number
outputCost?: number
requestCost?: number
webSearchCost?: number
totalCost?: number
inputState?: any
outputState?: any
traceName?: string
errorCount?: number
events: LLMTraceEvent[]
isSupportTrace?: boolean
tools?: string[]
sentiment?: LLMSentimentResult
}
export interface TracesQueryResponse extends AnalyticsQueryResponseBase {
results: LLMTrace[]
hasMore?: boolean
limit?: integer
offset?: integer
columns?: string[]
}
export interface TracesQuery extends DataNode<TracesQueryResponse> {
kind: NodeKind.TracesQuery
dateRange?: DateRange
limit?: integer
offset?: integer
filterTestAccounts?: boolean
filterSupportTraces?: boolean
showColumnConfigurator?: boolean
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
/** Person who performed the event */
personId?: string
groupKey?: string
groupTypeIndex?: integer
/** Include stored sentiment evaluation results for returned traces and direct generation events. */
includeSentiment?: boolean
/** Use random ordering instead of timestamp DESC. Useful for representative sampling to avoid recency bias. */
randomOrder?: boolean
searchTerm?: string
}
export interface TraceQueryResponse extends AnalyticsQueryResponseBase {
results: LLMTrace[]
hasMore?: boolean
limit?: integer
offset?: integer
columns?: string[]
}
export interface TraceQuery extends DataNode<TraceQueryResponse> {
kind: NodeKind.TraceQuery
traceId: string
dateRange?: DateRange
/** Include stored sentiment evaluation results for the trace and its generations. */
includeSentiment?: boolean
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
}
export interface SessionQueryResponse extends AnalyticsQueryResponseBase {
results: LLMTrace[]
hasMore?: boolean
limit?: integer
offset?: integer
columns?: string[]
}
export interface SessionQuery extends DataNode<SessionQueryResponse> {
kind: NodeKind.SessionQuery
sessionId: string
dateRange?: DateRange
limit?: integer
offset?: integer
/** Include stored sentiment evaluation results for returned traces and generation events. */
includeSentiment?: boolean
}
export interface TraceNeighborsQueryResponse {
/** ID of the newer trace (chronologically after current) */
newerTraceId?: string
/** Timestamp of the newer trace */
newerTimestamp?: string
/** ID of the older trace (chronologically before current) */
olderTraceId?: string
/** Timestamp of the older trace */
olderTimestamp?: string
/** Measured timings for different parts of the query generation process */
timings?: QueryTiming[]
/** Data warehouse sync warnings — see AnalyticsQueryResponseBase.warnings for semantics. */
warnings?: DataWarehouseSyncWarning[]
}
export interface TraceNeighborsQuery extends DataNode<TraceNeighborsQueryResponse> {
kind: NodeKind.TraceNeighborsQuery
/** ID of the current trace to find neighbors for */
traceId: string
/** Timestamp of the current trace to find neighbors for */
timestamp: string
dateRange?: DateRange
filterTestAccounts?: boolean
filterSupportTraces?: boolean
/** Properties configurable in the interface */
properties?: AnyPropertyFilter[]
}
export type CachedTracesQueryResponse = CachedQueryResponse<TracesQueryResponse>
export type CachedTraceQueryResponse = CachedQueryResponse<TraceQueryResponse>
export type CachedSessionQueryResponse = CachedQueryResponse<SessionQueryResponse>
export type CachedTraceNeighborsQueryResponse = CachedQueryResponse<TraceNeighborsQueryResponse>
// NOTE: Keep in sync with posthog/models/exchange_rate/currencies.py
// to provide proper type safety for the baseCurrency field
export enum CurrencyCode {
AED = 'AED',
AFN = 'AFN',
ALL = 'ALL',
AMD = 'AMD',
ANG = 'ANG',
AOA = 'AOA',
ARS = 'ARS',
AUD = 'AUD',
AWG = 'AWG',
AZN = 'AZN',
BAM = 'BAM',
BBD = 'BBD',
BDT = 'BDT',
BGN = 'BGN',
BHD = 'BHD',
BIF = 'BIF',
BMD = 'BMD',
BND = 'BND',
BOB = 'BOB',
BRL = 'BRL',
BSD = 'BSD',
BTC = 'BTC',
BTN = 'BTN',
BWP = 'BWP',
BYN = 'BYN',
BZD = 'BZD',
CAD = 'CAD',
CDF = 'CDF',
CHF = 'CHF',
CLP = 'CLP',
CNY = 'CNY',
COP = 'COP',
CRC = 'CRC',
CVE = 'CVE',
CZK = 'CZK',
DJF = 'DJF',
DKK = 'DKK',
DOP = 'DOP',
DZD = 'DZD',
EGP = 'EGP',
ERN = 'ERN',
ETB = 'ETB',
EUR = 'EUR',
FJD = 'FJD',
GBP = 'GBP',
GEL = 'GEL',
GHS = 'GHS',
GIP = 'GIP',
GMD = 'GMD',
GNF = 'GNF',
GTQ = 'GTQ',
GYD = 'GYD',
HKD = 'HKD',
HNL = 'HNL',
HRK = 'HRK',
HTG = 'HTG',
HUF = 'HUF',
IDR = 'IDR',
ILS = 'ILS',
INR = 'INR',
IQD = 'IQD',
IRR = 'IRR',
ISK = 'ISK',
JMD = 'JMD',
JOD = 'JOD',
JPY = 'JPY',
KES = 'KES',
KGS = 'KGS',
KHR = 'KHR',
KMF = 'KMF',
KRW = 'KRW',
KWD = 'KWD',
KYD = 'KYD',
KZT = 'KZT',
LAK = 'LAK',
LBP = 'LBP',
LKR = 'LKR',
LRD = 'LRD',
LTL = 'LTL',
LVL = 'LVL',
LSL = 'LSL',
LYD = 'LYD',
MAD = 'MAD',
MDL = 'MDL',
MGA = 'MGA',
MKD = 'MKD',
MMK = 'MMK',
MNT = 'MNT',
MOP = 'MOP',
MRU = 'MRU',
MTL = 'MTL',
MUR = 'MUR',
MVR = 'MVR',
MWK = 'MWK',
MXN = 'MXN',
MYR = 'MYR',
MZN = 'MZN',
NAD = 'NAD',
NGN = 'NGN',
NIO = 'NIO',
NOK = 'NOK',
NPR = 'NPR',
NZD = 'NZD',
OMR = 'OMR',
PAB = 'PAB',
PEN = 'PEN',
PGK = 'PGK',
PHP = 'PHP',
PKR = 'PKR',
PLN = 'PLN',
PYG = 'PYG',
QAR = 'QAR',
RON = 'RON',
RSD = 'RSD',
RUB = 'RUB',
RWF = 'RWF',
SAR = 'SAR',
SBD = 'SBD',
SCR = 'SCR',
SDG = 'SDG',
SEK = 'SEK',
SGD = 'SGD',
SRD = 'SRD',
SSP = 'SSP',
STN = 'STN',
SYP = 'SYP',
SZL = 'SZL',
THB = 'THB',
TJS = 'TJS',
TMT = 'TMT',
TND = 'TND',
TOP = 'TOP',
TRY = 'TRY',
TTD = 'TTD',
TWD = 'TWD',
TZS = 'TZS',
UAH = 'UAH',
UGX = 'UGX',
USD = 'USD',
UYU = 'UYU',
UZS = 'UZS',
VES = 'VES',
VND = 'VND',
VUV = 'VUV',
WST = 'WST',
XAF = 'XAF',
XCD = 'XCD',
XOF = 'XOF',
XPF = 'XPF',
YER = 'YER',
ZAR = 'ZAR',
ZMW = 'ZMW',
}
export type RevenueCurrencyPropertyConfig = {
property?: string
static?: CurrencyCode
}
export type SubscriptionDropoffMode = 'last_event' | 'after_dropoff_period'
export interface RevenueAnalyticsEventItem {
eventName: string
revenueProperty: string
/**
* Property used to identify what product the revenue event refers to
* Useful when trying to break revenue down by a specific product
*/
productProperty?: string
/**
* Property used to identify whether the revenue event is connected to a coupon
* Useful when trying to break revenue down by a specific coupon
*/
couponProperty?: string
/**
* Property used to identify what subscription the revenue event refers to
* Useful when trying to detect churn/LTV/ARPU/etc.
*/
subscriptionProperty?: string
/**
* The number of days we still consider a subscription to be active
* after the last event. This is useful to avoid the current month's data
* to look as if most of the subscriptions have churned since we might not
* have an event for the current month.
*
* @default 45
*/
subscriptionDropoffDays: number
/**
* After a subscription has dropped off, when should we consider it to have ended?
* It should either be at the date of the last event (will alter past periods, the default),
* or at the date of the last event plus the dropoff period.
*
* @default "last_event"
*/
subscriptionDropoffMode: SubscriptionDropoffMode
/**
* TODO: In the future, this should probably be renamed to
* `currencyProperty` to follow the pattern above
*
* @default {"static": "USD"}
*/
revenueCurrencyProperty: RevenueCurrencyPropertyConfig
/**
* If true, the revenue will be divided by the smallest unit of the currency.
*
* For example, in case this is set to true,
* if the revenue is 1089 and the currency is USD, the revenue will be $10.89,
* but if the currency is JPY, the revenue will be ¥1089.
*
* @default false
*/
currencyAwareDecimal: boolean
}
export interface RevenueAnalyticsConfig {
/**
* @default []
*/
events: RevenueAnalyticsEventItem[]
/**
* @default false
*/
filter_test_accounts: boolean
}
export interface PageURL {
url: string
}
export interface WebPageURLSearchQuery extends WebAnalyticsQueryBase<WebPageURLSearchQueryResponse> {
kind: NodeKind.WebPageURLSearchQuery
searchTerm?: string
stripQueryParams?: boolean
limit?: integer
}
export interface WebPageURLSearchQueryResponse extends AnalyticsQueryResponseBase {
results: PageURL[]
hasMore?: boolean
limit?: integer
preComputeStrategy?: WebAnalyticsPreComputeStrategy
}
export type CachedWebPageURLSearchQueryResponse = CachedQueryResponse<WebPageURLSearchQueryResponse>
export interface WebNotableChangesQuery extends WebAnalyticsQueryBase<WebNotableChangesQueryResponse> {
kind: NodeKind.WebNotableChangesQuery
limit?: integer
}
export interface WebNotableChangeItem {
dimension_type: string
dimension_value: string
metric: string
current_value: number
previous_value: number
percent_change: number
impact_score: number
}
export interface WebNotableChangesQueryResponse extends AnalyticsQueryResponseBase {
results: WebNotableChangeItem[]
samplingRate?: SamplingRate
preComputeStrategy?: WebAnalyticsPreComputeStrategy
}
export type CachedWebNotableChangesQueryResponse = CachedQueryResponse<WebNotableChangesQueryResponse>
export type MarketingAnalyticsOrderBy = [string, 'ASC' | 'DESC']
export interface MarketingAnalyticsTableQuery extends Omit<
WebAnalyticsQueryBase<MarketingAnalyticsTableQueryResponse>,
'orderBy'
> {
kind: NodeKind.MarketingAnalyticsTableQuery
/** Return a limited set of data. Will use default columns if empty. */
select?: HogQLExpression[]
/** Columns to order by - similar to EventsQuery format */
orderBy?: MarketingAnalyticsOrderBy[]
/** Number of rows to return */
limit?: integer
/** Number of rows to skip before returning rows */
offset?: integer
/** Filter test accounts */
filterTestAccounts?: boolean
/** Draft conversion goal that can be set in the UI without saving */
draftConversionGoal?: ConversionGoalFilter | null
/** Compare to date range */
compareFilter?: CompareFilter
/** Filter by integration type */
integrationFilter?: IntegrationFilter
/** Drill-down hierarchy level: channel, source, or campaign (default) */
drillDownLevel?: MarketingAnalyticsDrillDownLevel
}
export interface MarketingAnalyticsItem extends WebAnalyticsItemBase<number | string> {
hasComparison?: boolean
}
export interface MarketingAnalyticsTableQueryResponse extends AnalyticsQueryResponseBase {
results: MarketingAnalyticsItem[][]
types?: unknown[]
columns?: unknown[]
hogql?: string
samplingRate?: SamplingRate
hasMore?: boolean
limit?: integer
offset?: integer
/** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a
* "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
precomputeNotReady?: boolean
/** ISO timestamp of the oldest precompute window backing this result. */
dataComputedAt?: string
/** ISO timestamp of when the numbers for the most recent day in the range were computed, at this time or
* later. It is the oldest stamp among the precompute windows that hold that day, across costs and
* conversion goals. Unset when no precompute was read or a window has no stamp. */
latestDayComputedAt?: string
}
export type CachedMarketingAnalyticsTableQueryResponse = CachedQueryResponse<MarketingAnalyticsTableQueryResponse>
export interface MarketingAnalyticsAggregatedQueryResponse extends AnalyticsQueryResponseBase {
results: Record<string, MarketingAnalyticsItem>
hogql?: string
samplingRate?: SamplingRate
/** True when a conversion goal's precompute has not been warmed for this window yet — the UI shows a
* "computing" state rather than empty results. Marketing analytics serves exclusively from precompute. */
precomputeNotReady?: boolean
/** ISO timestamp of the oldest precompute window backing this result. */
dataComputedAt?: string
/** ISO timestamp of when the numbers for the most recent day in the range were computed, at this time or
* later. It is the oldest stamp among the precompute windows that hold that day, across costs and
* conversion goals. Unset when no precompute was read or a window has no stamp. */
latestDayComputedAt?: string
}
export type CachedMarketingAnalyticsAggregatedQueryResponse =
CachedQueryResponse<MarketingAnalyticsAggregatedQueryResponse>
export interface MarketingAnalyticsAggregatedQuery extends Omit<
WebAnalyticsQueryBase<MarketingAnalyticsAggregatedQueryResponse>,
'orderBy' | 'limit' | 'offset'
> {
kind: NodeKind.MarketingAnalyticsAggregatedQuery
/** Return a limited set of data. Will use default columns if empty. */
select?: HogQLExpression[]
/** Draft conversion goal that can be set in the UI without saving */
draftConversionGoal?: ConversionGoalFilter
/** Filter by integration IDs */
integrationFilter?: IntegrationFilter
/** Drill-down hierarchy level: channel, source, or campaign (default) */
drillDownLevel?: MarketingAnalyticsDrillDownLevel
}
/**
* Dimension a session is sliced by, shared by the Attribution table and the Retention explorer. String
* values match MarketingAnalyticsDrillDownLevel for the
* levels they share, so both surfaces speak the same vocabulary. It's a separate enum because
* `ad_group`/`ad` can't be attributed to events at all (no ad identifier reaches the events table), while
* `referring_domain`/`landing_page` have no cost-side expression and so don't belong in the drill-down.
*/
export enum MarketingAnalyticsAttributionBreakdown {
Channel = 'channel',
Source = 'source',
Campaign = 'campaign',
Medium = 'medium',
Content = 'content',
Term = 'term',
ReferringDomain = 'referring_domain',
LandingPage = 'landing_page',
}
export interface MarketingAnalyticsAttributionQuery extends Omit<
WebAnalyticsQueryBase<MarketingAnalyticsAttributionQueryResponse>,
'orderBy' | 'compareFilter'
> {
kind: NodeKind.MarketingAnalyticsAttributionQuery
/** Row dimension. Defaults to channel. */
breakdownBy?: MarketingAnalyticsAttributionBreakdown
/** conversion_goal_id of the goal to attribute. The table is meaningless without one. */
conversionGoalId: string
/**
* Drop direct sessions from the touchpoint set before weights are computed, so the remaining
* touchpoints renormalize to full credit rather than losing direct's share.
*/
excludeDirectTraffic?: boolean
/**
* Drop touchpoints whose current breakdown value is empty or unknown — the "(none)" row — before
* weights are computed, so the remaining touchpoints renormalize to full credit.
*/
excludeUnattributed?: boolean
/**
* How many days before each conversion a touchpoint can earn credit, overriding the team's
* configured attribution window for this query only.
*/
lookbackWindowDays?: integer
/**
* Whether one person converting repeatedly counts once or every time. Null follows the goal's own
* math: unique-users goals count each person once, count-based goals count every conversion. Set
* explicitly to override. Counting every conversion makes the rate columns exceed 100%, since a
* person can convert more times than they visited.
*/
allowMultipleConversionsPerVisitor?: boolean
/** Number of rows to return */
limit?: integer
/** Number of rows to skip before returning rows */
offset?: integer
/** Filter test accounts */
filterTestAccounts?: boolean
}
/** One attribution model's credit for one breakdown row. */
export interface MarketingAnalyticsAttributionModelCell {
model: AttributionMode
/** Fractional for multi-touch models: each conversion's credit is split across its touchpoints. */
conversions: number
/** conversions / visitors. Null when the row has no visitors. */
conversionRate: number | null
/** Null unless the goal is revenue-bearing. */
conversionValue: number | null
}
export interface MarketingAnalyticsAttributionRow {
breakdownValue: string
/** Unique persons who arrived via this dimension in the date range, converters or not. */
visitors: integer
/**
* Conversions with at least one touchpoint on this dimension. Counted once per conversion, so a
* conversion influenced by several dimensions is counted in each of their rows. These
* deliberately sum to more than the total, unlike the per-model columns.
*/
influencedConversions: integer
influencedValue: number | null
/** One cell per model, always in the order given by the response's `models`. */
models: MarketingAnalyticsAttributionModelCell[]
}
export interface MarketingAnalyticsAttributionQueryResponse extends AnalyticsQueryResponseBase {
results: MarketingAnalyticsAttributionRow[]
/** Model order for the column groups. */
models: AttributionMode[]
/** Whether the goal is revenue-bearing, which gates the value columns. */
hasValue: boolean
/** The team's configured attribution window, for the tooltips. */
attributionWindowDays: integer
/**
* Whether this result counted a repeat converter's every conversion, after resolving the query's
* null against the goal's math. The rate columns are a true share only when this is false, so the
* table reads it to label them.
*/
allowsMultipleConversionsPerVisitor: boolean
/** Conversions with no touchpoint in the window. Reported in the footer, not in any row. */
unattributedConversions: integer
/** Total conversions in range, so the footer can say "N of M". */
totalConversions: integer
hogql?: string
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedMarketingAnalyticsAttributionQueryResponse =
CachedQueryResponse<MarketingAnalyticsAttributionQueryResponse>
export interface MarketingAnalyticsAttributionPathsQuery extends Omit<
WebAnalyticsQueryBase<MarketingAnalyticsAttributionPathsQueryResponse>,
'orderBy' | 'compareFilter'
> {
kind: NodeKind.MarketingAnalyticsAttributionPathsQuery
/** Path step dimension. Defaults to channel. */
breakdownBy?: MarketingAnalyticsAttributionBreakdown
/** conversion_goal_id of the goal whose conversions the paths lead to. */
conversionGoalId: string
/** Drop direct sessions from every path, mirroring the attribution table's option. */
excludeDirectTraffic?: boolean
/** Drop touchpoints whose breakdown value is empty or unknown — the "(none)" steps. */
excludeUnattributed?: boolean
/**
* How many days before each conversion a touchpoint can be part of its path, overriding the
* team's configured attribution window for this query only.
*/
lookbackWindowDays?: integer
/** Whether one person converting repeatedly contributes one path or one per conversion. Null follows the goal's math. */
allowMultipleConversionsPerVisitor?: boolean
/** Only paths with at least this many touchpoints, counted before truncation. */
minTouchpoints?: integer
/** Only paths with at most this many touchpoints, counted before truncation. */
maxTouchpoints?: integer
/** Number of rows to return */
limit?: integer
/** Number of rows to skip before returning rows */
offset?: integer
/** Filter test accounts */
filterTestAccounts?: boolean
}
export interface MarketingAnalyticsAttributionPathRow {
/**
* Breakdown values in touch order, oldest first. Consecutive repeats are preserved — collapsing
* them to "×N" is a display concern. Truncated to the most recent steps when the journey is
* longer than the grouping cap.
*/
path: string[]
/** Conversions whose in-window touchpoints form exactly this path. */
conversions: integer
/** Null unless the goal is revenue-bearing. */
conversionValue: number | null
/** True when at least one grouped conversion had more touchpoints than the path shows. */
pathTruncated: boolean
}
export interface MarketingAnalyticsAttributionPathsQueryResponse extends AnalyticsQueryResponseBase {
results: MarketingAnalyticsAttributionPathRow[]
/** All conversions in range, before the touchpoint-count filter. */
totalConversions: integer
/**
* Conversions with at least one in-window touchpoint. The share denominator — deliberately
* unfiltered by min/maxTouchpoints so shares stay comparable across filter values.
*/
attributedConversions: integer
/** The attribution window actually used, for the tooltips. */
attributionWindowDays: integer
/** Whether the goal is revenue-bearing, which gates the value column. */
hasValue: boolean
hogql?: string
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedMarketingAnalyticsAttributionPathsQueryResponse =
CachedQueryResponse<MarketingAnalyticsAttributionPathsQueryResponse>
/**
* Cohort and column period for the Retention explorer. Narrower than IntervalType, because hour and
* minute grains produce a matrix nobody can read.
*/
export enum MarketingAnalyticsRetentionInterval {
Day = 'day',
Week = 'week',
Month = 'month',
}
/**
* The omitted fields are ones this runner ignores, so leaving them settable would let a caller ask for
* something that does nothing. `interval` goes because `retentionInterval` shadows it, and
* `conversionGoal` because this table counts return visits rather than conversions.
*/
export interface MarketingAnalyticsRetentionQuery extends Omit<
WebAnalyticsQueryBase<MarketingAnalyticsRetentionQueryResponse>,
'orderBy' | 'compareFilter' | 'interval' | 'conversionGoal' | 'doPathCleaning' | 'sampling' | 'samplingFactor'
> {
kind: NodeKind.MarketingAnalyticsRetentionQuery
/** Return session-based 7/30-day metrics instead of the cohort matrix. Defaults to false. */
summary?: boolean
/** Include the previous acquisition period in summary mode. Defaults to false. */
comparePreviousPeriod?: boolean
/** Cohort dimension, read off each person's first session. Defaults to channel. */
breakdownBy?: MarketingAnalyticsAttributionBreakdown
/** Period for both the cohort rows and the return columns. Defaults to week. */
retentionInterval?: MarketingAnalyticsRetentionInterval
/** Return columns, counting period 0. Defaults to 8, clamped to 40. */
totalIntervals?: integer
/** Drop direct sessions when deciding first touch, mirroring the attribution explorer. */
excludeDirectTraffic?: boolean
/** Drop persons whose first session names nothing for the current breakdown. */
excludeUnattributed?: boolean
/**
* Only count persons with no session before the range, so a channel's cohorts are not inflated by
* users it acquired long ago. Defaults to true.
*/
onlyNewUsers?: boolean
/** How far back to look for a prior session. Defaults to 90, clamped to 365. */
newUserLookbackDays?: integer
/** Breakdown values kept before the rest roll into 'Other'. Defaults to 20. */
breakdownLimit?: integer
}
/** One cohort's activity in one period since acquisition. */
export interface MarketingAnalyticsRetentionCell {
/** Distinct persons from this cohort active in this period. */
count: integer
/** count / cohortSize. Null when the cohort is empty. */
rate: number | null
/**
* False when this period has not fully elapsed within the queried range, so a low cell reads as
* unfinished instead of as churn.
*/
complete: boolean
}
export interface MarketingAnalyticsRetentionRow {
breakdownValue: string
/** Start of the cohort's period, in the team's timezone. @format date-time */
cohortDate: string
/** 0-based position of this cohort from the range start. */
cohortIndex: integer
/** Persons acquired in this period under this breakdown value. The denominator for every cell. */
cohortSize: integer
/** One per column, index = periods since the cohort started. Always intervalCount long. */
values: MarketingAnalyticsRetentionCell[]
}
export interface MarketingAnalyticsRetentionSummaryRow {
breakdownValue: string
previous: boolean
acquired: integer
eligible7d: integer
returned7d: integer
eligible30d: integer
returned30d: integer
/**
* Estimated median calendar days from the first session to the first return on a later day, using
* the project's timezone. Includes observed returns within 30 days. Same-day visits do not count.
*/
medianReturnDays: number | null
/**
* People who returned on a later calendar day in the project's timezone within 30 days of their
* first session, including incomplete windows.
*/
returners: integer
}
export interface MarketingAnalyticsRetentionQueryResponse extends AnalyticsQueryResponseBase {
results: MarketingAnalyticsRetentionRow[]
/** Only populated in summary mode. Rates use the corresponding eligible population. */
summary?: MarketingAnalyticsRetentionSummaryRow[]
/** Column count. Every row's values array has this length. */
intervalCount: integer
interval: MarketingAnalyticsRetentionInterval
/** Column headers, e.g. ['Week 0', 'Week 1', ...]. */
labels: string[]
/** How many breakdown values were folded into 'Other', so the table can say so. */
otherBreakdownCount: integer
/**
* Older cohorts dropped to bound the matrix. Non-zero means the table covers less than the date
* range the filter bar shows, so the table has to say so.
*/
truncatedCohorts: integer
/** Distinct persons acquired across every cohort and breakdown value. */
totalCohortSize: integer
hogql?: string
}
export type CachedMarketingAnalyticsRetentionQueryResponse =
CachedQueryResponse<MarketingAnalyticsRetentionQueryResponse>
export interface MarketingAnalyticsSearchSource {
sourceType: 'GoogleAds' | 'BingAds' | 'GoogleSearchConsole'
/** For the Google Ads search term breakdown, the campaign table, which carries the account currency. */
statsTable: string
keywordTable?: string
placementTable?: string
queryPageTable?: boolean
/** Google Ads search terms from Search campaigns. */
searchTermTable?: string
/** Google Ads search terms from Performance Max campaigns. */
performanceMaxSearchTermTable?: string
}
export interface MarketingAnalyticsSearchQuery extends DataNode<MarketingAnalyticsSearchQueryResponse> {
kind: NodeKind.MarketingAnalyticsSearchQuery
dateRange?: DateRange
sources: MarketingAnalyticsSearchSource[]
compareFilter?: CompareFilter
search?: string
breakdown?: 'keyword' | 'page' | 'search_term'
keyword?: string
page?: string
normalizePageUrls?: boolean
includePostHogConversions?: boolean
}
export interface MarketingAnalyticsSearchMetrics {
clicks: number
impressions: number
cost: number | null
conversions: number | null
ctr: number | null
cpc: number | null
cpa: number | null
position?: number | null
/** Fraction of Google Search ad impressions shown among the top ads. */
topImpressionRate?: number | null
/** Fraction of Google Search ad impressions shown as the first ad. */
absoluteTopImpressionRate?: number | null
}
export interface MarketingAnalyticsSearchConversionGoal {
id: string
name: string
}
export interface MarketingAnalyticsSearchConversion extends MarketingAnalyticsSearchConversionGoal {
conversions: number | null
costPerConversion: number | null
previousConversions?: number | null
previousCostPerConversion?: number | null
}
export interface MarketingAnalyticsSearchRow extends MarketingAnalyticsSearchMetrics {
keyword: string | null
page?: string | null
platform: 'GoogleAds' | 'BingAds' | 'GoogleSearchConsole'
matchType: string | null
currency: string | null
previous?: MarketingAnalyticsSearchMetrics | null
posthogConversions?: MarketingAnalyticsSearchConversion[] | null
}
export interface MarketingAnalyticsSearchQueryResponse extends AnalyticsQueryResponseBase {
placementUnavailable?: boolean
results: MarketingAnalyticsSearchRow[]
posthogConversionGoals?: MarketingAnalyticsSearchConversionGoal[] | null
posthogConversionsWarning?: string | null
posthogAttributionMode?: AttributionMode | null
}
export type CachedMarketingAnalyticsSearchQueryResponse = CachedQueryResponse<MarketingAnalyticsSearchQueryResponse>
export type MarketingAnalyticsRecommendationsSourceType = 'GoogleAds' | 'GoogleSearchConsole'
export interface MarketingAnalyticsRecommendationsSource {
sourceType: MarketingAnalyticsRecommendationsSourceType
/** Google Ads campaign table. */
campaignTable?: string
/** Google Ads daily campaign stats table. */
campaignStatsTable?: string
/** Google Ads daily campaign impression share table. */
campaignImpressionShareTable?: string
/** Google Ads customer table, used for the account currency. */
customerTable?: string
/** Google Ads search term table for Search campaigns. */
searchTermTable?: string
/** Google Ads search term table split by the keyword that matched each term. */
searchTermKeywordTable?: string
/** Google Ads search term table for Performance Max campaigns. */
performanceMaxSearchTermTable?: string
/** Google Search Console table with one row per query, or per query and page. */
queryTable?: string
/** Google Search Console table with one row per query and page, used to find the page that ranks for a search. */
queryPageTable?: string
/** Google Search Console sites table, used to infer the brand name. */
sitesTable?: string
}
export interface MarketingAnalyticsRecommendationsQuery extends DataNode<MarketingAnalyticsRecommendationsQueryResponse> {
kind: NodeKind.MarketingAnalyticsRecommendationsQuery
dateRange?: DateRange
/** Tables to read. Omit to read every synced Google Ads and Google Search Console source in the project. */
sources?: MarketingAnalyticsRecommendationsSource[]
}
export type MarketingAnalyticsRecommendationRule =
| 'budget_constrained'
| 'brand_leak'
| 'scale_campaign'
| 'review_campaign'
| 'policy_limited'
| 'brand_overlap'
| 'content_gap'
| 'keyword_gap'
| 'spend_without_conversions'
| 'striking_distance'
export type MarketingAnalyticsRecommendationLevel = 'campaign' | 'search_term'
export type MarketingAnalyticsRecommendationImpactDirection = 'save' | 'gain' | 'invest' | 'keep'
export type MarketingAnalyticsRecommendationImpactType = 'measured' | 'estimated'
export interface MarketingAnalyticsRecommendationStep {
text: string
/** Text to paste into Google Ads at this step, such as a campaign name or keywords in match type syntax, one per line. */
copyValue?: string | null
/** Google Ads page for this step. It opens the section for the whole account, because links cannot filter to one campaign. */
url?: string | null
/** The words in `text` that link to `url`, usually the section name. */
linkText?: string | null
}
export interface MarketingAnalyticsRecommendation {
rule: MarketingAnalyticsRecommendationRule
level: MarketingAnalyticsRecommendationLevel
/** The campaign name or the search term the recommendation is about. */
subject: string
/** The campaign a search term recommendation applies to, when it applies to one. */
campaign?: string | null
action: string
reason: string
/** Monthly money impact in the account currency. Null when the rule has no money impact. */
impact?: number | null
impactDirection: MarketingAnalyticsRecommendationImpactDirection
impactType: MarketingAnalyticsRecommendationImpactType
currency?: string | null
/** How to apply the recommendation in Google Ads, in order. Empty when the rule has no steps yet. */
steps?: MarketingAnalyticsRecommendationStep[]
}
export interface MarketingAnalyticsRecommendationsQueryResponse extends AnalyticsQueryResponseBase {
results: MarketingAnalyticsRecommendation[]
/** Caveat to show with the results. The results are suggestions, and impact figures are estimates. */
disclaimer: string
}
export type CachedMarketingAnalyticsRecommendationsQueryResponse =
CachedQueryResponse<MarketingAnalyticsRecommendationsQueryResponse>
export interface WebAnalyticsExternalSummaryRequest {
date_from: string
date_to: string
explicit_date?: boolean
}
export type ExternalQueryErrorCode = 'platform_access_required' | 'query_execution_failed'
export type ExternalQueryStatus = 'success' | 'error'
export interface ExternalQueryError {
code: ExternalQueryErrorCode
detail: string
}
export interface WebAnalyticsExternalSummaryQueryResponse {
data: Record<string, any>
status: ExternalQueryStatus
error?: ExternalQueryError
}
export interface WebAnalyticsExternalSummaryQuery extends Pick<
WebAnalyticsQueryBase<WebAnalyticsExternalSummaryQueryResponse>,
'dateRange' | 'properties' | 'version'
> {
kind: NodeKind.WebAnalyticsExternalSummaryQuery
dateRange: DateRange
properties: WebAnalyticsPropertyFilters
response?: WebAnalyticsExternalSummaryQueryResponse
}
export type HeatMapQuerySource = EventsNode
export interface EventsHeatMapDataResult {
row: integer
column: integer
value: integer
}
export interface EventsHeatMapRowAggregationResult {
row: integer
value: integer
}
export interface EventsHeatMapColumnAggregationResult {
column: integer
value: integer
}
export interface EventsHeatMapStructuredResult {
data: EventsHeatMapDataResult[]
rowAggregations: EventsHeatMapRowAggregationResult[]
columnAggregations: EventsHeatMapColumnAggregationResult[]
allAggregations: integer
}
export type MarketingAnalyticsSchemaFieldTypes =
| 'string'
| 'integer'
| 'number'
| 'float'
| 'datetime'
| 'date'
| 'boolean'
export type MarketingAnalyticsSchemaField = {
type: MarketingAnalyticsSchemaFieldTypes[]
required: boolean
isCurrency: boolean
}
export enum MarketingAnalyticsColumnsSchemaNames {
Id = 'id',
Campaign = 'campaign',
Clicks = 'clicks',
Cost = 'cost',
Currency = 'currency',
Date = 'date',
Impressions = 'impressions',
Source = 'source',
ReportedConversion = 'reported_conversion',
ReportedConversionValue = 'reported_conversion_value',
AdGroupId = 'ad_group_id',
AdGroupName = 'ad_group_name',
AdId = 'ad_id',
AdName = 'ad_name',
}
export const MARKETING_ANALYTICS_SCHEMA: Record<MarketingAnalyticsColumnsSchemaNames, MarketingAnalyticsSchemaField> = {
[MarketingAnalyticsColumnsSchemaNames.Date]: {
type: ['datetime', 'date', 'string'],
required: true,
isCurrency: false,
}, // self managed sources dates are not converted to date type
[MarketingAnalyticsColumnsSchemaNames.Source]: { type: ['string'], required: true, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.Campaign]: { type: ['string'], required: true, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.Id]: { type: ['string'], required: true, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.Cost]: { type: ['float', 'integer'], required: true, isCurrency: true },
[MarketingAnalyticsColumnsSchemaNames.Clicks]: {
type: ['integer', 'number', 'float'],
required: false,
isCurrency: false,
},
[MarketingAnalyticsColumnsSchemaNames.Currency]: { type: ['string'], required: false, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.Impressions]: {
type: ['integer', 'number', 'float'],
required: false,
isCurrency: false,
},
[MarketingAnalyticsColumnsSchemaNames.ReportedConversion]: {
type: ['integer', 'number', 'float'],
required: false,
isCurrency: false,
},
[MarketingAnalyticsColumnsSchemaNames.ReportedConversionValue]: {
type: ['integer', 'number', 'float'],
required: false,
isCurrency: true,
},
[MarketingAnalyticsColumnsSchemaNames.AdGroupId]: { type: ['string'], required: false, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.AdGroupName]: { type: ['string'], required: false, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.AdId]: { type: ['string'], required: false, isCurrency: false },
[MarketingAnalyticsColumnsSchemaNames.AdName]: { type: ['string'], required: false, isCurrency: false },
}
export type SourceMap = Record<MarketingAnalyticsColumnsSchemaNames, string | undefined>
export type SchemaMap = Record<ConversionGoalSchema, string | undefined>
export type ConversionGoalFilter = (EventsNode | ActionsNode | DataWarehouseNode) & {
conversion_goal_id: string
conversion_goal_name: string
schema_map: SchemaMap
/**
* Marks this goal as customer-defining: a conversion here means the person became a customer
* (e.g. a payment or subscription), not an intermediate step like a sign up. It gates
* customer-based metrics such as CAC, whose denominator is this goal's conversions — its
* count, or its unique converters under dau math. That equals new customers only for a
* once-per-person moment: a repeatable event such as a monthly payment counts every time and
* understates cost per customer, and dedup under dau is per result row, so someone converting
* under two sources counts twice at channel level. Defaults to false.
*/
counts_as_customer?: boolean
/**
* Marks this goal as revenue-bearing: the value of a conversion is a monetary amount, not a
* count or an arbitrary numeric property. It gates revenue metrics such as ROAS and LTV:CAC.
* The amount itself comes from math_property, and its currency from
* math_property_revenue_currency, the same shape Revenue analytics uses for revenue events.
* Independent of counts_as_customer: a purchase is usually both, a trial signup neither.
* Defaults to false.
*/
counts_as_revenue?: boolean
}
export enum AttributionMode {
FirstTouch = 'first_touch',
LastTouch = 'last_touch',
Linear = 'linear',
TimeDecay = 'time_decay',
PositionBased = 'position_based',
}
export enum MatchField {
CAMPAIGN_NAME = 'campaign_name',
CAMPAIGN_ID = 'campaign_id',
}
export interface CampaignFieldPreference {
match_field: MatchField
}
export interface MarketingAnalyticsConfig {
sources_map?: Record<string, SourceMap>
conversion_goals?: ConversionGoalFilter[]
attribution_window_days?: number
attribution_mode?: AttributionMode
filter_test_accounts?: boolean
campaign_name_mappings?: Record<string, Record<string, string[]>>
custom_source_mappings?: Record<string, string[]>
campaign_field_preferences?: Record<string, CampaignFieldPreference>
}
export enum MarketingAnalyticsDrillDownLevel {
Channel = 'channel',
ChannelSource = 'channel_source',
Source = 'source',
Campaign = 'campaign',
AdGroup = 'ad_group',
Ad = 'ad',
Medium = 'medium',
Content = 'content',
Term = 'term',
}
export enum MarketingAnalyticsBaseColumns {
Id = 'ID',
Campaign = 'Campaign',
Source = 'Source',
AdGroup = 'Ad group',
AdGroupId = 'Ad group ID',
Ad = 'Ad',
AdId = 'Ad ID',
Cost = 'Cost',
Clicks = 'Clicks',
Impressions = 'Impressions',
CPC = 'CPC',
CTR = 'CTR',
ReportedConversions = 'Reported Conversions',
ReportedConversionValue = 'Reported Conversion Value',
ReportedROAS = 'Reported ROAS',
CostPerReportedConversions = 'Cost per Reported Conversions',
}
export type MarketingAnalyticsDrillDownConfig = {
columnAlias: string
excludedBaseColumns: MarketingAnalyticsBaseColumns[]
// When true, this level can't be attributed to events — drop conversion goal columns.
// Used for ad-group / ad levels where events can't be mapped to a specific ad.
excludesConversionGoals?: boolean
}
// Hierarchy columns are emitted only at AD_GROUP / AD levels — at every other level
// the runtime auto-excludes them via `getEffectiveExcludedColumns`. Keep this mirrored
// with backend `HIERARCHY_BASE_COLUMNS` (products/marketing_analytics/backend/hogql_queries/constants.py).
export const HIERARCHY_BASE_COLUMNS: ReadonlySet<MarketingAnalyticsBaseColumns> = new Set([
MarketingAnalyticsBaseColumns.AdGroup,
MarketingAnalyticsBaseColumns.AdGroupId,
MarketingAnalyticsBaseColumns.Ad,
MarketingAnalyticsBaseColumns.AdId,
])
export const HIERARCHY_DRILL_DOWN_LEVELS: ReadonlySet<MarketingAnalyticsDrillDownLevel> = new Set([
MarketingAnalyticsDrillDownLevel.AdGroup,
MarketingAnalyticsDrillDownLevel.Ad,
])
// Centralized drill-down level configuration. Hierarchy columns (ad_group / ad) are
// auto-excluded by the runtime at non-hierarchy levels — see HIERARCHY_BASE_COLUMNS —
// so they don't need to appear in `excludedBaseColumns` for CHANNEL/SOURCE/CAMPAIGN/UTM.
export const MARKETING_ANALYTICS_DRILL_DOWN_CONFIG: Record<
MarketingAnalyticsDrillDownLevel,
MarketingAnalyticsDrillDownConfig
> = {
[MarketingAnalyticsDrillDownLevel.Channel]: {
columnAlias: 'Channel',
excludedBaseColumns: [
MarketingAnalyticsBaseColumns.Id,
MarketingAnalyticsBaseColumns.Campaign,
MarketingAnalyticsBaseColumns.Source,
],
},
[MarketingAnalyticsDrillDownLevel.ChannelSource]: {
// Channel is the grouping alias; Source survives as the second column so a channel's
// rows break down into the sources that make it up.
columnAlias: 'Channel',
excludedBaseColumns: [MarketingAnalyticsBaseColumns.Id, MarketingAnalyticsBaseColumns.Campaign],
},
[MarketingAnalyticsDrillDownLevel.Source]: {
columnAlias: 'Source',
excludedBaseColumns: [
MarketingAnalyticsBaseColumns.Id,
MarketingAnalyticsBaseColumns.Campaign,
MarketingAnalyticsBaseColumns.Source,
],
},
[MarketingAnalyticsDrillDownLevel.Campaign]: {
columnAlias: MarketingAnalyticsBaseColumns.Campaign,
// Empty user-config preserves master's natural enum order at CAMPAIGN —
// hierarchy columns are auto-excluded by the runtime.
excludedBaseColumns: [],
},
[MarketingAnalyticsDrillDownLevel.AdGroup]: {
// Show Campaign + Source as parent context, plus Ad group + ID. Hide Id (campaign id),
// Ad / AdId since they don't apply at this level.
columnAlias: MarketingAnalyticsBaseColumns.AdGroup,
excludedBaseColumns: [
MarketingAnalyticsBaseColumns.Id,
MarketingAnalyticsBaseColumns.Ad,
MarketingAnalyticsBaseColumns.AdId,
],
excludesConversionGoals: true,
},
[MarketingAnalyticsDrillDownLevel.Ad]: {
// Full hierarchy: Campaign + Source + Ad group + Ad + Ad ID. Hide campaign Id and
// Ad group ID to keep the table readable.
columnAlias: MarketingAnalyticsBaseColumns.Ad,
excludedBaseColumns: [MarketingAnalyticsBaseColumns.Id, MarketingAnalyticsBaseColumns.AdGroupId],
excludesConversionGoals: true,
},
[MarketingAnalyticsDrillDownLevel.Medium]: {
columnAlias: 'Medium',
excludedBaseColumns: Object.values(MarketingAnalyticsBaseColumns),
},
[MarketingAnalyticsDrillDownLevel.Content]: {
columnAlias: 'Content',
excludedBaseColumns: Object.values(MarketingAnalyticsBaseColumns),
},
[MarketingAnalyticsDrillDownLevel.Term]: {
columnAlias: 'Term',
excludedBaseColumns: Object.values(MarketingAnalyticsBaseColumns),
},
}
/** Combine the level's user-facing excluded set with the hierarchy auto-exclusion.
* Mirror of backend `get_effective_excluded_columns`. */
export function getEffectiveExcludedColumns(
level: MarketingAnalyticsDrillDownLevel
): Set<MarketingAnalyticsBaseColumns> {
const userExcluded = new Set(MARKETING_ANALYTICS_DRILL_DOWN_CONFIG[level].excludedBaseColumns)
if (HIERARCHY_DRILL_DOWN_LEVELS.has(level)) {
return userExcluded
}
HIERARCHY_BASE_COLUMNS.forEach((col) => userExcluded.add(col))
return userExcluded
}
export enum MarketingAnalyticsConstants {
Goal = 'Goal',
CostPer = 'Cost per',
Roas = 'ROAS',
Customer = 'customer',
ConstantValuePrefix = 'const:',
}
/** Category for core events (lifecycle stages) */
export enum CoreEventCategory {
Acquisition = 'acquisition',
Activation = 'activation',
Monetization = 'monetization',
Expansion = 'expansion',
Referral = 'referral',
Retention = 'retention',
Churn = 'churn',
Reactivation = 'reactivation',
}
/** Unified core event stored in Team settings */
export interface CoreEvent {
/** Unique identifier */
id: string
/** Display name */
name: string
/** Optional description */
description?: string
/** Category (acquisition, activation, retention, referral, revenue) */
category: CoreEventCategory
/** Filter configuration - event, action, or data warehouse node (includes math support for sum, etc.) */
filter: EventsNode | ActionsNode | DataWarehouseNode
}
export const VALID_NATIVE_MARKETING_SOURCES = [
'GoogleAds',
'LinkedinAds',
'MetaAds',
'TikTokAds',
'RedditAds',
'BingAds',
'SnapchatAds',
'PinterestAds',
'AppleSearchAds',
'OpenAIAds',
'AmazonAds',
'RoktAds',
'TwitterAds',
] as const
export type NativeMarketingSource = (typeof VALID_NATIVE_MARKETING_SOURCES)[number]
export const MARKETING_INTEGRATION_CONFIGS = {
GoogleAds: {
sourceType: 'GoogleAds' as const,
nameField: 'campaign_name',
idField: 'campaign_id',
campaignTableName: 'campaign',
statsTableName: 'campaign_overview_stats',
defaultSources: [
'google',
'adwords',
'youtube',
'display',
'gmail',
'google_maps',
'google_play',
'google_discover',
'admob',
'waze',
] as const,
primarySource: 'google',
// Optional ad-group / ad warehouse schemas — present when the platform's API
// exposes per-level entity + stats tables. A source that omits them stays
// CAMPAIGN-only; the factory then reports `supports_level` False at AD_GROUP/AD.
adsetTableName: 'ad_group' as const,
adsetStatsTableName: 'ad_group_stats' as const,
adTableName: 'ad' as const,
adStatsTableName: 'ad_stats' as const,
},
LinkedinAds: {
sourceType: 'LinkedinAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaign_groups',
statsTableName: 'campaign_group_stats',
defaultSources: ['linkedin', 'li'] as const,
primarySource: 'linkedin',
// LinkedIn API hierarchy: Account → CampaignGroup → Campaign → Creative.
// We map CampaignGroups to "campaign" (matching the marketer's mental model),
// so LinkedIn's `campaigns` resource is what the rest of the platform calls
// "ad group", and `creatives` is what they call "ad".
adsetTableName: 'campaigns' as const,
adsetStatsTableName: 'campaign_stats' as const,
adTableName: 'creatives' as const,
adStatsTableName: 'creative_stats' as const,
},
MetaAds: {
sourceType: 'MetaAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_stats',
defaultSources: [
'meta',
'facebook',
'instagram',
'messenger',
'fb',
'whatsapp',
'audience_network',
'facebook_marketplace',
'threads',
'th',
] as const,
primarySource: 'meta',
adsetTableName: 'adsets' as const,
adsetStatsTableName: 'adset_stats' as const,
adTableName: 'ads' as const,
adStatsTableName: 'ad_stats' as const,
conversionActionTypes: {
omni: [
'omni_purchase',
'omni_lead',
'omni_complete_registration',
'omni_app_install',
'omni_subscribe',
] as const,
fallback: ['purchase', 'lead', 'complete_registration', 'app_install', 'subscribe'] as const,
specific: [
'offsite_conversion.fb_pixel_purchase',
'app_custom_event.fb_mobile_purchase',
'offsite_conversion.fb_pixel_lead',
'onsite_conversion.lead_grouped',
'offsite_conversion.fb_pixel_complete_registration',
'app_custom_event.fb_mobile_complete_registration',
'offsite_complete_registration_add_meta_leads',
'mobile_app_install',
'offsite_conversion.fb_pixel_subscribe',
] as const,
},
},
TikTokAds: {
sourceType: 'TikTokAds' as const,
nameField: 'campaign_name',
idField: 'campaign_id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_report',
defaultSources: ['tiktok'] as const,
primarySource: 'tiktok',
adsetTableName: 'ad_groups' as const,
adsetStatsTableName: 'ad_group_report' as const,
adTableName: 'ads' as const,
adStatsTableName: 'ad_report' as const,
},
RedditAds: {
sourceType: 'RedditAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_report',
defaultSources: ['reddit'] as const,
primarySource: 'reddit',
adsetTableName: 'ad_groups' as const,
adsetStatsTableName: 'ad_group_report' as const,
adTableName: 'ads' as const,
adStatsTableName: 'ad_report' as const,
},
BingAds: {
sourceType: 'BingAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_performance_report',
defaultSources: ['bing', 'microsoft', 'msads', 'bing_video'] as const,
primarySource: 'bing',
// At ad-group / ad level Bing's data import only ships performance *reports* —
// no separate entity tables. The report embeds the entity columns, so it
// doubles as both entity and stats: `adset*`/`ad*` `Table` and `StatsTable`
// point at the same name, and the factory detects the duplication to wire the
// matched DataWarehouseTable into both adapter slots. (Campaign level still has
// a distinct `campaigns` entity table separate from `campaign_performance_report`.)
adsetTableName: 'ad_group_performance_report' as const,
adsetStatsTableName: 'ad_group_performance_report' as const,
adTableName: 'ad_performance_report' as const,
adStatsTableName: 'ad_performance_report' as const,
},
SnapchatAds: {
sourceType: 'SnapchatAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_stats_daily',
defaultSources: ['snapchat'] as const,
primarySource: 'snapchat',
adsetTableName: 'ad_squads' as const,
adsetStatsTableName: 'ad_squad_stats_daily' as const,
adTableName: 'ads' as const,
adStatsTableName: 'ad_stats_daily' as const,
conversionFields: ['conversion_purchases', 'conversion_sign_ups', 'conversion_subscribe'] as const,
conversionValueFields: [
'conversion_purchases_value',
'conversion_sign_ups_value',
'conversion_subscribe_value',
] as const,
},
PinterestAds: {
sourceType: 'PinterestAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_analytics',
defaultSources: ['pinterest'] as const,
primarySource: 'pinterest',
adsetTableName: 'ad_groups' as const,
adsetStatsTableName: 'ad_group_analytics' as const,
adTableName: 'ads' as const,
adStatsTableName: 'ad_analytics' as const,
},
AppleSearchAds: {
sourceType: 'AppleSearchAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_report',
defaultSources: ['apple', 'apple_search_ads', 'apple_ads', 'asa'] as const,
primarySource: 'apple',
adsetTableName: 'ad_groups' as const,
adsetStatsTableName: 'ad_group_report' as const,
},
OpenAIAds: {
sourceType: 'OpenAIAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_insights',
defaultSources: ['openai', 'chatgpt', 'openai_ads'] as const,
primarySource: 'openai',
},
AmazonAds: {
sourceType: 'AmazonAds' as const,
nameField: 'name',
idField: 'campaign_id',
campaignTableName: 'sp_campaigns',
statsTableName: 'sp_campaign_reports',
defaultSources: ['amazon', 'amazon_ads'] as const,
primarySource: 'amazon',
},
TwitterAds: {
sourceType: 'TwitterAds' as const,
nameField: 'name',
idField: 'id',
campaignTableName: 'campaigns',
statsTableName: 'campaign_stats',
defaultSources: ['twitter', 'x', 'twitter_ads', 'x_ads'] as const,
primarySource: 'twitter',
adsetTableName: 'line_items' as const,
adsetStatsTableName: 'line_item_stats' as const,
},
RoktAds: {
sourceType: 'RoktAds' as const,
nameField: 'campaign_name',
idField: 'campaign_id',
campaignTableName: 'CampaignPerformance',
statsTableName: 'CampaignPerformance',
defaultSources: ['rokt', 'rokt_ads'] as const,
primarySource: 'rokt',
},
} as const
export type MarketingIntegrationConfig = (typeof MARKETING_INTEGRATION_CONFIGS)[NativeMarketingSource]
export type AmazonAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['AmazonAds']['defaultSources'][number]
export type TwitterAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['TwitterAds']['defaultSources'][number]
export type RoktAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['RoktAds']['defaultSources'][number]
export type AppleSearchAdsDefaultSources =
(typeof MARKETING_INTEGRATION_CONFIGS)['AppleSearchAds']['defaultSources'][number]
export type OpenAIAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['OpenAIAds']['defaultSources'][number]
export type GoogleAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['GoogleAds']['defaultSources'][number]
export type LinkedinAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['LinkedinAds']['defaultSources'][number]
export type MetaAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['MetaAds']['defaultSources'][number]
export type TikTokAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['TikTokAds']['defaultSources'][number]
export type RedditAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['RedditAds']['defaultSources'][number]
export type BingAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['BingAds']['defaultSources'][number]
export type SnapchatAdsDefaultSources = (typeof MARKETING_INTEGRATION_CONFIGS)['SnapchatAds']['defaultSources'][number]
export type PinterestAdsDefaultSources =
(typeof MARKETING_INTEGRATION_CONFIGS)['PinterestAds']['defaultSources'][number]
// Conversion fields for Snapchat Ads - extracted as types so they generate as StrEnum in Python
export type SnapchatAdsConversionFields =
(typeof MARKETING_INTEGRATION_CONFIGS)['SnapchatAds']['conversionFields'][number]
export type SnapchatAdsConversionValueFields =
(typeof MARKETING_INTEGRATION_CONFIGS)['SnapchatAds']['conversionValueFields'][number]
// Conversion action types for Meta Ads - extracted as types so they generate as StrEnum in Python
export type MetaAdsConversionOmniActionTypes =
(typeof MARKETING_INTEGRATION_CONFIGS)['MetaAds']['conversionActionTypes']['omni'][number]
export type MetaAdsConversionFallbackActionTypes =
(typeof MARKETING_INTEGRATION_CONFIGS)['MetaAds']['conversionActionTypes']['fallback'][number]
export type MetaAdsConversionSpecificActionTypes =
(typeof MARKETING_INTEGRATION_CONFIGS)['MetaAds']['conversionActionTypes']['specific'][number]
export const MARKETING_INTEGRATION_FIELD_MAP = Object.fromEntries(
VALID_NATIVE_MARKETING_SOURCES.map((source) => [
source,
{
nameField: MARKETING_INTEGRATION_CONFIGS[source].nameField,
idField: MARKETING_INTEGRATION_CONFIGS[source].idField,
},
])
) as unknown as Record<NativeMarketingSource, { nameField: string; idField: string }>
export const MARKETING_DEFAULT_SOURCE_MAPPINGS = Object.fromEntries(
VALID_NATIVE_MARKETING_SOURCES.map((source) => [source, [...MARKETING_INTEGRATION_CONFIGS[source].defaultSources]])
) as unknown as Record<NativeMarketingSource, string[]>
export interface MarketingIntegrationConfigType {
sourceType: NativeMarketingSource
nameField: string
idField: string
campaignTableName: string
statsTableName: string
defaultSources: string[]
primarySource: string
}
export enum InfinityValue {
INFINITY_VALUE = 999999,
NEGATIVE_INFINITY_VALUE = -999999,
}
export enum DashboardAutoRefreshInterval {
SECONDS = 1800,
}
/** Subscriptions a free-tier team may create. */
export enum SubscriptionFreeTierLimit {
COUNT = 5,
}
/** Maximum length, in characters, of an AI subscription prompt. */
export enum SubscriptionAIPromptMaxLength {
CHARACTERS = 4000,
}
/** Maximum number of dashboards and insights an AI subscription may use as context. */
export enum SubscriptionAIContextLimit {
COUNT = 3,
}
export type UsageMetricFormat = 'numeric' | 'currency'
export type UsageMetricDisplay = 'number' | 'sparkline'
export interface UsageMetric {
id: string
name: string
value: number
previous: number
change_from_previous_pct: number | null
format: UsageMetricFormat
display: UsageMetricDisplay
interval: integer
/** Daily values over the current interval period. Only populated when display is 'sparkline'. */
timeseries?: number[]
/** ISO date strings for sparkline tooltip labels. Only populated when display is 'sparkline'. */
timeseries_labels?: string[]
}
export interface UsageMetricsQueryResponse extends AnalyticsQueryResponseBase {
results: UsageMetric[]
}
export type CachedUsageMetricsQueryResponse = CachedQueryResponse<UsageMetricsQueryResponse>
export interface UsageMetricsQuery extends DataNode<UsageMetricsQueryResponse> {
kind: NodeKind.UsageMetricsQuery
/** Person ID to fetch metrics for. Mutually exclusive with group parameters. */
person_id?: string
/** Group type index. Required with group_key for group queries. */
group_type_index?: integer
/** Group key. Required with group_type_index for group queries. */
group_key?: string
}
/*
* Endpoints Usage Analytics
*/
export enum EndpointsUsageBreakdown {
Endpoint = 'Endpoint',
MaterializationType = 'MaterializationType',
ApiKey = 'ApiKey',
Status = 'Status',
}
export type EndpointsUsageOrderByField =
| 'requests'
| 'bytes_read'
| 'cpu_seconds'
| 'avg_query_duration_ms'
| 'error_rate'
export type EndpointsUsageOrderByDirection = 'ASC' | 'DESC'
export type EndpointsUsageOrderBy = [EndpointsUsageOrderByField, EndpointsUsageOrderByDirection]
/** Base interface for Endpoints usage queries */
interface EndpointsUsageQueryBase<R extends Record<string, any>> extends DataNode<R> {
dateRange?: DateRange
/** Filter to specific endpoints by name */
endpointNames?: string[]
/** Filter by materialization type */
materializationType?: 'materialized' | 'inline' | null
}
export type EndpointsUsageOverviewItemKey =
| 'total_requests'
| 'total_bytes_read'
| 'total_cpu_seconds'
| 'avg_query_duration_ms'
| 'p95_query_duration_ms'
| 'error_rate'
| 'materialized_requests'
| 'inline_requests'
export interface EndpointsUsageOverviewItem {
key: EndpointsUsageOverviewItemKey
value: number | null
previous?: number | null
changeFromPreviousPct?: number | null
}
export interface EndpointsUsageOverviewQueryResponse extends AnalyticsQueryResponseBase {
results: EndpointsUsageOverviewItem[]
}
export type CachedEndpointsUsageOverviewQueryResponse = CachedQueryResponse<EndpointsUsageOverviewQueryResponse>
export interface EndpointsUsageOverviewQuery extends EndpointsUsageQueryBase<EndpointsUsageOverviewQueryResponse> {
kind: NodeKind.EndpointsUsageOverviewQuery
/** Compare to previous period */
compareFilter?: CompareFilter
}
export interface EndpointsUsageTableQueryResponse extends AnalyticsQueryResponseBase {
results: unknown[]
columns?: unknown[]
types?: unknown[]
hasMore?: boolean
limit?: integer
offset?: integer
}
export type CachedEndpointsUsageTableQueryResponse = CachedQueryResponse<EndpointsUsageTableQueryResponse>
export interface EndpointsUsageTableQuery extends EndpointsUsageQueryBase<EndpointsUsageTableQueryResponse> {
kind: NodeKind.EndpointsUsageTableQuery
breakdownBy: EndpointsUsageBreakdown
orderBy?: EndpointsUsageOrderBy
limit?: integer
offset?: integer
}
export interface EndpointsUsageTrendsQueryResponse extends AnalyticsQueryResponseBase {
results: Record<string, any>[]
}
export type CachedEndpointsUsageTrendsQueryResponse = CachedQueryResponse<EndpointsUsageTrendsQueryResponse>
export interface EndpointsUsageTrendsQuery extends EndpointsUsageQueryBase<EndpointsUsageTrendsQueryResponse> {
kind: NodeKind.EndpointsUsageTrendsQuery
/** Metric to trend */
metric: 'bytes_read' | 'cpu_seconds' | 'requests' | 'query_duration' | 'error_rate'
/** Optional breakdown for stacked charts */
breakdownBy?: EndpointsUsageBreakdown
/** Time interval */
interval?: IntervalType
/** Compare to previous period */
compareFilter?: CompareFilter
}
export interface CustomerAnalyticsPinnedProperty {
kind: 'custom_property' | 'relationship' | 'account_field'
id: string
}
export interface CustomerAnalyticsConfig {
activity_event: EventsNode | ActionsNode
signup_pageview_event: EventsNode | ActionsNode
signup_event: EventsNode | ActionsNode
subscription_event: EventsNode | ActionsNode
payment_event: EventsNode | ActionsNode
account_group_type_index?: integer | null
default_pinned_properties?: CustomerAnalyticsPinnedProperty[]
}
/**
* Product item structure matching products.json.
* NOTE: These types must match the structure generated by build-products.mjs.
* Any changes to these types should be reflected in the build script.
*/
export interface ProductItem {
path: string
category: ProductItemCategory | null
iconType: string | null
type: string | null
intents: ProductKey[]
}
export enum ProductItemCategory {
ANALYTICS = 'Analytics',
DATA = 'Data',
AI_ENGINEERING = 'AI engineering',
PRODUCT_ENGINEERING = 'Product engineering',
MESSAGING = 'Messaging',
MONITORING = 'Monitoring',
TOOLS = 'Tools',
SCHEMA = 'Schema',
CDP = 'CDP',
UNRELEASED = 'Unreleased',
}
/**
* Products data structure matching products.json.
* NOTE: These types must match the structure generated by build-products.mjs.
* Any changes to these types should be reflected in the build script.
*/
export interface ProductsData {
products: ProductItem[]
games: ProductItem[]
metadata: ProductItem[]
}
/** Customization of the SQL editor. Extra keys are tolerated so older servers accept configs written by newer clients. */
export interface SQLEditorConfiguration {
/** Whether the SQL editor uses Vim keybindings. An absent value falls back to the legacy browser preference. */
vim_mode_enabled?: boolean
/**
* Vim commands to run when Vim mode starts, one per line, such as `imap jj <Esc>` or `set cursorblink`.
* @maxLength 10000
*/
vimrc?: string
[key: string]: unknown
}
/**
* Per-user UI customization, persisted on the User model as a single JSONB blob.
* A null configuration and any absent key mean "default".
* Writers must send the complete object; the server validates and replaces it wholesale.
*/
/** One person's display choices for the Analytics lists. */
export interface AnalyticsListDisplayConfiguration {
/** Leaves insights out of the All list. */
hide_insights?: boolean
/** The sort a list opens with. A column header click still changes the sort for that visit. */
default_sort?: '-last_viewed_at' | '-created_at'
}
export interface TicketSidebarConfiguration {
/** Widget keys in display order. Typed as strings so a layout naming a removed widget still validates. */
order?: string[]
hidden?: string[]
}
export interface UserUIConfiguration {
/**
* Schema version of this configuration blob, for future format migrations.
* @asType integer
*/
version: number
sql_editor?: SQLEditorConfiguration
analytics_list?: AnalyticsListDisplayConfiguration
ticket_sidebar?: TicketSidebarConfiguration
[key: string]: unknown
}
// Keep this in alphabetical order if you wanna maintain Rafa's sanity
export enum ProductKey {
ACTIONS = 'actions',
AI_OBSERVABILITY = 'llm_analytics',
ALERTS = 'alerts',
ANNOTATIONS = 'annotations',
AUTORESEARCH = 'autoresearch',
BUSINESS_KNOWLEDGE = 'business_knowledge',
COHORTS = 'cohorts',
COMMENTS = 'comments',
CONVERSATIONS = 'conversations',
CUSTOMER_ANALYTICS = 'customer_analytics',
DASHBOARDS = 'dashboards',
DATA_CATALOG = 'data_catalog',
DATA_WAREHOUSE = 'data_warehouse',
DATA_WAREHOUSE_SAVED_QUERY = 'data_warehouse_saved_queries',
EARLY_ACCESS_FEATURES = 'early_access_features',
ENDPOINTS = 'endpoints',
ENGINEERING_ANALYTICS = 'engineering_analytics',
ERROR_TRACKING = 'error_tracking',
EXPERIMENTS = 'experiments',
FEATURE_FLAGS = 'feature_flags',
GROUP_ANALYTICS = 'group_analytics',
HEATMAPS = 'heatmaps',
HISTORY = 'history',
INGESTION_WARNINGS = 'ingestion_warnings',
INTEGRATIONS = 'integrations',
LLM_CLUSTERS = 'llm_clusters',
LLM_DATASETS = 'llm_datasets',
LLM_EVALUATIONS = 'llm_evaluations',
LLM_PROMPTS = 'llm_prompts',
LOGS = 'logs',
MANAGED_WAREHOUSE = 'managed_warehouse',
MARKETING_ANALYTICS = 'marketing_analytics',
MAX = 'max',
MCP_ANALYTICS = 'mcp_analytics',
MOBILE_REPLAY = 'mobile_replay',
NOTEBOOKS = 'notebooks',
PERSONS = 'persons',
PIPELINE_BATCH_EXPORTS = 'pipeline_batch_exports',
PIPELINE_DESTINATIONS = 'pipeline_destinations',
PIPELINE_TRANSFORMATIONS = 'pipeline_transformations',
PLATFORM_AND_SUPPORT = 'platform_and_support',
POSTHOG_AI_ONBOARDING = 'posthog_ai_onboarding',
POSTHOG_DESKTOP = 'posthog_desktop',
POSTHOG_GITHUB = 'posthog_github',
POSTHOG_SLACK = 'posthog_slack',
PRODUCT_ANALYTICS = 'product_analytics',
PRODUCT_TOURS = 'product_tours',
PULSE = 'pulse',
REVENUE_ANALYTICS = 'revenue_analytics',
REVIEW_HOG = 'review_hog',
SELF_DRIVING = 'self_driving',
SESSION_REPLAY = 'session_replay',
REPLAY_VISION = 'replay_vision',
SITE_APPS = 'site_apps',
SKILLS = 'skills',
SUBSCRIPTIONS = 'subscriptions',
STREAMLIT_APPS = 'streamlit_apps',
SURVEYS = 'surveys',
TASKS = 'tasks',
TEAMS = 'teams',
TOOLBAR = 'toolbar',
TRACING = 'tracing',
UPTIME_MONITORING = 'uptime_monitoring',
METRICS = 'metrics',
VISUAL_REVIEW = 'visual_review',
WEB_ANALYTICS = 'web_analytics',
WORKFLOWS = 'workflows',
}
export enum ProductIntentContext {
// Onboarding
ONBOARDING_PRODUCT_SELECTED_PRIMARY = 'onboarding product selected - primary',
ONBOARDING_PRODUCT_SELECTED_SECONDARY = 'onboarding product selected - secondary',
QUICK_START_PRODUCT_SELECTED = 'quick start product selected',
// Data Warehouse
SELECTED_CONNECTOR = 'selected connector',
SQL_EDITOR_EMPTY_STATE = 'sql editor empty state',
DATA_WAREHOUSE_SOURCES_TABLE = 'data warehouse sources table',
// Managed Warehouse
MANAGED_WAREHOUSE_PROVISIONED = 'managed warehouse provisioned',
// Experiments
EXPERIMENT_CREATED = 'experiment created',
EXPERIMENT_ANALYZED = 'experiment analyzed',
EXPERIMENT_VIEW_RECORDINGS = 'experiment view recordings',
EXPERIMENT_REPLAY_VISION_SCANNER_CREATED = 'experiment replay vision scanner created',
EXPERIMENT_CREATE_SCANNER = 'experiment create scanner',
// Feature Flags
FEATURE_FLAG_CREATED = 'feature flag created',
// Session Replay
SESSION_REPLAY_SET_FILTERS = 'session_replay_set_filters',
SESSION_REPLAY_EXPERIMENT_LINK_CLICKED = 'session_replay_experiment_link_clicked',
SESSION_REPLAY_SAVE_FILTERS_AS_SCANNER = 'session_replay_save_filters_as_scanner',
// Replay Vision
// Shallow: dwelled on the scanner list long enough to have read it. Deliberately not a bare
// pageview — a mount-and-bounce must not start the activation clock for the team.
REPLAY_VISION_VIEWED = 'replay_vision_viewed',
// Deep, both registered server-side so agent/API callers count too, not just the app.
REPLAY_VISION_SCANNER_CREATED = 'replay_vision_scanner_created',
REPLAY_VISION_SCAN_TRIGGERED = 'replay_vision_scan_triggered',
// Error Tracking
ERROR_TRACKING_EXCEPTION_AUTOCAPTURE_ENABLED = 'error_tracking_exception_autocapture_enabled',
ERROR_TRACKING_ISSUE_SORTING = 'error_tracking_issue_sorting',
ERROR_TRACKING_DOCS_VIEWED = 'error_tracking_docs_viewed',
ERROR_TRACKING_ISSUE_EXPLAINED = 'error_tracking_issue_explained',
ERROR_TRACKING_SCAN_WITH_VISION = 'error_tracking_scan_with_vision',
// LLM Analytics
LLM_ANALYTICS_VIEWED = 'llm_analytics_viewed',
LLM_ANALYTICS_TRACE_VIEWED = 'llm_analytics_trace_viewed',
LLM_ANALYTICS_DOCS_VIEWED = 'llm_analytics_docs_viewed',
LLM_CLUSTER_EXPLORED = 'llm_cluster_explored',
LLM_DATASET_CREATED = 'llm_dataset_created',
LLM_EVALUATION_CREATED = 'llm_evaluation_created',
LLM_PROMPT_CREATED = 'llm_prompt_created',
// MCP Analytics
MCP_ANALYTICS_VIEWED = 'mcp_analytics_viewed',
MCP_ANALYTICS_CONNECTED = 'mcp_analytics_connected',
// Logs
LOGS_DOCS_VIEWED = 'logs_docs_viewed',
LOGS_SET_FILTERS = 'logs_set_filters',
LOGS_SETTINGS_OPENED = 'logs_settings_opened',
// Metrics
METRICS_DOCS_VIEWED = 'metrics_docs_viewed',
METRICS_VIEWER_QUERY_RUN = 'metrics_viewer_query_run',
METRICS_SQL_QUERY_RUN = 'metrics_sql_query_run',
METRICS_QUERY_SAVED = 'metrics_query_saved',
METRICS_FIRST_INGESTED = 'metrics_first_ingested',
METRICS_SCRAPE_AGENT_SNIPPET_COPIED = 'metrics_scrape_agent_snippet_copied',
// Product Analytics
TAXONOMIC_FILTER_EMPTY_STATE = 'taxonomic filter empty state',
CREATE_EXPERIMENT_FROM_FUNNEL_BUTTON = 'create_experiment_from_funnel_button',
// Web Analytics
WEB_ANALYTICS_INSIGHT = 'web_analytics_insight',
WEB_VITALS_INSIGHT = 'web_vitals_insight',
WEB_ANALYTICS_RECORDINGS = 'web_analytics_recordings',
WEB_ANALYTICS_ERROR_TRACKING = 'web_analytics_error_tracking',
WEB_ANALYTICS_ERRORS = 'web_analytics_errors',
WEB_ANALYTICS_FRUSTRATING_PAGES = 'web_analytics_frustrating_pages',
// Actions
ACTION_VIEW_RECORDINGS = 'action_view_recordings',
// Persons
PERSON_VIEW_RECORDINGS = 'person_view_recordings',
// Feature Flags
FEATURE_FLAG_CREATE_INSIGHT = 'feature_flag_create_insight',
FEATURE_FLAG_VIEW_RECORDINGS = 'feature_flag_view_recordings',
// Early Access Features
EARLY_ACCESS_FEATURE_VIEW_RECORDINGS = 'early_access_feature_view_recordings',
// Data Warehouse -> Revenue Analytics Cross-sell
DATA_WAREHOUSE_STRIPE_SOURCE_CREATED = 'data_warehouse_stripe_source_created',
// Surveys
SURVEYS_VIEWED = 'surveys_viewed',
SURVEY_ADD_NEW = 'survey_add_new',
SURVEY_CREATED = 'survey_created',
SURVEY_LAUNCHED = 'survey_launched',
SURVEY_VIEWED = 'survey_viewed',
SURVEY_COMPLETED = 'survey_completed', // stop survey
SURVEY_RESUMED = 'survey_resumed',
SURVEY_ARCHIVED = 'survey_archived',
SURVEY_UNARCHIVED = 'survey_unarchived',
SURVEY_DELETED = 'survey_deleted',
SURVEY_DUPLICATED = 'survey_duplicated',
SURVEY_BULK_DUPLICATED = 'survey_bulk_duplicated',
SURVEY_EDITED = 'survey_edited',
SURVEY_ANALYZED = 'survey_analyzed',
QUICK_SURVEY_STARTED = 'quick_survey_started',
// Revenue Analytics
REVENUE_ANALYTICS_EVENT_CREATED = 'revenue_analytics_event_created',
// Marketing Analytics
MARKETING_ANALYTICS_SOURCE_CONFIGURED = 'marketing_analytics_source_configured',
MARKETING_ANALYTICS_SETTINGS_UPDATED = 'marketing_analytics_settings_updated',
MARKETING_ANALYTICS_DASHBOARD_INTERACTION = 'marketing_analytics_dashboard_interaction',
MARKETING_ANALYTICS_ADS_INTEGRATION_VISITED = 'marketing_analytics_ads_integration_visited',
MARKETING_ANALYTICS_DATA_SOURCE_CONNECTED = 'marketing_analytics_data_source_connected',
MARKETING_ANALYTICS_ONBOARDING_COMPLETED = 'marketing_analytics_onboarding_completed',
// Customer Analytics
CUSTOMER_ANALYTICS_DASHBOARD_BUSINESS_MODE_CHANGED = 'customer_analytics_dashboard_business_mode_changed',
CUSTOMER_ANALYTICS_DASHBOARD_CONFIGURATION_BUTTON_CLICKED = 'customer_analytics_dashboard_configuration_button_clicked',
CUSTOMER_ANALYTICS_DASHBOARD_FILTERS_CHANGED = 'customer_analytics_dashboard_filters_changed',
CUSTOMER_ANALYTICS_DASHBOARD_EVENTS_SAVED = 'customer_analytics_dashboard_events_saved',
CUSTOMER_ANALYTICS_VIEWED = 'customer_analytics_viewed',
CUSTOMER_ANALYTICS_USAGE_METRIC_CREATED = 'customer_analytics_usage_metric_created',
// Nav Panel Advertisement
NAV_PANEL_ADVERTISEMENT_CLICKED = 'nav_panel_advertisement_clicked',
// Feature previews
FEATURE_PREVIEW_ENABLED = 'feature_preview_enabled',
// Workflows
WORKFLOW_CREATED = 'workflow_created',
// Data Pipelines
DATA_PIPELINE_CREATED = 'data_pipeline_created',
BATCH_EXPORT_CREATED = 'batch_export_created',
BATCH_EXPORT_UPDATED = 'batch_export_updated',
BATCH_EXPORT_BACKFILL_CREATED = 'batch_export_backfill_created',
// Notebooks
NOTEBOOK_CREATED = 'notebook_created',
// Product Tours
PRODUCT_TOUR_CREATED = 'product_tour_created',
// Tasks
TASK_CREATED = 'task_created',
// Toolbar
TOOLBAR_LAUNCHED = 'toolbar_launched',
// Used by the backend but defined here for type safety
VERCEL_INTEGRATION = 'vercel_integration',
// Endpoints
ENDPOINTS_VIEWED = 'endpoints_viewed',
ENDPOINT_CREATED = 'endpoint_created',
ENDPOINT_CREATED_FROM_INSIGHT = 'endpoint_created_from_insight',
ENDPOINT_CREATED_FROM_SQL_EDITOR = 'endpoint_created_from_sql_editor',
// Tracing
TRACING_DOCS_VIEWED = 'tracing_docs_viewed',
}
// Known prod_interest values from posthog.com
export type WebsiteBrowsingHistoryProdInterest =
| 'product-analytics'
| 'web-analytics'
| 'session-replay'
| 'feature-flags'
| 'experiments'
| 'error-tracking'
| 'surveys'
| 'data-warehouse'
| 'llm-analytics'
| 'revenue-analytics'
| 'workflows'
| 'logs'
| 'endpoints'
export interface ReplayInactivityPeriod {
ts_from_s: number
ts_to_s?: number
active: boolean
recording_ts_from_s?: number
recording_ts_to_s?: number
}
export enum DomainConnectProviderName {
Cloudflare = 'Cloudflare',
Vercel = 'Vercel',
}
export enum PropertyType {
Event = 'event',
Person = 'person',
}
export interface PropertyValueItem {
name: string | number | boolean | null
count?: integer
}
export interface PropertyValuesQuery extends DataNode<PropertyValuesQueryResponse> {
kind: NodeKind.PropertyValuesQuery
property_type: PropertyType
property_key: string
search_value?: string
event_names?: string[]
is_column?: boolean
}
export interface PropertyValuesQueryResponse extends AnalyticsQueryResponseBase {
results: PropertyValueItem[]
}
export type CachedPropertyValuesQueryResponse = CachedQueryResponse<PropertyValuesQueryResponse>