Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(marketing-analytics): guard cost trends with precompute coverage (#118032)

Javier Bahamondes475a4abfc1e6
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 203d05beeb95..c20517db75ed 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -147,6 +147,18 @@ Both cards have **AND / OR groups**. Choose **AND (match all)** or **OR (match a
Top N selects categories before result filters run. Comparison periods apply the same result conditions independently. Result filters hide detail groups; totals still aggregate all data matching the row filters. Table calculations use the full aggregated result before result filtering. Query usage events include result-filter and group counts without their values.
+## Marketing analytics cost charts
+
+The `marketing-analytics-costs-precomputation` flag controls whether the cost trend can use precomputed costs.
+The backend checks materialization jobs for every displayed source over the requested date range and comparison period.
+It uses precomputed costs only when all windows are ready and unexpired.
+An in-progress refresh can temporarily route the chart to the original sources until coverage is ready.
+Opening the chart as an editable insight uses its original source series without the automatic precompute selection.
+Completed windows with zero rows count as covered.
+Missing, expired, inaccessible, or unmaterializable sources use the original live warehouse series for the whole chart.
+Coverage check errors also fall back to the live query.
+This read-only check does not start or wait for materialization jobs.
+
## Apple Ads in Marketing analytics
Marketing analytics support is controlled by the boolean organization flag `marketing-analytics-apple-ads` and is off by default.
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 192cc8f15a6f..5f291353d56d 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -35761,6 +35761,29 @@
"enum": ["Goal", "Cost per", "ROAS", "customer", "const:"],
"type": "string"
},
+ "MarketingAnalyticsCostFallback": {
+ "additionalProperties": false,
+ "properties": {
+ "series": {
+ "items": {
+ "$ref": "#/definitions/DataWarehouseNode"
+ },
+ "maxItems": 200,
+ "minItems": 1,
+ "type": "array"
+ },
+ "sourceIds": {
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 200,
+ "minItems": 1,
+ "type": "array"
+ }
+ },
+ "required": ["series", "sourceIds"],
+ "type": "object"
+ },
"MarketingAnalyticsDrillDownConfig": {
"additionalProperties": false,
"properties": {
@@ -56438,6 +56461,10 @@
"const": "TrendsQuery",
"type": "string"
},
+ "marketingAnalyticsCostFallback": {
+ "$ref": "#/definitions/MarketingAnalyticsCostFallback",
+ "description": "Live series for a Marketing cost trend when materialization coverage is incomplete."
+ },
"modifiers": {
"$ref": "#/definitions/HogQLQueryModifiers",
"description": "Modifiers used when performing the query"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 1ec8543aa95a..dc6fc243ac91 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -2031,6 +2031,13 @@ export type TrendsQuerySeriesNodeUnion = EventsNode | ActionsNode | DataWarehous
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
/**
@@ -2044,6 +2051,8 @@ export interface TrendsQuery extends InsightsQueryBase<TrendsQueryResponse> {
* @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
/**
diff --git a/frontend/src/scenes/web-analytics/insightsUtils.ts b/frontend/src/scenes/web-analytics/insightsUtils.ts
index 9603122b909c..bc0caba3151a 100644
--- a/frontend/src/scenes/web-analytics/insightsUtils.ts
+++ b/frontend/src/scenes/web-analytics/insightsUtils.ts
@@ -13,8 +13,19 @@ export const getNewInsightUrlFactory = (tiles: WebAnalyticsTile[]) => {
return function getNewInsightUrl(tileId: TileId, tabId?: string): string | undefined {
const formatQueryForNewInsight = (query: QuerySchema): QuerySchema => {
if (query.kind === NodeKind.InsightVizNode) {
+ const source = query.source
+ const editableSource =
+ source.kind === NodeKind.TrendsQuery && source.marketingAnalyticsCostFallback
+ ? {
+ ...source,
+ series: source.marketingAnalyticsCostFallback.series,
+ breakdownFilter: undefined,
+ marketingAnalyticsCostFallback: undefined,
+ }
+ : source
return {
...query,
+ source: editableSource,
embedded: undefined,
hidePersonsModal: undefined,
}
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
index 760748db69fa..5c02994267ec 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.test.ts
@@ -10,6 +10,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { getNewInsightUrlFactory } from 'scenes/web-analytics/insightsUtils'
import { useMocks } from '~/mocks/jest'
import { dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
@@ -582,6 +583,28 @@ describe('marketingAnalyticsLogic', () => {
table_name: precomputed ? 'marketing_costs_precomputed' : 'campaign_overview_stats',
math_hogql: expect.stringContaining(precomputed ? 'reported_conversions' : 'metrics_conversions'),
})
+ expect(chartAfter.marketingAnalyticsCostFallback).toEqual(
+ precomputed
+ ? { series: logic.values.createMarketingDataWarehouseNodes, sourceIds: ['google-source'] }
+ : undefined
+ )
+ const tile = tiles.values.marketingChartTile
+ expect(getNewInsightUrlFactory([tile])(tile.tileId)).toEqual(
+ urls.insightNew({
+ query: {
+ ...(tile.query as InsightVizNode),
+ source: {
+ ...chartAfter,
+ series: logic.values.createMarketingDataWarehouseNodes,
+ breakdownFilter: undefined,
+ marketingAnalyticsCostFallback: undefined,
+ },
+ embedded: undefined,
+ hidePersonsModal: undefined,
+ } as InsightVizNode,
+ sceneSource: 'web-analytics',
+ })
+ )
expect(logic.values.tileColumnSelection).toBe('reported_conversion')
}
logic.actions.setAdPerformanceConversionGoals(false)
@@ -1009,6 +1032,18 @@ describe('marketingAnalyticsLogic', () => {
expect.objectContaining({ id: sourceId, status: ExternalDataSchemaStatus.Completed }),
])
expect(logic.values.hasSyncedMarketingSources).toBe(true)
+ expect(logic.values.marketingChartSourceIds).toEqual([sourceId])
+ expect(logic.values.createMarketingDataWarehouseNodes).toEqual([
+ expect.objectContaining({ id: tableId, table_name: table.name }),
+ ])
+ logic.actions.setIntegrationFilter({ integrationSourceIds: ['organic'] })
+ expect(logic.values.marketingChartSourceIds).toEqual([])
+ expect(logic.values.createMarketingDataWarehouseNodes).toEqual([])
+ logic.actions.setIntegrationFilter({ integrationSourceIds: [sourceId] })
+ expect(logic.values.marketingChartSourceIds).toEqual([sourceId])
+ expect(logic.values.createMarketingDataWarehouseNodes).toEqual([
+ expect.objectContaining({ id: tableId, table_name: table.name }),
+ ])
if (type === 'managed') {
for (const status of [ExternalDataSchemaStatus.Running, ExternalDataSchemaStatus.Failed, undefined]) {
databaseTableListLogic.actions.loadDatabaseSuccess({
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
index 64b7d3e51cfc..54d9979b3581 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsLogic.ts
@@ -411,6 +411,11 @@ export interface marketingAnalyticsLogicValues {
integrationFilter: IntegrationFilter
isAdPerformance: boolean
loading: boolean
+ marketingChartSourceIds: string[]
+ marketingDataWarehouseSeries: {
+ node: DataWarehouseNode
+ sourceId: string
+ }[]
nativeSources: ExternalDataSource[]
nativeSourcesHierarchyStatus: NativeSourceHierarchyStatus[]
optionsOpen: boolean
@@ -779,13 +784,28 @@ export interface marketingAnalyticsLogicMeta {
statusMessage: string
url_pattern: string
}[]
- createMarketingDataWarehouseNodes: (
+ marketingDataWarehouseSeries: (
validExternalTables: ExternalTable[],
baseCurrency: CurrencyCode,
validNativeSources: NativeSource[],
tileColumnSelection: validColumnsForTiles,
integrationFilter: IntegrationFilter
+ ) => {
+ node: DataWarehouseNode
+ sourceId: string
+ }[]
+ createMarketingDataWarehouseNodes: (
+ marketingDataWarehouseSeries: {
+ node: DataWarehouseNode
+ sourceId: string
+ }[]
) => DataWarehouseNode[]
+ marketingChartSourceIds: (
+ marketingDataWarehouseSeries: {
+ node: DataWarehouseNode
+ sourceId: string
+ }[]
+ ) => string[]
shouldFilterTestAccounts: (filter_test_accounts: boolean) => boolean
overviewQuery: (
dateFilter: {
@@ -1522,7 +1542,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
return result
},
],
- createMarketingDataWarehouseNodes: [
+ marketingDataWarehouseSeries: [
(s) => [
s.validExternalTables,
s.baseCurrency,
@@ -1536,7 +1556,7 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
validNativeSources: NativeSource[],
tileColumnSelection: validColumnsForTiles,
integrationFilter: IntegrationFilter
- ): DataWarehouseNode[] => {
+ ): { sourceId: string; node: DataWarehouseNode }[] => {
const selectedIds = integrationFilter.integrationSourceIds || []
const hasFilter = selectedIds.length > 0
@@ -1548,17 +1568,27 @@ export const marketingAnalyticsLogic = kea<marketingAnalyticsLogicType>([
? validNativeSources.filter((source) => selectedIds.includes(source.source.id))
: validNativeSources
- const nonNativeNodeList: DataWarehouseNode[] = filteredExternalTables
- .map((table) => externalAdsCostTile(table, baseCurrency, tileColumnSelection))
- .filter(Boolean) as DataWarehouseNode[]
-
- const nativeNodeList: DataWarehouseNode[] = filteredNativeSources
- .map((source) => MarketingDashboardMapper(source, tileColumnSelection, baseCurrency))
- .filter(Boolean) as DataWarehouseNode[]
-
+ const nonNativeNodeList = filteredExternalTables.flatMap((table) => {
+ const node = externalAdsCostTile(table, baseCurrency, tileColumnSelection)
+ return node ? [{ sourceId: table.source_map_id, node }] : []
+ })
+ const nativeNodeList = filteredNativeSources.flatMap((source) => {
+ const node = MarketingDashboardMapper(source, tileColumnSelection, baseCurrency)
+ return node ? [{ sourceId: source.source.id, node }] : []
+ })
return [...nativeNodeList, ...nonNativeNodeList]
},
],
+ createMarketingDataWarehouseNodes: [
+ (s) => [s.marketingDataWarehouseSeries],
+ (series: { sourceId: string; node: DataWarehouseNode }[]): DataWarehouseNode[] =>
+ series.map(({ node }) => node),
+ ],
+ marketingChartSourceIds: [
+ (s) => [s.marketingDataWarehouseSeries],
+ (series: { sourceId: string; node: DataWarehouseNode }[]): string[] =>
+ series.map(({ sourceId }) => sourceId),
+ ],
shouldFilterTestAccounts: [
(s) => [s.filter_test_accounts],
(filter_test_accounts: boolean): boolean => filter_test_accounts,
diff --git a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
index 585e053bb297..4ac16c1e72c7 100644
--- a/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
+++ b/frontend/src/scenes/web-analytics/tabs/marketing-analytics/frontend/logic/marketingAnalyticsTilesLogic.ts
@@ -86,6 +86,7 @@ export interface marketingAnalyticsTilesLogicValues {
includeConversionGoals: boolean // marketingAnalyticsLogic
integrationFilter: IntegrationFilter // marketingAnalyticsLogic
loading: boolean // marketingAnalyticsLogic
+ marketingChartSourceIds: string[] // marketingAnalyticsLogic
shouldFilterTestAccounts: boolean // marketingAnalyticsLogic
sourcesInitialLoading: boolean // marketingAnalyticsLogic
tileColumnSelection: validColumnsForTiles // marketingAnalyticsLogic
@@ -125,7 +126,8 @@ export interface marketingAnalyticsTilesLogicMeta {
tileColumnSelection: validColumnsForTiles,
baseCurrency: CurrencyCode,
integrationFilter: IntegrationFilter,
- featureFlags: FeatureFlagsSet
+ featureFlags: FeatureFlagsSet,
+ marketingChartSourceIds: string[]
) => QueryTile
campaignBreakdownTile: (
campaignCostsBreakdown: DataTableNode | null,
@@ -171,6 +173,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
'compareFilter',
'dateFilter',
'createMarketingDataWarehouseNodes',
+ 'marketingChartSourceIds',
'loading',
'sourcesInitialLoading',
'draftConversionGoal',
@@ -242,6 +245,7 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
s.baseCurrency,
s.integrationFilter,
s.featureFlags,
+ s.marketingChartSourceIds,
],
(
compareFilter: CompareFilter | null,
@@ -251,7 +255,8 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
tileColumnSelection: validColumnsForTiles,
baseCurrency: CurrencyCode,
integrationFilter: IntegrationFilter,
- featureFlags: FeatureFlagsSet
+ featureFlags: FeatureFlagsSet,
+ marketingChartSourceIds: string[]
): QueryTile => {
const tileColumnSelectionName = tileColumnSelection?.split('_').join(' ')
const hasSources = createMarketingDataWarehouseNodes.length > 0
@@ -326,6 +331,10 @@ export const marketingAnalyticsTilesLogic = kea<marketingAnalyticsTilesLogicType
: costsPrecomputeEnabled
? [costSeriesNode]
: createMarketingDataWarehouseNodes,
+ marketingAnalyticsCostFallback:
+ costsPrecomputeEnabled && hasSources
+ ? { series: createMarketingDataWarehouseNodes, sourceIds: marketingChartSourceIds }
+ : undefined,
compareFilter: compareFilter || undefined,
// The precompute path reads a single node, so split by source here; the S3 adapters
// are already per-source series and need no breakdown.
diff --git a/posthog/schema.py b/posthog/schema.py
index 4c5f5440c94e..e0e0de7b73c2 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -29179,6 +29179,14 @@ class MarketingAnalyticsConfig(BaseModel):
sources_map: dict[str, SourceMap] | None = None
+class MarketingAnalyticsCostFallback(BaseModel):
+ model_config = ConfigDict(
+ extra="forbid",
+ )
+ series: list[DataWarehouseNode] = Field(..., max_length=200, min_length=1)
+ sourceIds: list[str] = Field(..., max_length=200, min_length=1)
+
+
class MarketingAnalyticsRetentionQuery(BaseModel):
model_config = ConfigDict(
extra="forbid",
@@ -32172,6 +32180,10 @@ class TrendsQuery(BaseModel):
description=("Granularity of the response. Can be one of `hour`, `day`, `week` or `month`"),
)
kind: Literal["TrendsQuery"] = "TrendsQuery"
+ marketingAnalyticsCostFallback: MarketingAnalyticsCostFallback | None = Field(
+ default=None,
+ description=("Live series for a Marketing cost trend when materialization coverage is incomplete."),
+ )
modifiers: HogQLQueryModifiers | None = Field(default=None, description="Modifiers used when performing the query")
properties: list[AnyPropertyFilterDiscriminated] | PropertyGroupFilter | None = Field(
default=[], description="Property filters for all series"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 1548a73b5d3d..49a7c89c68fa 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1381,423 +1381,163 @@ export const IntervalTypeApi = {
Year: 'year',
} as const
-export type BounceRatePageViewModeApi = (typeof BounceRatePageViewModeApi)[keyof typeof BounceRatePageViewModeApi]
-
-export const BounceRatePageViewModeApi = {
- CountPageviews: 'count_pageviews',
- UniqUrls: 'uniq_urls',
- UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
-} as const
+export interface PersonMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
+ type?: 'person_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]
+export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]
-export const FilterLogicalOperatorApi = {
- And: 'AND',
- Or: 'OR',
+export const Key10Api = {
+ TagName: 'tag_name',
+ Text: 'text',
+ Href: 'href',
+ Selector: 'selector',
} as const
-export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+export interface ElementPropertyFilterApi {
+ key: Key10Api
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'element'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const CustomBotFieldApi = {
- 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',
- GeoipCountryCode: '$geoip_country_code',
- Referrer: '$referrer',
- ReferringDomain: '$referring_domain',
-} as const
+export interface EventMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'event_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]
-export const CustomBotMatcherApi = {
- Contains: 'contains',
- Regex: 'regex',
- Exact: 'exact',
- Cidr: 'cidr',
+export const DurationTypeApi = {
+ Duration: 'duration',
+ ActiveSeconds: 'active_seconds',
+ InactiveSeconds: 'inactive_seconds',
} as const
-export interface CustomBotConditionApi {
- id: string
- /** The event property this condition reads. */
- key: CustomBotFieldApi
- matcher: CustomBotMatcherApi
- /** Matched against the property named by `key`. */
- pattern: string
+export interface RecordingPropertyFilterApi {
+ key: DurationTypeApi | string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'recording'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export interface CustomBotRuleApi {
- /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
- category?: string | null
- /** Whether every condition must match (AND) or any one of them (OR). */
- combiner: FilterLogicalOperatorApi
- id: string
- items: CustomBotConditionApi[]
- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */
- name: string
+export interface LogEntryPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'log_entry'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]
-
-export const CustomChannelFieldApi = {
- UtmSource: 'utm_source',
- UtmMedium: 'utm_medium',
- UtmCampaign: 'utm_campaign',
- ReferringDomain: 'referring_domain',
- Url: 'url',
- Pathname: 'pathname',
- Hostname: 'hostname',
-} as const
-
-export type CustomChannelOperatorApi = (typeof CustomChannelOperatorApi)[keyof typeof CustomChannelOperatorApi]
-
-export const CustomChannelOperatorApi = {
- Exact: 'exact',
- IsNot: 'is_not',
- IsSet: 'is_set',
- IsNotSet: 'is_not_set',
- Icontains: 'icontains',
- NotIcontains: 'not_icontains',
- Regex: 'regex',
- NotRegex: 'not_regex',
-} as const
+export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null
-export interface CustomChannelConditionApi {
- id: string
- key: CustomChannelFieldApi
- op: CustomChannelOperatorApi
- value?: string | string[] | null
+export interface GroupPropertyFilterApi {
+ group_key_names?: GroupPropertyFilterApiGroupKeyNames
+ group_type_index?: number | null
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'group'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export interface CustomChannelRuleApi {
- channel_type: string
- combiner: FilterLogicalOperatorApi
- id: string
- items: CustomChannelConditionApi[]
+export interface FeaturePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Event property with "$feature/" prepended */
+ type?: 'feature'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export interface DataWarehouseEventsModifierApi {
- distinct_id_field: string
- id_field: string
- table_name: string
- timestamp_field: string
+export interface FlagPropertyFilterApi {
+ /** The key should be the flag ID */
+ key: string
+ label?: string | null
+ /** Only flag_evaluates_to operator is allowed for flag dependencies */
+ operator?: 'flag_evaluates_to'
+ /** Feature flag dependency */
+ type?: 'flag'
+ /** The value can be true, false, or a variant name */
+ value: boolean | string
}
-export type InCohortViaApi = (typeof InCohortViaApi)[keyof typeof InCohortViaApi]
+export interface HogQLPropertyFilterApi {
+ key: string
+ label?: string | null
+ type?: 'hogql'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const InCohortViaApi = {
- Auto: 'auto',
- Leftjoin: 'leftjoin',
- Subquery: 'subquery',
- LeftjoinConjoined: 'leftjoin_conjoined',
+export const EmptyPropertyFilterApiValue = {
+ type: 'empty',
} as const
+export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue
-export type InlineCohortCalculationApi = (typeof InlineCohortCalculationApi)[keyof typeof InlineCohortCalculationApi]
-
-export const InlineCohortCalculationApi = {
- Off: 'off',
- Auto: 'auto',
- Always: 'always',
-} as const
+export interface DataWarehousePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type MaterializationModeApi = (typeof MaterializationModeApi)[keyof typeof MaterializationModeApi]
+export interface DataWarehousePersonPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse_person_property'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const MaterializationModeApi = {
- Auto: 'auto',
- LegacyNullAsString: 'legacy_null_as_string',
- LegacyNullAsNull: 'legacy_null_as_null',
- Disabled: 'disabled',
-} as const
+export interface ErrorTrackingIssueFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'error_tracking_issue'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type MaterializedColumnsOptimizationModeApi =
- (typeof MaterializedColumnsOptimizationModeApi)[keyof typeof MaterializedColumnsOptimizationModeApi]
+export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]
-export const MaterializedColumnsOptimizationModeApi = {
- Disabled: 'disabled',
- Optimized: 'optimized',
+export const LogPropertyFilterTypeApi = {
+ Log: 'log',
+ LogAttribute: 'log_attribute',
+ LogResourceAttribute: 'log_resource_attribute',
} as const
-export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]
+export interface LogPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type: LogPropertyFilterTypeApi
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const ParserModeApi = {
- CppOnly: 'cpp_only',
- CppWithRustShadow: 'cpp_with_rust_shadow',
- CppWithRustPyShadow: 'cpp_with_rust_py_shadow',
- RustWithCppShadow: 'rust_with_cpp_shadow',
- RustOnly: 'rust_only',
- RustPyOnly: 'rust_py_only',
- RustPyWithCppShadow: 'rust_py_with_cpp_shadow',
-} as const
+export interface MetricPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'metric_attribute'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]
+export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]
-export const PersonsArgMaxVersionApi = {
- Auto: 'auto',
- V1: 'v1',
- V2: 'v2',
-} as const
-
-export type PersonsJoinModeApi = (typeof PersonsJoinModeApi)[keyof typeof PersonsJoinModeApi]
-
-export const PersonsJoinModeApi = {
- Inner: 'inner',
- Left: 'left',
-} as const
-
-export type PersonsOnEventsModeApi = (typeof PersonsOnEventsModeApi)[keyof typeof PersonsOnEventsModeApi]
-
-export const PersonsOnEventsModeApi = {
- Disabled: 'disabled',
- PersonIdNoOverridePropertiesOnEvents: 'person_id_no_override_properties_on_events',
- PersonIdOverridePropertiesOnEvents: 'person_id_override_properties_on_events',
- PersonIdOverridePropertiesJoined: 'person_id_override_properties_joined',
-} as const
-
-export type PropertyGroupsModeApi = (typeof PropertyGroupsModeApi)[keyof typeof PropertyGroupsModeApi]
-
-export const PropertyGroupsModeApi = {
- Enabled: 'enabled',
- Disabled: 'disabled',
- Optimized: 'optimized',
-} as const
-
-export type SessionTableVersionApi = (typeof SessionTableVersionApi)[keyof typeof SessionTableVersionApi]
-
-export const SessionTableVersionApi = {
- Auto: 'auto',
- V1: 'v1',
- V2: 'v2',
- V3: 'v3',
-} as const
-
-export type SessionsV2JoinModeApi = (typeof SessionsV2JoinModeApi)[keyof typeof SessionsV2JoinModeApi]
-
-export const SessionsV2JoinModeApi = {
- String: 'string',
- Uuid: 'uuid',
-} as const
-
-export interface HogQLQueryModifiersApi {
- bounceRateDurationSeconds?: number | null
- bounceRatePageViewMode?: BounceRatePageViewModeApi | null
- convertToProjectTimezone?: boolean | null
- /** 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
- customBotDefinitions?: CustomBotRuleApi[] | null
- customChannelTypeRules?: CustomChannelRuleApi[] | null
- dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
- debug?: boolean | null
- /** If these are provided, the query will fail if these skip indexes are not used */
- forceClickhouseDataSkippingIndexes?: string[] | null
- formatCsvAllowDoubleQuotes?: boolean | null
- inCohortVia?: InCohortViaApi | null
- inlineCohortCalculation?: InlineCohortCalculationApi | null
- materializationMode?: MaterializationModeApi | null
- materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
- /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
- mergeFederatedAggregateJoins?: boolean | null
- /** 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 | null
- optimizeJoinedFilters?: boolean | null
- optimizeProjections?: boolean | null
- /** 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?: ParserModeApi | null
- /** 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 | null
- personsArgMaxVersion?: PersonsArgMaxVersionApi | null
- personsJoinMode?: PersonsJoinModeApi | null
- personsOnEventsMode?: PersonsOnEventsModeApi | null
- propertyGroupsMode?: PropertyGroupsModeApi | null
- pushDownPredicates?: boolean | null
- s3TableUseInvalidColumns?: boolean | null
- /** 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 | null
- /** 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 | null
- sessionTableVersion?: SessionTableVersionApi | null
- /** 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?: number | null
- sessionsV2JoinMode?: SessionsV2JoinModeApi | null
- timings?: boolean | null
- /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
- typeAwareCastSimplification?: boolean | null
- useMaterializedViews?: boolean | null
- /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
- useNewEventsCluster?: boolean | null
- /** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
- useNewEventsSchema?: boolean | null
- usePreaggregatedIntermediateResults?: boolean | null
- /** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */
- usePreaggregatedTableTransforms?: boolean | null
- useWebAnalyticsPreAggregatedTables?: boolean | null
- /** 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 | null
-}
-
-export interface PersonMetadataPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
- type?: 'person_metadata'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]
-
-export const Key10Api = {
- TagName: 'tag_name',
- Text: 'text',
- Href: 'href',
- Selector: 'selector',
-} as const
-
-export interface ElementPropertyFilterApi {
- key: Key10Api
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'element'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface EventMetadataPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'event_metadata'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]
-
-export const DurationTypeApi = {
- Duration: 'duration',
- ActiveSeconds: 'active_seconds',
- InactiveSeconds: 'inactive_seconds',
-} as const
-
-export interface RecordingPropertyFilterApi {
- key: DurationTypeApi | string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'recording'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface LogEntryPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'log_entry'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null
-
-export interface GroupPropertyFilterApi {
- group_key_names?: GroupPropertyFilterApiGroupKeyNames
- group_type_index?: number | null
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'group'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface FeaturePropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- /** Event property with "$feature/" prepended */
- type?: 'feature'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface FlagPropertyFilterApi {
- /** The key should be the flag ID */
- key: string
- label?: string | null
- /** Only flag_evaluates_to operator is allowed for flag dependencies */
- operator?: 'flag_evaluates_to'
- /** Feature flag dependency */
- type?: 'flag'
- /** The value can be true, false, or a variant name */
- value: boolean | string
-}
-
-export interface HogQLPropertyFilterApi {
- key: string
- label?: string | null
- type?: 'hogql'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export const EmptyPropertyFilterApiValue = {
- type: 'empty',
-} as const
-export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue
-
-export interface DataWarehousePropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'data_warehouse'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface DataWarehousePersonPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'data_warehouse_person_property'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface ErrorTrackingIssueFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'error_tracking_issue'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]
-
-export const LogPropertyFilterTypeApi = {
- Log: 'log',
- LogAttribute: 'log_attribute',
- LogResourceAttribute: 'log_resource_attribute',
-} as const
-
-export interface LogPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type: LogPropertyFilterTypeApi
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface MetricPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'metric_attribute'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]
-
-export const SpanPropertyFilterTypeApi = {
- Span: 'span',
- SpanAttribute: 'span_attribute',
- SpanResourceAttribute: 'span_resource_attribute',
+export const SpanPropertyFilterTypeApi = {
+ Span: 'span',
+ SpanAttribute: 'span_attribute',
+ SpanResourceAttribute: 'span_resource_attribute',
} as const
export interface SpanPropertyFilterApi {
@@ -1888,231 +1628,6 @@ export interface BehavioralPropertyFilterApi {
value: InlineBehavioralTypeApi
}
-export interface PropertyGroupFilterValueApi {
- type: FilterLogicalOperatorApi
- values: (
- | PropertyGroupFilterValueApi
- | EventPropertyFilterApi
- | PersonPropertyFilterApi
- | PersonMetadataPropertyFilterApi
- | ElementPropertyFilterApi
- | EventMetadataPropertyFilterApi
- | SessionPropertyFilterApi
- | CohortPropertyFilterApi
- | RecordingPropertyFilterApi
- | LogEntryPropertyFilterApi
- | GroupPropertyFilterApi
- | FeaturePropertyFilterApi
- | FlagPropertyFilterApi
- | HogQLPropertyFilterApi
- | EmptyPropertyFilterApi
- | DataWarehousePropertyFilterApi
- | DataWarehousePersonPropertyFilterApi
- | ErrorTrackingIssueFilterApi
- | LogPropertyFilterApi
- | MetricPropertyFilterApi
- | SpanPropertyFilterApi
- | RevenueAnalyticsPropertyFilterApi
- | AccountCustomPropertyFilterApi
- | WorkflowVariablePropertyFilterApi
- | BehavioralPropertyFilterApi
- )[]
-}
-
-export interface PropertyGroupFilterApi {
- type: FilterLogicalOperatorApi
- values: PropertyGroupFilterValueApi[]
-}
-
-export interface BoxPlotDatumApi {
- day: string
- label: string
- max: number
- mean: number
- median: number
- min: number
- p25: number
- p75: number
- series_index?: number | null
- series_label?: string | null
-}
-
-export interface ClickhouseQueryProgressApi {
- active_cpu_time: number
- bytes_read: number
- estimated_rows_total: number
- rows_read: number
- time_elapsed: number
-}
-
-export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
-
-export const QueryScanFixLocationApi = {
- Query: 'query',
- Subquery: 'subquery',
- View: 'view',
- InsightDateRange: 'insight_date_range',
- DashboardDateFilter: 'dashboard_date_filter',
-} as const
-
-export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
-
-export const QueryScanFindingKindApi = {
- NoEventFilter: 'no_event_filter',
- NoStartDate: 'no_start_date',
- PersonsJoin: 'persons_join',
-} as const
-
-export interface QueryScanWarningApi {
- /** 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
- /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
- by_design?: boolean | null
- /** 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 | null
- /** The one fact the finding rests on. */
- evidence?: string | null
- /** What "Fix with AI" and the assistant are told to do. */
- fix: string
- /** Where the change goes. Absent means the query itself. */
- fix_location?: QueryScanFixLocationApi | null
- kind: QueryScanFindingKindApi
- /** Shown to the person: what happened and what to do. */
- message: string
-}
-
-export interface QueryScanAnalysisApi {
- /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
- assistant_prompt?: string | null
- /** Every finding, fixable or not. Empty when the analysis found none. */
- findings: QueryScanWarningApi[]
- /** How much of all the project's events the query read, 0 to 1. */
- project_share?: number | null
- /** How much of the project's events in the query's date range the query read, 0 to 1. */
- range_share?: number | null
-}
-
-export interface QueryScanSummaryApi {
- /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */
- analysis?: QueryScanAnalysisApi | null
- /** 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 | null
- /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */
- duration_ms: number
- /** True when ClickHouse stopped the run instead of finishing it. */
- killed?: boolean | null
- /** Rows ClickHouse read for the last fresh run, all tables included. */
- rows_read: number
-}
-
-export interface QueryStatusApi {
- budget_remaining_bytes?: number | null
- bytes_read?: number | null
- /** Cache key of the run that failed, so clients can ask for its query scan. */
- cache_key?: string | null
- /** 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. */
- complete?: boolean | null
- dashboard_id?: number | null
- /** When did the query execution task finish (whether successfully or not). */
- end_time?: string | null
- /** If the query failed, this will be set to true. More information can be found in the error_message field. */
- error?: boolean | null
- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */
- error_code?: string | null
- error_message?: string | null
- expiration_time?: string | null
- id: string
- insight_id?: number | null
- labels?: string[] | null
- /** When was the query execution task picked up by a worker. */
- pickup_time?: string | null
- /** ONLY async queries use QueryStatus. */
- query_async?: true
- query_progress?: ClickhouseQueryProgressApi | null
- query_scan?: QueryScanSummaryApi | null
- results?: unknown
- /** When was query execution task enqueued. */
- start_time?: string | null
- task_id?: string | null
- team_id: number
-}
-
-export interface ResolvedDateRangeResponseApi {
- date_from: string
- date_to: string
-}
-
-export interface QueryTimingApi {
- /** Key. Shortened to 'k' to save on data. */
- k: string
- /** Time in seconds. Shortened to 't' to save on data. */
- t: number
-}
-
-export interface DataWarehouseSourceUsageApi {
- /** ExternalDataSource id */
- id: string
- /** Connector type of the source (e.g. Stripe, Postgres), if known */
- source_type?: string | null
- /** Warehouse table name that was referenced */
- table_name: string
-}
-
-export interface DataWarehouseSyncWarningApi {
- /** 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 | null
- /** Human-readable warning shown to the user */
- message: string
- /** Name of the ExternalDataSchema responsible for syncing the table */
- schema_name: string
- /** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */
- source_id?: string | null
- /** Source type, e.g. "Stripe", "Hubspot" */
- source_type: string
- /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
- status: string
- /** Name of the warehouse table the warning refers to */
- table_name: string
- /** Tells warning kinds apart in the shared `warnings` list */
- type?: 'warehouse_sync'
-}
-
-export interface AccessControlFilterWarningApi {
- /** Human-readable warning shown to the user */
- message: string
- /** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */
- resources: string[]
- /** Tells warning kinds apart in the shared `warnings` list */
- type?: 'access_control'
-}
-
-export type TrendsQueryResponseApiResultsItem = { [key: string]: unknown }
-
-export interface TrendsQueryResponseApi {
- boxplot_data?: BoxPlotDatumApi[] | null
- /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
- error?: string | null
- /** Wether more breakdown values are available. */
- hasMore?: boolean | null
- /** Generated HogQL query. */
- hogql?: string | null
- /** Modifiers used when performing the query */
- modifiers?: HogQLQueryModifiersApi | null
- /** Query status indicates whether next to the provided data, a query is still running. */
- query_status?: QueryStatusApi | null
- /** The resolved previous/comparison period date range, when comparing against another period */
- resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
- /** The date range used for the query */
- resolved_date_range?: ResolvedDateRangeResponseApi | null
- results: TrendsQueryResponseApiResultsItem[]
- /** Measured timings for different parts of the query generation process */
- timings?: QueryTimingApi[] | null
- /** Connector-synced data warehouse sources referenced by this query, if any. */
- used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null
- /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
- warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
-}
-
export type BaseMathTypeApi = (typeof BaseMathTypeApi)[keyof typeof BaseMathTypeApi]
export const BaseMathTypeApi = {
@@ -2356,9 +1871,599 @@ export const CurrencyCodeApi = {
Zmw: 'ZMW',
} as const
-export interface RevenueCurrencyPropertyConfigApi {
- property?: string | null
- static?: CurrencyCodeApi | null
+export interface RevenueCurrencyPropertyConfigApi {
+ property?: string | null
+ static?: CurrencyCodeApi | null
+}
+
+export type DataWarehouseNodeApiResponse = { [key: string]: unknown } | null
+
+export interface DataWarehouseNodeApi {
+ custom_name?: string | null
+ distinct_id_field: string
+ dw_source_type?: string | null
+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+ | null
+ id: string
+ id_field: string
+ kind?: 'DataWarehouseNode'
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | GroupMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ /** Properties configurable in the interface */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+ | null
+ response?: DataWarehouseNodeApiResponse
+ table_name: string
+ timestamp_field: string
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
+export interface MarketingAnalyticsCostFallbackApi {
+ /**
+ * @minItems 1
+ * @maxItems 200
+ */
+ series: DataWarehouseNodeApi[]
+ /**
+ * @minItems 1
+ * @maxItems 200
+ */
+ sourceIds: string[]
+}
+
+export type BounceRatePageViewModeApi = (typeof BounceRatePageViewModeApi)[keyof typeof BounceRatePageViewModeApi]
+
+export const BounceRatePageViewModeApi = {
+ CountPageviews: 'count_pageviews',
+ UniqUrls: 'uniq_urls',
+ UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
+} as const
+
+export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]
+
+export const FilterLogicalOperatorApi = {
+ And: 'AND',
+ Or: 'OR',
+} as const
+
+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+
+export const CustomBotFieldApi = {
+ 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',
+ GeoipCountryCode: '$geoip_country_code',
+ Referrer: '$referrer',
+ ReferringDomain: '$referring_domain',
+} as const
+
+export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+
+export const CustomBotMatcherApi = {
+ Contains: 'contains',
+ Regex: 'regex',
+ Exact: 'exact',
+ Cidr: 'cidr',
+} as const
+
+export interface CustomBotConditionApi {
+ id: string
+ /** The event property this condition reads. */
+ key: CustomBotFieldApi
+ matcher: CustomBotMatcherApi
+ /** Matched against the property named by `key`. */
+ pattern: string
+}
+
+export interface CustomBotRuleApi {
+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
+ category?: string | null
+ /** Whether every condition must match (AND) or any one of them (OR). */
+ combiner: FilterLogicalOperatorApi
+ id: string
+ items: CustomBotConditionApi[]
+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */
+ name: string
+}
+
+export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]
+
+export const CustomChannelFieldApi = {
+ UtmSource: 'utm_source',
+ UtmMedium: 'utm_medium',
+ UtmCampaign: 'utm_campaign',
+ ReferringDomain: 'referring_domain',
+ Url: 'url',
+ Pathname: 'pathname',
+ Hostname: 'hostname',
+} as const
+
+export type CustomChannelOperatorApi = (typeof CustomChannelOperatorApi)[keyof typeof CustomChannelOperatorApi]
+
+export const CustomChannelOperatorApi = {
+ Exact: 'exact',
+ IsNot: 'is_not',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+ Icontains: 'icontains',
+ NotIcontains: 'not_icontains',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+} as const
+
+export interface CustomChannelConditionApi {
+ id: string
+ key: CustomChannelFieldApi
+ op: CustomChannelOperatorApi
+ value?: string | string[] | null
+}
+
+export interface CustomChannelRuleApi {
+ channel_type: string
+ combiner: FilterLogicalOperatorApi
+ id: string
+ items: CustomChannelConditionApi[]
+}
+
+export interface DataWarehouseEventsModifierApi {
+ distinct_id_field: string
+ id_field: string
+ table_name: string
+ timestamp_field: string
+}
+
+export type InCohortViaApi = (typeof InCohortViaApi)[keyof typeof InCohortViaApi]
+
+export const InCohortViaApi = {
+ Auto: 'auto',
+ Leftjoin: 'leftjoin',
+ Subquery: 'subquery',
+ LeftjoinConjoined: 'leftjoin_conjoined',
+} as const
+
+export type InlineCohortCalculationApi = (typeof InlineCohortCalculationApi)[keyof typeof InlineCohortCalculationApi]
+
+export const InlineCohortCalculationApi = {
+ Off: 'off',
+ Auto: 'auto',
+ Always: 'always',
+} as const
+
+export type MaterializationModeApi = (typeof MaterializationModeApi)[keyof typeof MaterializationModeApi]
+
+export const MaterializationModeApi = {
+ Auto: 'auto',
+ LegacyNullAsString: 'legacy_null_as_string',
+ LegacyNullAsNull: 'legacy_null_as_null',
+ Disabled: 'disabled',
+} as const
+
+export type MaterializedColumnsOptimizationModeApi =
+ (typeof MaterializedColumnsOptimizationModeApi)[keyof typeof MaterializedColumnsOptimizationModeApi]
+
+export const MaterializedColumnsOptimizationModeApi = {
+ Disabled: 'disabled',
+ Optimized: 'optimized',
+} as const
+
+export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]
+
+export const ParserModeApi = {
+ CppOnly: 'cpp_only',
+ CppWithRustShadow: 'cpp_with_rust_shadow',
+ CppWithRustPyShadow: 'cpp_with_rust_py_shadow',
+ RustWithCppShadow: 'rust_with_cpp_shadow',
+ RustOnly: 'rust_only',
+ RustPyOnly: 'rust_py_only',
+ RustPyWithCppShadow: 'rust_py_with_cpp_shadow',
+} as const
+
+export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]
+
+export const PersonsArgMaxVersionApi = {
+ Auto: 'auto',
+ V1: 'v1',
+ V2: 'v2',
+} as const
+
+export type PersonsJoinModeApi = (typeof PersonsJoinModeApi)[keyof typeof PersonsJoinModeApi]
+
+export const PersonsJoinModeApi = {
+ Inner: 'inner',
+ Left: 'left',
+} as const
+
+export type PersonsOnEventsModeApi = (typeof PersonsOnEventsModeApi)[keyof typeof PersonsOnEventsModeApi]
+
+export const PersonsOnEventsModeApi = {
+ Disabled: 'disabled',
+ PersonIdNoOverridePropertiesOnEvents: 'person_id_no_override_properties_on_events',
+ PersonIdOverridePropertiesOnEvents: 'person_id_override_properties_on_events',
+ PersonIdOverridePropertiesJoined: 'person_id_override_properties_joined',
+} as const
+
+export type PropertyGroupsModeApi = (typeof PropertyGroupsModeApi)[keyof typeof PropertyGroupsModeApi]
+
+export const PropertyGroupsModeApi = {
+ Enabled: 'enabled',
+ Disabled: 'disabled',
+ Optimized: 'optimized',
+} as const
+
+export type SessionTableVersionApi = (typeof SessionTableVersionApi)[keyof typeof SessionTableVersionApi]
+
+export const SessionTableVersionApi = {
+ Auto: 'auto',
+ V1: 'v1',
+ V2: 'v2',
+ V3: 'v3',
+} as const
+
+export type SessionsV2JoinModeApi = (typeof SessionsV2JoinModeApi)[keyof typeof SessionsV2JoinModeApi]
+
+export const SessionsV2JoinModeApi = {
+ String: 'string',
+ Uuid: 'uuid',
+} as const
+
+export interface HogQLQueryModifiersApi {
+ bounceRateDurationSeconds?: number | null
+ bounceRatePageViewMode?: BounceRatePageViewModeApi | null
+ convertToProjectTimezone?: boolean | null
+ /** 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
+ customBotDefinitions?: CustomBotRuleApi[] | null
+ customChannelTypeRules?: CustomChannelRuleApi[] | null
+ dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
+ debug?: boolean | null
+ /** If these are provided, the query will fail if these skip indexes are not used */
+ forceClickhouseDataSkippingIndexes?: string[] | null
+ formatCsvAllowDoubleQuotes?: boolean | null
+ inCohortVia?: InCohortViaApi | null
+ inlineCohortCalculation?: InlineCohortCalculationApi | null
+ materializationMode?: MaterializationModeApi | null
+ materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
+ mergeFederatedAggregateJoins?: boolean | null
+ /** 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 | null
+ optimizeJoinedFilters?: boolean | null
+ optimizeProjections?: boolean | null
+ /** 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?: ParserModeApi | null
+ /** 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 | null
+ personsArgMaxVersion?: PersonsArgMaxVersionApi | null
+ personsJoinMode?: PersonsJoinModeApi | null
+ personsOnEventsMode?: PersonsOnEventsModeApi | null
+ propertyGroupsMode?: PropertyGroupsModeApi | null
+ pushDownPredicates?: boolean | null
+ s3TableUseInvalidColumns?: boolean | null
+ /** 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 | null
+ /** 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 | null
+ sessionTableVersion?: SessionTableVersionApi | null
+ /** 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?: number | null
+ sessionsV2JoinMode?: SessionsV2JoinModeApi | null
+ timings?: boolean | null
+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
+ typeAwareCastSimplification?: boolean | null
+ useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
+ /** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
+ useNewEventsSchema?: boolean | null
+ usePreaggregatedIntermediateResults?: boolean | null
+ /** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */
+ usePreaggregatedTableTransforms?: boolean | null
+ useWebAnalyticsPreAggregatedTables?: boolean | null
+ /** 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 | null
+}
+
+export interface PropertyGroupFilterValueApi {
+ type: FilterLogicalOperatorApi
+ values: (
+ | PropertyGroupFilterValueApi
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+}
+
+export interface PropertyGroupFilterApi {
+ type: FilterLogicalOperatorApi
+ values: PropertyGroupFilterValueApi[]
+}
+
+export interface BoxPlotDatumApi {
+ day: string
+ label: string
+ max: number
+ mean: number
+ median: number
+ min: number
+ p25: number
+ p75: number
+ series_index?: number | null
+ series_label?: string | null
+}
+
+export interface ClickhouseQueryProgressApi {
+ active_cpu_time: number
+ bytes_read: number
+ estimated_rows_total: number
+ rows_read: number
+ time_elapsed: number
+}
+
+export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
+
+export const QueryScanFixLocationApi = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+} as const
+
+export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
+
+export const QueryScanFindingKindApi = {
+ NoEventFilter: 'no_event_filter',
+ NoStartDate: 'no_start_date',
+ PersonsJoin: 'persons_join',
+} as const
+
+export interface QueryScanWarningApi {
+ /** 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
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null
+ /** 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 | null
+ /** The one fact the finding rests on. */
+ evidence?: string | null
+ /** What "Fix with AI" and the assistant are told to do. */
+ fix: string
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocationApi | null
+ kind: QueryScanFindingKindApi
+ /** Shown to the person: what happened and what to do. */
+ message: string
+}
+
+export interface QueryScanAnalysisApi {
+ /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
+ assistant_prompt?: string | null
+ /** Every finding, fixable or not. Empty when the analysis found none. */
+ findings: QueryScanWarningApi[]
+ /** How much of all the project's events the query read, 0 to 1. */
+ project_share?: number | null
+ /** How much of the project's events in the query's date range the query read, 0 to 1. */
+ range_share?: number | null
+}
+
+export interface QueryScanSummaryApi {
+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */
+ analysis?: QueryScanAnalysisApi | null
+ /** 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 | null
+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */
+ duration_ms: number
+ /** True when ClickHouse stopped the run instead of finishing it. */
+ killed?: boolean | null
+ /** Rows ClickHouse read for the last fresh run, all tables included. */
+ rows_read: number
+}
+
+export interface QueryStatusApi {
+ budget_remaining_bytes?: number | null
+ bytes_read?: number | null
+ /** Cache key of the run that failed, so clients can ask for its query scan. */
+ cache_key?: string | null
+ /** 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. */
+ complete?: boolean | null
+ dashboard_id?: number | null
+ /** When did the query execution task finish (whether successfully or not). */
+ end_time?: string | null
+ /** If the query failed, this will be set to true. More information can be found in the error_message field. */
+ error?: boolean | null
+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */
+ error_code?: string | null
+ error_message?: string | null
+ expiration_time?: string | null
+ id: string
+ insight_id?: number | null
+ labels?: string[] | null
+ /** When was the query execution task picked up by a worker. */
+ pickup_time?: string | null
+ /** ONLY async queries use QueryStatus. */
+ query_async?: true
+ query_progress?: ClickhouseQueryProgressApi | null
+ query_scan?: QueryScanSummaryApi | null
+ results?: unknown
+ /** When was query execution task enqueued. */
+ start_time?: string | null
+ task_id?: string | null
+ team_id: number
+}
+
+export interface ResolvedDateRangeResponseApi {
+ date_from: string
+ date_to: string
+}
+
+export interface QueryTimingApi {
+ /** Key. Shortened to 'k' to save on data. */
+ k: string
+ /** Time in seconds. Shortened to 't' to save on data. */
+ t: number
+}
+
+export interface DataWarehouseSourceUsageApi {
+ /** ExternalDataSource id */
+ id: string
+ /** Connector type of the source (e.g. Stripe, Postgres), if known */
+ source_type?: string | null
+ /** Warehouse table name that was referenced */
+ table_name: string
+}
+
+export interface DataWarehouseSyncWarningApi {
+ /** 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 | null
+ /** Human-readable warning shown to the user */
+ message: string
+ /** Name of the ExternalDataSchema responsible for syncing the table */
+ schema_name: string
+ /** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */
+ source_id?: string | null
+ /** Source type, e.g. "Stripe", "Hubspot" */
+ source_type: string
+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
+ status: string
+ /** Name of the warehouse table the warning refers to */
+ table_name: string
+ /** Tells warning kinds apart in the shared `warnings` list */
+ type?: 'warehouse_sync'
+}
+
+export interface AccessControlFilterWarningApi {
+ /** Human-readable warning shown to the user */
+ message: string
+ /** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */
+ resources: string[]
+ /** Tells warning kinds apart in the shared `warnings` list */
+ type?: 'access_control'
+}
+
+export type TrendsQueryResponseApiResultsItem = { [key: string]: unknown }
+
+export interface TrendsQueryResponseApi {
+ boxplot_data?: BoxPlotDatumApi[] | null
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null
+ /** Wether more breakdown values are available. */
+ hasMore?: boolean | null
+ /** Generated HogQL query. */
+ hogql?: string | null
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatusApi | null
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponseApi | null
+ results: TrendsQueryResponseApiResultsItem[]
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTimingApi[] | null
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
}
export type EventsNodeApiResponse = { [key: string]: unknown } | null
@@ -2539,98 +2644,6 @@ export interface ActionsNodeApi {
version?: number | null
}
-export type DataWarehouseNodeApiResponse = { [key: string]: unknown } | null
-
-export interface DataWarehouseNodeApi {
- custom_name?: string | null
- distinct_id_field: string
- dw_source_type?: string | null
- /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
- fixedProperties?:
- | (
- | EventPropertyFilterApi
- | PersonPropertyFilterApi
- | PersonMetadataPropertyFilterApi
- | ElementPropertyFilterApi
- | EventMetadataPropertyFilterApi
- | SessionPropertyFilterApi
- | CohortPropertyFilterApi
- | RecordingPropertyFilterApi
- | LogEntryPropertyFilterApi
- | GroupPropertyFilterApi
- | FeaturePropertyFilterApi
- | FlagPropertyFilterApi
- | HogQLPropertyFilterApi
- | EmptyPropertyFilterApi
- | DataWarehousePropertyFilterApi
- | DataWarehousePersonPropertyFilterApi
- | ErrorTrackingIssueFilterApi
- | LogPropertyFilterApi
- | MetricPropertyFilterApi
- | SpanPropertyFilterApi
- | RevenueAnalyticsPropertyFilterApi
- | AccountCustomPropertyFilterApi
- | WorkflowVariablePropertyFilterApi
- | BehavioralPropertyFilterApi
- )[]
- | null
- id: string
- id_field: string
- kind?: 'DataWarehouseNode'
- math?:
- | BaseMathTypeApi
- | FunnelMathTypeApi
- | PropertyMathTypeApi
- | CountPerActorMathTypeApi
- | GroupMathTypeApi
- | ExperimentMetricMathTypeApi
- | CalendarHeatmapMathTypeApi
- | 'hogql'
- | null
- math_group_type_index?: MathGroupTypeIndexApi | null
- math_hogql?: string | null
- math_multiplier?: number | null
- math_property?: string | null
- math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
- math_property_type?: string | null
- name?: string | null
- optionalInFunnel?: boolean | null
- /** Properties configurable in the interface */
- properties?:
- | (
- | EventPropertyFilterApi
- | PersonPropertyFilterApi
- | PersonMetadataPropertyFilterApi
- | ElementPropertyFilterApi
- | EventMetadataPropertyFilterApi
- | SessionPropertyFilterApi
- | CohortPropertyFilterApi
- | RecordingPropertyFilterApi
- | LogEntryPropertyFilterApi
- | GroupPropertyFilterApi
- | FeaturePropertyFilterApi
- | FlagPropertyFilterApi
- | HogQLPropertyFilterApi
- | EmptyPropertyFilterApi
- | DataWarehousePropertyFilterApi
- | DataWarehousePersonPropertyFilterApi
- | ErrorTrackingIssueFilterApi
- | LogPropertyFilterApi
- | MetricPropertyFilterApi
- | SpanPropertyFilterApi
- | RevenueAnalyticsPropertyFilterApi
- | AccountCustomPropertyFilterApi
- | WorkflowVariablePropertyFilterApi
- | BehavioralPropertyFilterApi
- )[]
- | null
- response?: DataWarehouseNodeApiResponse
- table_name: string
- timestamp_field: string
- /** version of the node, used for schema migrations */
- version?: number | null
-}
-
export type GroupNodeApiResponse = { [key: string]: unknown } | null
export interface GroupNodeApi {
@@ -3031,6 +3044,8 @@ export interface TrendsQueryApi {
/** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */
interval?: IntervalTypeApi | null
kind?: 'TrendsQuery'
+ /** Live series for a Marketing cost trend when materialization coverage is incomplete. */
+ marketingAnalyticsCostFallback?: MarketingAnalyticsCostFallbackApi | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
/** Property filters for all series */
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index e5b6bdd24d9a..905c78bc8d53 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -1836,6 +1836,101 @@ export namespace Schemas {
| "month"
| "quarter"
| "year";
+ export type DataWarehouseNode = {
+ custom_name?: (string | null) | undefined;
+ distinct_id_field: string;
+ dw_source_type?: (string | null) | undefined;
+ fixedProperties?:
+ | (Array<
+ | EventPropertyFilter
+ | PersonPropertyFilter
+ | PersonMetadataPropertyFilter
+ | ElementPropertyFilter
+ | EventMetadataPropertyFilter
+ | SessionPropertyFilter
+ | CohortPropertyFilter
+ | RecordingPropertyFilter
+ | LogEntryPropertyFilter
+ | GroupPropertyFilter
+ | FeaturePropertyFilter
+ | FlagPropertyFilter
+ | HogQLPropertyFilter
+ | EmptyPropertyFilter
+ | DataWarehousePropertyFilter
+ | DataWarehousePersonPropertyFilter
+ | ErrorTrackingIssueFilter
+ | LogPropertyFilter
+ | MetricPropertyFilter
+ | SpanPropertyFilter
+ | RevenueAnalyticsPropertyFilter
+ | AccountCustomPropertyFilter
+ | WorkflowVariablePropertyFilter
+ | BehavioralPropertyFilter
+ > | null)
+ | undefined;
+ id: string;
+ id_field: string;
+ kind?: string | undefined;
+ math?:
+ | (
+ | BaseMathType
+ | FunnelMathType
+ | PropertyMathType
+ | CountPerActorMathType
+ | GroupMathType
+ | ExperimentMetricMathType
+ | CalendarHeatmapMathType
+ | string
+ | null
+ )
+ | undefined;
+ math_group_type_index?: (MathGroupTypeIndex | null) | undefined;
+ math_hogql?: (string | null) | undefined;
+ math_multiplier?: (number | null) | undefined;
+ math_property?: (string | null) | undefined;
+ math_property_revenue_currency?:
+ | (RevenueCurrencyPropertyConfig | null)
+ | undefined;
+ math_property_type?: (string | null) | undefined;
+ name?: (string | null) | undefined;
+ optionalInFunnel?: (boolean | null) | undefined;
+ properties?:
+ | (Array<
+ | EventPropertyFilter
+ | PersonPropertyFilter
+ | PersonMetadataPropertyFilter
+ | ElementPropertyFilter
+ | EventMetadataPropertyFilter
+ | SessionPropertyFilter
+ | CohortPropertyFilter
+ | RecordingPropertyFilter
+ | LogEntryPropertyFilter
+ | GroupPropertyFilter
+ | FeaturePropertyFilter
+ | FlagPropertyFilter
+ | HogQLPropertyFilter
+ | EmptyPropertyFilter
+ | DataWarehousePropertyFilter
+ | DataWarehousePersonPropertyFilter
+ | ErrorTrackingIssueFilter
+ | LogPropertyFilter
+ | MetricPropertyFilter
+ | SpanPropertyFilter
+ | RevenueAnalyticsPropertyFilter
+ | AccountCustomPropertyFilter
+ | WorkflowVariablePropertyFilter
+ | BehavioralPropertyFilter
+ > | null)
+ | undefined;
+ response?: (Record<string, unknown> | null) | undefined;
+ table_name: string;
+ timestamp_field: string;
+ version?: (number | null) | undefined;
+ };
+ export type MarketingAnalyticsCostFallback = {
+ series: Array<DataWarehouseNode>;
+ sourceIds: Array<string>;
+ };
export type PropertyGroupFilter = {
type: FilterLogicalOperator;
values: Array<PropertyGroupFilterValue>;
@@ -1953,97 +2048,6 @@ export namespace Schemas {
response: Record<string, unknown> | null;
version: number | null;
}>;
- export type DataWarehouseNode = {
- custom_name?: (string | null) | undefined;
- distinct_id_field: string;
- dw_source_type?: (string | null) | undefined;
- fixedProperties?:
- | (Array<
- | EventPropertyFilter
- | PersonPropertyFilter
- | PersonMetadataPropertyFilter
- | ElementPropertyFilter
- | EventMetadataPropertyFilter
- | SessionPropertyFilter
- | CohortPropertyFilter
- | RecordingPropertyFilter
- | LogEntryPropertyFilter
- | GroupPropertyFilter
- | FeaturePropertyFilter
- | FlagPropertyFilter
- | HogQLPropertyFilter
- | EmptyPropertyFilter
- | DataWarehousePropertyFilter
- | DataWarehousePersonPropertyFilter
- | ErrorTrackingIssueFilter
- | LogPropertyFilter
- | MetricPropertyFilter
- | SpanPropertyFilter
- | RevenueAnalyticsPropertyFilter
- | AccountCustomPropertyFilter
- | WorkflowVariablePropertyFilter
- | BehavioralPropertyFilter
- > | null)
- | undefined;
- id: string;
- id_field: string;
- kind?: string | undefined;
- math?:
- | (
- | BaseMathType
- | FunnelMathType
- | PropertyMathType
- | CountPerActorMathType
- | GroupMathType
- | ExperimentMetricMathType
- | CalendarHeatmapMathType
- | string
- | null
- )
- | undefined;
- math_group_type_index?: (MathGroupTypeIndex | null) | undefined;
- math_hogql?: (string | null) | undefined;
- math_multiplier?: (number | null) | undefined;
- math_property?: (string | null) | undefined;
- math_property_revenue_currency?:
- | (RevenueCurrencyPropertyConfig | null)
- | undefined;
- math_property_type?: (string | null) | undefined;
- name?: (string | null) | undefined;
- optionalInFunnel?: (boolean | null) | undefined;
- properties?:
- | (Array<
- | EventPropertyFilter
- | PersonPropertyFilter
- | PersonMetadataPropertyFilter
- | ElementPropertyFilter
- | EventMetadataPropertyFilter
- | SessionPropertyFilter
- | CohortPropertyFilter
- | RecordingPropertyFilter
- | LogEntryPropertyFilter
- | GroupPropertyFilter
- | FeaturePropertyFilter
- | FlagPropertyFilter
- | HogQLPropertyFilter
- | EmptyPropertyFilter
- | DataWarehousePropertyFilter
- | DataWarehousePersonPropertyFilter
- | ErrorTrackingIssueFilter
- | LogPropertyFilter
- | MetricPropertyFilter
- | SpanPropertyFilter
- | RevenueAnalyticsPropertyFilter
- | AccountCustomPropertyFilter
- | WorkflowVariablePropertyFilter
- | BehavioralPropertyFilter
- > | null)
- | undefined;
- response?: (Record<string, unknown> | null) | undefined;
- table_name: string;
- timestamp_field: string;
- version?: (number | null) | undefined;
- };
export type GroupNode = {
custom_name?: (string | null) | undefined;
fixedProperties?:
@@ -2294,6 +2298,9 @@ export namespace Schemas {
filterTestAccounts?: (boolean | null) | undefined;
interval?: (IntervalType | null) | undefined;
kind?: string | undefined;
+ marketingAnalyticsCostFallback?:
+ | (MarketingAnalyticsCostFallback | null)
+ | undefined;
modifiers?: (HogQLQueryModifiers | null) | undefined;
properties?:
| (
diff --git a/products/marketing_analytics/backend/facade/__init__.py b/products/marketing_analytics/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/marketing_analytics/backend/facade/queries.py b/products/marketing_analytics/backend/facade/queries.py
new file mode 100644
index 000000000000..4038859c191f
--- /dev/null
+++ b/products/marketing_analytics/backend/facade/queries.py
@@ -0,0 +1,5 @@
+from products.marketing_analytics.backend.hogql_queries.marketing_cost_trends_query_resolver import (
+ resolve_marketing_cost_trend,
+)
+
+__all__ = ["resolve_marketing_cost_trend"]
diff --git a/products/marketing_analytics/backend/hogql_queries/adapters/factory.py b/products/marketing_analytics/backend/hogql_queries/adapters/factory.py
index 3b5bb8ed8ee8..53b0b016b37b 100644
--- a/products/marketing_analytics/backend/hogql_queries/adapters/factory.py
+++ b/products/marketing_analytics/backend/hogql_queries/adapters/factory.py
@@ -8,7 +8,7 @@ import structlog
if TYPE_CHECKING:
from posthog.models.team.team_marketing_analytics_config import TeamMarketingAnalyticsConfig
-from posthog.schema import NativeMarketingSource, SourceMap
+from posthog.schema import MarketingAnalyticsDrillDownLevel, NativeMarketingSource, SourceMap
from posthog.hogql import ast
from posthog.hogql.database.database import Database
@@ -429,6 +429,16 @@ class MarketingSourceFactory:
self.logger.exception("Error validating adapter", source_type=adapter.get_source_type(), error=str(e))
return valid_adapters
+ @staticmethod
+ def build_materialization_queries(
+ adapters: list[MarketingSourceAdapter], grain: MarketingAnalyticsDrillDownLevel
+ ) -> dict[str, ast.SelectQuery | None]:
+ return {
+ str(adapter.get_source_id()): adapter.build_materialization_query(adapter.get_source_id())
+ for adapter in adapters
+ if adapter.supports_level(grain)
+ }
+
def get_validation_errors(self, adapters: list[MarketingSourceAdapter]) -> dict[str, list[str]]:
errors_by_source: dict[str, list[str]] = {}
for adapter in adapters:
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index 5d2484bbbc2f..b862121e8202 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -396,7 +396,8 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
if integration_filter and integration_filter.integrationSourceIds:
selected_ids = integration_filter.integrationSourceIds
mat_adapters = [a for a in mat_adapters if a.get_source_id() in selected_ids]
- mat_adapters = [a for a in mat_adapters if a.supports_level(grain)]
+ materialization_queries = mat_factory.build_materialization_queries(mat_adapters, grain)
+ mat_adapters = [a for a in mat_adapters if str(a.get_source_id()) in materialization_queries]
grain_value = str(grain.value)
if not mat_adapters:
self._costs_precompute_outcome = "fallback_no_materializable_sources"
@@ -416,7 +417,7 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
s3_fallback_adapters: list[MarketingSourceAdapter] = []
for adapter in mat_adapters:
with self.timings.measure("ma_precompute_build_mat_query"):
- insert_query = adapter.build_materialization_query(adapter.get_source_id())
+ insert_query = materialization_queries[str(adapter.get_source_id())]
if insert_query is None:
logger.info(
"marketing_costs_precompute",
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_cost_trends_query_resolver.py b/products/marketing_analytics/backend/hogql_queries/marketing_cost_trends_query_resolver.py
new file mode 100644
index 000000000000..a88fb279045d
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_cost_trends_query_resolver.py
@@ -0,0 +1,136 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import structlog
+
+from posthog.schema import (
+ DataWarehouseNode,
+ DataWarehousePropertyFilter,
+ MarketingAnalyticsDrillDownLevel,
+ PropertyOperator,
+)
+
+from posthog.models.team.team import DEFAULT_CURRENCY
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationTable,
+ ensure_precomputed,
+)
+
+from .adapters.base import QueryContext
+from .adapters.factory import MarketingSourceFactory
+from .marketing_analytics_base_query_runner import costs_precompute_ttl_schedule
+from .marketing_analytics_config import MarketingAnalyticsConfig
+
+if TYPE_CHECKING:
+ from collections.abc import Callable, Sequence
+
+ from posthog.schema import TrendsQuery
+
+ from posthog.hogql.database.database import Database
+
+ from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+ from posthog.models import Team
+
+logger = structlog.get_logger(__name__)
+
+
+class MarketingCostTrendsQueryResolver:
+ def __init__(
+ self,
+ query: TrendsQuery,
+ team: Team,
+ date_ranges: Sequence[QueryDateRange],
+ get_database: Callable[[], Database],
+ ) -> None:
+ self.query = query
+ self.team = team
+ self.date_ranges = date_ranges
+ self.get_database = get_database
+
+ def _covered_source_ids(self, date_ranges: Sequence[QueryDateRange]) -> list[str] | None:
+ fallback = self.query.marketingAnalyticsCostFallback
+ assert fallback is not None
+ selected_ids = set(fallback.sourceIds)
+ if not selected_ids or not date_ranges:
+ return None
+ grain = MarketingAnalyticsDrillDownLevel.CAMPAIGN
+ factory = MarketingSourceFactory(
+ context=QueryContext(
+ date_range=date_ranges[0],
+ team=self.team,
+ base_currency=self.team.base_currency or DEFAULT_CURRENCY,
+ drill_down_level=grain,
+ database=self.get_database(),
+ )
+ )
+ adapters = factory.get_valid_adapters(factory.create_adapters())
+ adapters = [adapter for adapter in adapters if adapter.get_source_id() in selected_ids]
+ queries = factory.build_materialization_queries(adapters, grain)
+ if set(queries) != selected_ids or any(query is None for query in queries.values()):
+ return None
+ for date_range in date_ranges:
+ for insert_query in queries.values():
+ assert insert_query is not None
+ # The chart excludes expired rows, so the marketing wrapper's stale grace cannot apply.
+ result = ensure_precomputed(
+ team=self.team,
+ insert_query=insert_query,
+ time_range_start=date_range.date_from(),
+ time_range_end=date_range.date_to(),
+ ttl_seconds=costs_precompute_ttl_schedule(self.team),
+ table=LazyComputationTable.MARKETING_COSTS_PREAGGREGATED,
+ run_inserts=False,
+ stale_while_revalidate_seconds=0,
+ )
+ if not result.ready or result.stale or result.freshly_built:
+ return None
+ return sorted(selected_ids)
+
+ def resolve_query(self) -> TrendsQuery:
+ fallback = self.query.marketingAnalyticsCostFallback
+ assert fallback is not None
+ requested_query = self.query.model_copy(deep=True)
+ requested_query.marketingAnalyticsCostFallback = None
+ if (
+ len(self.query.series) != 1
+ or not isinstance(self.query.series[0], DataWarehouseNode)
+ or self.query.series[0].table_name != "marketing_costs_precomputed"
+ ):
+ return requested_query
+ live_query = requested_query.model_copy(deep=True)
+ live_query.series = [series.model_copy(deep=True) for series in fallback.series]
+ live_query.breakdownFilter = None
+ if not fallback.series or (self.query.dateRange and self.query.dateRange.date_from == "all"):
+ return live_query
+ try:
+ if not MarketingAnalyticsConfig.from_team(self.team).costs_precomputation_enabled:
+ return live_query
+ source_ids = self._covered_source_ids(self.date_ranges)
+ if source_ids is None:
+ return live_query
+ except Exception:
+ logger.exception("marketing_cost_trend_coverage_check_failed", team_id=self.team.pk)
+ return live_query
+
+ precomputed_query = self.query.model_copy(deep=True)
+ precomputed_query.marketingAnalyticsCostFallback = None
+ series = precomputed_query.series[0]
+ assert isinstance(series, DataWarehouseNode)
+ # Scope the shared precompute table to sources visible to this caller, even without an explicit selection.
+ series.properties = [prop for prop in (series.properties or []) if getattr(prop, "key", None) != "source_id"]
+ series.properties.append(
+ DataWarehousePropertyFilter(key="source_id", operator=PropertyOperator.EXACT, value=list(source_ids))
+ )
+ return precomputed_query
+
+
+def resolve_marketing_cost_trend(
+ *,
+ query: TrendsQuery,
+ team: Team,
+ date_ranges: Sequence[QueryDateRange],
+ get_database: Callable[[], Database],
+) -> TrendsQuery:
+ return MarketingCostTrendsQueryResolver(query, team, date_ranges, get_database).resolve_query()
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_cost_trends_query_resolver.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_cost_trends_query_resolver.py
new file mode 100644
index 000000000000..4120c78304bb
--- /dev/null
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_cost_trends_query_resolver.py
@@ -0,0 +1,298 @@
+from datetime import UTC, datetime
+
+import time_machine
+from unittest.mock import Mock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ Breakdown,
+ BreakdownFilter,
+ CompareFilter,
+ DataWarehouseNode,
+ DataWarehousePropertyFilter,
+ DateRange,
+ EventsNode,
+ HogQLQueryModifiers,
+ MarketingAnalyticsCostFallback,
+ MarketingAnalyticsDrillDownLevel,
+ MarketingAnalyticsTableQuery,
+ TrendsQuery,
+)
+
+from posthog.hogql import ast
+
+from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
+from posthog.models import Team
+
+from products.analytics_platform.backend.lazy_computation.lazy_computation_executor import (
+ LazyComputationExecutor,
+ LazyComputationResult,
+ compute_query_hash,
+ ensure_precomputed,
+)
+from products.marketing_analytics.backend.hogql_queries.adapters.base import (
+ GoogleAdsConfig,
+ MarketingSourceAdapter,
+ QueryContext,
+)
+from products.marketing_analytics.backend.hogql_queries.adapters.factory import MarketingSourceFactory
+from products.marketing_analytics.backend.hogql_queries.adapters.google_ads import GoogleAdsAdapter
+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_config import MarketingAnalyticsConfig
+from products.marketing_analytics.backend.hogql_queries.marketing_analytics_table_query_runner import (
+ MarketingAnalyticsTableQueryRunner,
+)
+from products.marketing_analytics.backend.hogql_queries.marketing_cost_trends_query_resolver import (
+ MarketingCostTrendsQueryResolver,
+)
+from products.marketing_analytics.dags.marketing_precompute import _ensure_costs_for_team
+from products.warehouse_sources.backend.facade.models import DataWarehouseTable
+
+MODULE = "products.marketing_analytics.backend.hogql_queries.marketing_cost_trends_query_resolver"
+
+
+@time_machine.travel("2025-01-15T12:00:00Z", tick=False)
+class TestMarketingCostTrendsQueryResolver(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ self.team = Team(id=17, timezone="America/New_York", base_currency="USD")
+ self.live_series = [
+ DataWarehouseNode(
+ id=f"source_{source}_stats",
+ table_name=f"source_{source}_stats",
+ id_field="id",
+ distinct_id_field="id",
+ timestamp_field="date",
+ )
+ for source in ("a", "b")
+ ]
+ self.query = TrendsQuery(
+ interval="day",
+ dateRange=DateRange(date_from="2025-01-10", date_to="2025-01-12"),
+ compareFilter=CompareFilter(compare=True),
+ series=[
+ DataWarehouseNode(
+ id="marketing_costs_precomputed",
+ table_name="marketing_costs_precomputed",
+ id_field="campaign_id",
+ distinct_id_field="campaign_id",
+ timestamp_field="timestamp",
+ )
+ ],
+ breakdownFilter=BreakdownFilter(breakdowns=[Breakdown(type="data_warehouse", property="source_name")]),
+ marketingAnalyticsCostFallback=MarketingAnalyticsCostFallback(
+ series=self.live_series, sourceIds=["a", "b"]
+ ),
+ )
+ self.adapters = []
+ for source_id in ("a", "b"):
+ adapter = Mock(spec=MarketingSourceAdapter)
+ adapter.get_source_id.return_value = source_id
+ adapter.supports_level.return_value = True
+ adapter.build_materialization_query.return_value = ast.SelectQuery(select=[ast.Constant(value=source_id)])
+ self.adapters.append(adapter)
+ self.factory = self.enterContext(patch(f"{MODULE}.MarketingSourceFactory"))
+ self.factory.return_value.get_valid_adapters.return_value = self.adapters
+ self.factory.return_value.build_materialization_queries.side_effect = (
+ MarketingSourceFactory.build_materialization_queries
+ )
+ self.database = Mock()
+ self.ensure = self.enterContext(patch(f"{MODULE}.ensure_precomputed"))
+ self.config = self.enterContext(patch(f"{MODULE}.MarketingAnalyticsConfig.from_team"))
+ self.config.return_value = MarketingAnalyticsConfig(costs_precomputation_enabled=True)
+
+ def runner(self) -> MarketingCostTrendsQueryResolver:
+ current = QueryDateRange(
+ date_range=self.query.dateRange, team=self.team, interval=self.query.interval, now=datetime.now()
+ )
+ ranges = [current]
+ if self.query.compareFilter and self.query.compareFilter.compare:
+ previous = (
+ QueryCompareToDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=self.query.interval,
+ now=datetime.now(),
+ compare_to=self.query.compareFilter.compare_to,
+ full_comparison_period=True,
+ )
+ if self.query.compareFilter.compare_to
+ else QueryPreviousPeriodDateRange(
+ date_range=self.query.dateRange,
+ team=self.team,
+ interval=self.query.interval,
+ now=datetime.now(),
+ full_comparison_period=True,
+ )
+ )
+ ranges.append(previous)
+ return MarketingCostTrendsQueryResolver(self.query.model_copy(deep=True), self.team, ranges, self.database)
+
+ @parameterized.expand(
+ [
+ ("flag_off", False, [True, True, True, True], False),
+ ("current_source_missing", True, [True, False], False),
+ ("comparison_source_missing", True, [True, True, True, False], False),
+ ("complete_including_empty_windows", True, [True, True, True, True], True),
+ ("custom_comparison", True, [True, True, True, True], True),
+ ]
+ )
+ def test_selects_precomputed_only_for_complete_coverage(
+ self, _name: str, enabled: bool, coverage: list[bool], precomputed: bool
+ ) -> None:
+ self.config.return_value.costs_precomputation_enabled = enabled
+ if _name == "custom_comparison":
+ self.query.compareFilter = CompareFilter(compare=True, compare_to="-1y")
+ self.ensure.side_effect = [LazyComputationResult(ready=ready, job_ids=[]) for ready in coverage]
+ runner = self.runner()
+ result = runner.resolve_query()
+ assert result.marketingAnalyticsCostFallback is None
+ assert result.dateRange == self.query.dateRange
+ assert result.compareFilter == self.query.compareFilter
+ assert self.query.marketingAnalyticsCostFallback is not None
+ if precomputed:
+ series = result.series[0]
+ assert isinstance(series, DataWarehouseNode)
+ assert series.table_name == "marketing_costs_precomputed"
+ assert series.properties is not None
+ source_filter = series.properties[-1]
+ assert isinstance(source_filter, DataWarehousePropertyFilter)
+ assert source_filter.value == ["a", "b"]
+ assert result.breakdownFilter == self.query.breakdownFilter
+ checked_ranges = [
+ (call.kwargs["time_range_start"], call.kwargs["time_range_end"]) for call in self.ensure.call_args_list
+ ]
+ assert checked_ranges == [
+ (runner.date_ranges[0].date_from(), runner.date_ranges[0].date_to()),
+ (runner.date_ranges[0].date_from(), runner.date_ranges[0].date_to()),
+ (runner.date_ranges[1].date_from(), runner.date_ranges[1].date_to()),
+ (runner.date_ranges[1].date_from(), runner.date_ranges[1].date_to()),
+ ]
+ assert runner.date_ranges[0].date_from() == datetime(2025, 1, 10, 5, tzinfo=UTC)
+ if _name == "custom_comparison":
+ assert runner.date_ranges[1].date_from().year == 2024
+ else:
+ assert result.series == self.live_series
+ assert result.breakdownFilter is None
+ for call in self.ensure.call_args_list:
+ assert call.kwargs["run_inserts"] is False
+ assert call.kwargs["stale_while_revalidate_seconds"] == 0
+ if not enabled:
+ self.ensure.assert_not_called()
+ self.database.assert_not_called()
+
+ @parameterized.expand([("unmaterializable",), ("check_error",), ("inaccessible_source",), ("expired",)])
+ def test_uncertain_coverage_uses_live(self, case: str) -> None:
+ self.ensure.return_value = LazyComputationResult(ready=True, job_ids=[])
+ if case == "unmaterializable":
+ self.adapters[1].build_materialization_query.return_value = None
+ elif case == "check_error":
+ self.ensure.side_effect = RuntimeError("Coverage service unavailable")
+ elif case == "expired":
+ self.ensure.return_value = LazyComputationResult(ready=True, job_ids=[], stale=True)
+ else:
+ assert self.query.marketingAnalyticsCostFallback is not None
+ self.query.marketingAnalyticsCostFallback.sourceIds = ["b"]
+ self.factory.return_value.get_valid_adapters.return_value = self.adapters[:1]
+ result = self.runner().resolve_query()
+ assert result.series == self.live_series
+ assert result.breakdownFilter is None
+
+ @parameterized.expand([(True,), (False,)])
+ def test_only_selected_sources_and_current_period_need_coverage(self, ready: bool) -> None:
+ assert self.query.marketingAnalyticsCostFallback is not None
+ self.query.marketingAnalyticsCostFallback.sourceIds = ["b"]
+ self.query.marketingAnalyticsCostFallback.series = self.live_series[1:]
+ self.query.compareFilter = CompareFilter(compare=False)
+ self.ensure.return_value = LazyComputationResult(ready=ready, job_ids=[])
+ result = self.runner().resolve_query()
+ if ready:
+ series = result.series[0]
+ assert isinstance(series, DataWarehouseNode)
+ assert series.table_name == "marketing_costs_precomputed"
+ assert series.properties is not None
+ source_filter = series.properties[-1]
+ assert isinstance(source_filter, DataWarehousePropertyFilter)
+ assert source_filter.value == ["b"]
+ else:
+ assert result.series == self.live_series[1:]
+ assert result.breakdownFilter is None
+ assert self.ensure.call_count == 1
+ assert self.ensure.call_args.kwargs["insert_query"].select == [ast.Constant(value="b")]
+
+ @parameterized.expand([("replace_series",), ("add_series",)])
+ def test_edited_insight_executes_requested_series(self, case: str) -> None:
+ event = EventsNode(event="$pageview")
+ self.query.series = [event] if case == "replace_series" else [*self.query.series, event]
+ result = self.runner().resolve_query()
+ assert result.series == self.query.series
+ assert result.breakdownFilter == self.query.breakdownFilter
+ assert result.marketingAnalyticsCostFallback is None
+ self.ensure.assert_not_called()
+
+ def test_coverage_and_warmer_hash_the_same_real_adapter(self) -> None:
+ assert self.query.marketingAnalyticsCostFallback is not None
+ self.query.marketingAnalyticsCostFallback.sourceIds = ["a"]
+ self.query.marketingAnalyticsCostFallback.series = self.live_series[:1]
+ runner = self.runner()
+ adapter_config = GoogleAdsConfig(
+ source_type="GoogleAds",
+ source_id="a",
+ campaign_table=DataWarehouseTable(name="googleads_campaign", columns={}),
+ stats_table=DataWarehouseTable(name="googleads_campaign_stats", columns={}),
+ )
+
+ def initialize_factory(factory: MarketingSourceFactory, context: QueryContext) -> None:
+ factory.context = context
+
+ def create_adapters(factory: MarketingSourceFactory) -> list[MarketingSourceAdapter]:
+ return [GoogleAdsAdapter(adapter_config, factory.context)]
+
+ self.factory.side_effect = MarketingSourceFactory
+ self.ensure.side_effect = ensure_precomputed
+ base_module = "products.marketing_analytics.backend.hogql_queries.marketing_analytics_base_query_runner"
+ with (
+ patch(
+ "posthog.hogql_queries.query_runner.create_default_modifiers_for_team",
+ return_value=HogQLQueryModifiers(),
+ ),
+ patch.object(MarketingSourceFactory, "__init__", initialize_factory),
+ patch.object(MarketingSourceFactory, "create_adapters", create_adapters),
+ patch(f"{base_module}.MarketingSourceFactory", MarketingSourceFactory),
+ patch(f"{base_module}.marketing_ensure_precomputed", side_effect=ensure_precomputed),
+ patch.object(
+ LazyComputationExecutor, "execute", return_value=LazyComputationResult(ready=True, job_ids=[])
+ ) as execute,
+ ):
+ series = runner.resolve_query().series[0]
+ assert isinstance(series, DataWarehouseNode)
+ assert series.table_name == "marketing_costs_precomputed"
+ trend_hashes = [compute_query_hash(call.args[1]) for call in execute.call_args_list]
+ execute.reset_mock()
+ warmer = MarketingAnalyticsTableQueryRunner(
+ query=MarketingAnalyticsTableQuery(properties=[]), team=self.team
+ )
+ warmer.__dict__["_shared_hogql_database"] = runner.get_database()
+ for date_range in (runner.date_ranges[0], runner.date_ranges[1]):
+ warmer._build_costs_from_precompute(date_range)
+ warmer_hashes = [compute_query_hash(call.args[1]) for call in execute.call_args_list]
+ execute.reset_mock()
+ dag_module = "products.marketing_analytics.dags.marketing_precompute"
+ with patch(f"{dag_module}.COST_MATERIALIZATION_GRAINS", [MarketingAnalyticsDrillDownLevel.CAMPAIGN]):
+ _ensure_costs_for_team(
+ Mock(),
+ self.team,
+ runner.date_ranges[0].date_from(),
+ runner.date_ranges[0].date_to(),
+ 30,
+ database=runner.get_database(),
+ )
+ scheduled_hashes = [compute_query_hash(call.args[1]) for call in execute.call_args_list]
+ assert len(trend_hashes) == 2
+ assert trend_hashes[0] == trend_hashes[1]
+ assert trend_hashes == warmer_hashes
+ assert scheduled_hashes == trend_hashes[:1]
diff --git a/products/product_analytics/backend/hogql_queries/trends/test/test_marketing_cost_fallback.py b/products/product_analytics/backend/hogql_queries/trends/test/test_marketing_cost_fallback.py
new file mode 100644
index 000000000000..bc2f7a5d3a96
--- /dev/null
+++ b/products/product_analytics/backend/hogql_queries/trends/test/test_marketing_cost_fallback.py
@@ -0,0 +1,94 @@
+from collections.abc import Callable, Sequence
+from datetime import UTC, datetime
+
+import time_machine
+from unittest.mock import patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.schema import (
+ CompareFilter,
+ DataWarehouseNode,
+ DateRange,
+ HogQLQueryModifiers,
+ MarketingAnalyticsCostFallback,
+ TrendsQuery,
+ TrendsQueryResponse,
+)
+
+from posthog.hogql.database.database import Database
+
+from posthog.hogql_queries.utils.query_date_range import QueryDateRange
+from posthog.models import Team, User
+
+from products.product_analytics.backend.hogql_queries.trends.trends_query_runner import TrendsQueryRunner
+
+
+@time_machine.travel("2025-01-15T12:00:00Z", tick=False)
+class TestMarketingCostFallback(SimpleTestCase):
+ @parameterized.expand([(True, None), (False, None), (True, "-1y"), (False, "-1y")])
+ def test_resolved_series_reuse_database_and_exact_trends_periods(self, ready: bool, compare_to: str | None) -> None:
+ team = Team(id=17, timezone="America/New_York", base_currency="USD")
+ user = User(id=3)
+ precomputed = DataWarehouseNode(
+ id="marketing_costs_precomputed",
+ table_name="marketing_costs_precomputed",
+ id_field="campaign_id",
+ distinct_id_field="campaign_id",
+ timestamp_field="timestamp",
+ )
+ live = DataWarehouseNode(
+ id="source_stats", table_name="source_stats", id_field="id", distinct_id_field="id", timestamp_field="date"
+ )
+ query = TrendsQuery(
+ interval="day",
+ dateRange=DateRange(date_from="2025-01-10", date_to="2025-01-12"),
+ compareFilter=CompareFilter(compare=True, compare_to=compare_to),
+ series=[precomputed],
+ marketingAnalyticsCostFallback=MarketingAnalyticsCostFallback(series=[live], sourceIds=["a"]),
+ )
+ original_calculate = TrendsQueryRunner.calculate
+
+ def execute_resolved(runner: TrendsQueryRunner) -> TrendsQueryResponse:
+ if runner.query.marketingAnalyticsCostFallback is not None:
+ return original_calculate(runner)
+ assert runner.shared_database is database.return_value
+ series = runner.query.series[0]
+ assert isinstance(series, DataWarehouseNode)
+ return TrendsQueryResponse(results=[{"label": series.table_name}])
+
+ def resolve(
+ *,
+ query: TrendsQuery,
+ team: Team,
+ date_ranges: Sequence[QueryDateRange],
+ get_database: Callable[[], Database],
+ ) -> TrendsQuery:
+ assert len(date_ranges) == 2
+ assert date_ranges[0].date_from() == datetime(2025, 1, 10, 5, tzinfo=UTC)
+ assert date_ranges[1].date_from().year == (2024 if compare_to else 2025)
+ assert get_database() is database.return_value
+ result = query.model_copy(deep=True)
+ result.marketingAnalyticsCostFallback = None
+ result.series = [precomputed if ready else live]
+ return result
+
+ with (
+ patch("posthog.hogql_queries.query_runner.Database.create_for") as database,
+ patch(
+ "posthog.hogql_queries.query_runner.create_default_modifiers_for_team",
+ return_value=HogQLQueryModifiers(),
+ ),
+ patch("posthog.hogql_queries.query_runner.get_instance_setting", return_value=True),
+ patch(
+ "products.marketing_analytics.backend.facade.queries.resolve_marketing_cost_trend", side_effect=resolve
+ ),
+ patch.object(TrendsQueryRunner, "calculate", execute_resolved),
+ ):
+ result = TrendsQueryRunner(query=query, team=team, user=user).calculate()
+ assert result.results[0]["label"] == ("marketing_costs_precomputed" if ready else "source_stats")
+ database.assert_called_once()
+ assert database.call_args.kwargs["user"] is user
+ assert not database.call_args.kwargs.get("bypass_warehouse_access_control", False)
diff --git a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
index 10798a2da471..0cbbdb6c0f2f 100644
--- a/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
+++ b/products/product_analytics/backend/hogql_queries/trends/trends_query_runner.py
@@ -405,6 +405,33 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
)
def _calculate(self):
+ if self.query.marketingAnalyticsCostFallback is not None:
+ from products.marketing_analytics.backend.facade.queries import (
+ resolve_marketing_cost_trend, # noqa: PLC0415 - keeps marketing adapters off the startup path
+ )
+
+ date_ranges = [self.query_date_range]
+ if self.query.compareFilter and self.query.compareFilter.compare:
+ date_ranges.append(self.query_previous_date_range)
+ resolved_query = resolve_marketing_cost_trend(
+ query=self.query,
+ team=self.team,
+ date_ranges=date_ranges,
+ get_database=lambda: self.shared_database,
+ )
+ runner = TrendsQueryRunner(
+ query=resolved_query,
+ team=self.team,
+ timings=self.timings,
+ modifiers=self.modifiers,
+ limit_context=self.limit_context,
+ user=self.user,
+ workload=self.workload,
+ hogql_settings=self.hogql_settings,
+ )
+ runner._shared_database = self._shared_database
+ return runner.calculate()
+
queries = self.to_queries()
response_hogql = get_response_hogql(
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index 447ed5d3afed..17353b75d05e 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -428,423 +428,163 @@ export const IntervalTypeApi = {
Year: 'year',
} as const
-export type BounceRatePageViewModeApi = (typeof BounceRatePageViewModeApi)[keyof typeof BounceRatePageViewModeApi]
-
-export const BounceRatePageViewModeApi = {
- CountPageviews: 'count_pageviews',
- UniqUrls: 'uniq_urls',
- UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
-} as const
+export interface PersonMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
+ type?: 'person_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]
+export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]
-export const FilterLogicalOperatorApi = {
- And: 'AND',
- Or: 'OR',
+export const Key10Api = {
+ TagName: 'tag_name',
+ Text: 'text',
+ Href: 'href',
+ Selector: 'selector',
} as const
-export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+export interface ElementPropertyFilterApi {
+ key: Key10Api
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'element'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const CustomBotFieldApi = {
- 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',
- GeoipCountryCode: '$geoip_country_code',
- Referrer: '$referrer',
- ReferringDomain: '$referring_domain',
-} as const
+export interface EventMetadataPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'event_metadata'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]
-export const CustomBotMatcherApi = {
- Contains: 'contains',
- Regex: 'regex',
- Exact: 'exact',
- Cidr: 'cidr',
+export const DurationTypeApi = {
+ Duration: 'duration',
+ ActiveSeconds: 'active_seconds',
+ InactiveSeconds: 'inactive_seconds',
} as const
-export interface CustomBotConditionApi {
- id: string
- /** The event property this condition reads. */
- key: CustomBotFieldApi
- matcher: CustomBotMatcherApi
- /** Matched against the property named by `key`. */
- pattern: string
+export interface RecordingPropertyFilterApi {
+ key: DurationTypeApi | string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'recording'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export interface CustomBotRuleApi {
- /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
- category?: string | null
- /** Whether every condition must match (AND) or any one of them (OR). */
- combiner: FilterLogicalOperatorApi
- id: string
- items: CustomBotConditionApi[]
- /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */
- name: string
+export interface LogEntryPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'log_entry'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]
-
-export const CustomChannelFieldApi = {
- UtmSource: 'utm_source',
- UtmMedium: 'utm_medium',
- UtmCampaign: 'utm_campaign',
- ReferringDomain: 'referring_domain',
- Url: 'url',
- Pathname: 'pathname',
- Hostname: 'hostname',
-} as const
-
-export type CustomChannelOperatorApi = (typeof CustomChannelOperatorApi)[keyof typeof CustomChannelOperatorApi]
-
-export const CustomChannelOperatorApi = {
- Exact: 'exact',
- IsNot: 'is_not',
- IsSet: 'is_set',
- IsNotSet: 'is_not_set',
- Icontains: 'icontains',
- NotIcontains: 'not_icontains',
- Regex: 'regex',
- NotRegex: 'not_regex',
-} as const
+export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null
-export interface CustomChannelConditionApi {
- id: string
- key: CustomChannelFieldApi
- op: CustomChannelOperatorApi
- value?: string | string[] | null
+export interface GroupPropertyFilterApi {
+ group_key_names?: GroupPropertyFilterApiGroupKeyNames
+ group_type_index?: number | null
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'group'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export interface CustomChannelRuleApi {
- channel_type: string
- combiner: FilterLogicalOperatorApi
- id: string
- items: CustomChannelConditionApi[]
+export interface FeaturePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ /** Event property with "$feature/" prepended */
+ type?: 'feature'
+ value?: (string | number | boolean)[] | string | number | boolean | null
}
-export interface DataWarehouseEventsModifierApi {
- distinct_id_field: string
- id_field: string
- table_name: string
- timestamp_field: string
+export interface FlagPropertyFilterApi {
+ /** The key should be the flag ID */
+ key: string
+ label?: string | null
+ /** Only flag_evaluates_to operator is allowed for flag dependencies */
+ operator?: 'flag_evaluates_to'
+ /** Feature flag dependency */
+ type?: 'flag'
+ /** The value can be true, false, or a variant name */
+ value: boolean | string
}
-export type InCohortViaApi = (typeof InCohortViaApi)[keyof typeof InCohortViaApi]
+export interface HogQLPropertyFilterApi {
+ key: string
+ label?: string | null
+ type?: 'hogql'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const InCohortViaApi = {
- Auto: 'auto',
- Leftjoin: 'leftjoin',
- Subquery: 'subquery',
- LeftjoinConjoined: 'leftjoin_conjoined',
+export const EmptyPropertyFilterApiValue = {
+ type: 'empty',
} as const
+export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue
-export type InlineCohortCalculationApi = (typeof InlineCohortCalculationApi)[keyof typeof InlineCohortCalculationApi]
-
-export const InlineCohortCalculationApi = {
- Off: 'off',
- Auto: 'auto',
- Always: 'always',
-} as const
+export interface DataWarehousePropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type MaterializationModeApi = (typeof MaterializationModeApi)[keyof typeof MaterializationModeApi]
+export interface DataWarehousePersonPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'data_warehouse_person_property'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const MaterializationModeApi = {
- Auto: 'auto',
- LegacyNullAsString: 'legacy_null_as_string',
- LegacyNullAsNull: 'legacy_null_as_null',
- Disabled: 'disabled',
-} as const
+export interface ErrorTrackingIssueFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'error_tracking_issue'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type MaterializedColumnsOptimizationModeApi =
- (typeof MaterializedColumnsOptimizationModeApi)[keyof typeof MaterializedColumnsOptimizationModeApi]
+export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]
-export const MaterializedColumnsOptimizationModeApi = {
- Disabled: 'disabled',
- Optimized: 'optimized',
+export const LogPropertyFilterTypeApi = {
+ Log: 'log',
+ LogAttribute: 'log_attribute',
+ LogResourceAttribute: 'log_resource_attribute',
} as const
-export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]
+export interface LogPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type: LogPropertyFilterTypeApi
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export const ParserModeApi = {
- CppOnly: 'cpp_only',
- CppWithRustShadow: 'cpp_with_rust_shadow',
- CppWithRustPyShadow: 'cpp_with_rust_py_shadow',
- RustWithCppShadow: 'rust_with_cpp_shadow',
- RustOnly: 'rust_only',
- RustPyOnly: 'rust_py_only',
- RustPyWithCppShadow: 'rust_py_with_cpp_shadow',
-} as const
+export interface MetricPropertyFilterApi {
+ key: string
+ label?: string | null
+ operator: PropertyOperatorApi
+ type?: 'metric_attribute'
+ value?: (string | number | boolean)[] | string | number | boolean | null
+}
-export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]
+export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]
-export const PersonsArgMaxVersionApi = {
- Auto: 'auto',
- V1: 'v1',
- V2: 'v2',
-} as const
-
-export type PersonsJoinModeApi = (typeof PersonsJoinModeApi)[keyof typeof PersonsJoinModeApi]
-
-export const PersonsJoinModeApi = {
- Inner: 'inner',
- Left: 'left',
-} as const
-
-export type PersonsOnEventsModeApi = (typeof PersonsOnEventsModeApi)[keyof typeof PersonsOnEventsModeApi]
-
-export const PersonsOnEventsModeApi = {
- Disabled: 'disabled',
- PersonIdNoOverridePropertiesOnEvents: 'person_id_no_override_properties_on_events',
- PersonIdOverridePropertiesOnEvents: 'person_id_override_properties_on_events',
- PersonIdOverridePropertiesJoined: 'person_id_override_properties_joined',
-} as const
-
-export type PropertyGroupsModeApi = (typeof PropertyGroupsModeApi)[keyof typeof PropertyGroupsModeApi]
-
-export const PropertyGroupsModeApi = {
- Enabled: 'enabled',
- Disabled: 'disabled',
- Optimized: 'optimized',
-} as const
-
-export type SessionTableVersionApi = (typeof SessionTableVersionApi)[keyof typeof SessionTableVersionApi]
-
-export const SessionTableVersionApi = {
- Auto: 'auto',
- V1: 'v1',
- V2: 'v2',
- V3: 'v3',
-} as const
-
-export type SessionsV2JoinModeApi = (typeof SessionsV2JoinModeApi)[keyof typeof SessionsV2JoinModeApi]
-
-export const SessionsV2JoinModeApi = {
- String: 'string',
- Uuid: 'uuid',
-} as const
-
-export interface HogQLQueryModifiersApi {
- bounceRateDurationSeconds?: number | null
- bounceRatePageViewMode?: BounceRatePageViewModeApi | null
- convertToProjectTimezone?: boolean | null
- /** 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
- customBotDefinitions?: CustomBotRuleApi[] | null
- customChannelTypeRules?: CustomChannelRuleApi[] | null
- dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
- debug?: boolean | null
- /** If these are provided, the query will fail if these skip indexes are not used */
- forceClickhouseDataSkippingIndexes?: string[] | null
- formatCsvAllowDoubleQuotes?: boolean | null
- inCohortVia?: InCohortViaApi | null
- inlineCohortCalculation?: InlineCohortCalculationApi | null
- materializationMode?: MaterializationModeApi | null
- materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
- /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
- mergeFederatedAggregateJoins?: boolean | null
- /** 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 | null
- optimizeJoinedFilters?: boolean | null
- optimizeProjections?: boolean | null
- /** 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?: ParserModeApi | null
- /** 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 | null
- personsArgMaxVersion?: PersonsArgMaxVersionApi | null
- personsJoinMode?: PersonsJoinModeApi | null
- personsOnEventsMode?: PersonsOnEventsModeApi | null
- propertyGroupsMode?: PropertyGroupsModeApi | null
- pushDownPredicates?: boolean | null
- s3TableUseInvalidColumns?: boolean | null
- /** 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 | null
- /** 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 | null
- sessionTableVersion?: SessionTableVersionApi | null
- /** 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?: number | null
- sessionsV2JoinMode?: SessionsV2JoinModeApi | null
- timings?: boolean | null
- /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
- typeAwareCastSimplification?: boolean | null
- useMaterializedViews?: boolean | null
- /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
- useNewEventsCluster?: boolean | null
- /** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
- useNewEventsSchema?: boolean | null
- usePreaggregatedIntermediateResults?: boolean | null
- /** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */
- usePreaggregatedTableTransforms?: boolean | null
- useWebAnalyticsPreAggregatedTables?: boolean | null
- /** 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 | null
-}
-
-export interface PersonMetadataPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- /** Top-level columns on the persons table (e.g. created_at), not properties JSON */
- type?: 'person_metadata'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type Key10Api = (typeof Key10Api)[keyof typeof Key10Api]
-
-export const Key10Api = {
- TagName: 'tag_name',
- Text: 'text',
- Href: 'href',
- Selector: 'selector',
-} as const
-
-export interface ElementPropertyFilterApi {
- key: Key10Api
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'element'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface EventMetadataPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'event_metadata'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type DurationTypeApi = (typeof DurationTypeApi)[keyof typeof DurationTypeApi]
-
-export const DurationTypeApi = {
- Duration: 'duration',
- ActiveSeconds: 'active_seconds',
- InactiveSeconds: 'inactive_seconds',
-} as const
-
-export interface RecordingPropertyFilterApi {
- key: DurationTypeApi | string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'recording'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface LogEntryPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'log_entry'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type GroupPropertyFilterApiGroupKeyNames = { [key: string]: string } | null
-
-export interface GroupPropertyFilterApi {
- group_key_names?: GroupPropertyFilterApiGroupKeyNames
- group_type_index?: number | null
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'group'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface FeaturePropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- /** Event property with "$feature/" prepended */
- type?: 'feature'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface FlagPropertyFilterApi {
- /** The key should be the flag ID */
- key: string
- label?: string | null
- /** Only flag_evaluates_to operator is allowed for flag dependencies */
- operator?: 'flag_evaluates_to'
- /** Feature flag dependency */
- type?: 'flag'
- /** The value can be true, false, or a variant name */
- value: boolean | string
-}
-
-export interface HogQLPropertyFilterApi {
- key: string
- label?: string | null
- type?: 'hogql'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export const EmptyPropertyFilterApiValue = {
- type: 'empty',
-} as const
-export type EmptyPropertyFilterApi = typeof EmptyPropertyFilterApiValue
-
-export interface DataWarehousePropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'data_warehouse'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface DataWarehousePersonPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'data_warehouse_person_property'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface ErrorTrackingIssueFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'error_tracking_issue'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type LogPropertyFilterTypeApi = (typeof LogPropertyFilterTypeApi)[keyof typeof LogPropertyFilterTypeApi]
-
-export const LogPropertyFilterTypeApi = {
- Log: 'log',
- LogAttribute: 'log_attribute',
- LogResourceAttribute: 'log_resource_attribute',
-} as const
-
-export interface LogPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type: LogPropertyFilterTypeApi
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export interface MetricPropertyFilterApi {
- key: string
- label?: string | null
- operator: PropertyOperatorApi
- type?: 'metric_attribute'
- value?: (string | number | boolean)[] | string | number | boolean | null
-}
-
-export type SpanPropertyFilterTypeApi = (typeof SpanPropertyFilterTypeApi)[keyof typeof SpanPropertyFilterTypeApi]
-
-export const SpanPropertyFilterTypeApi = {
- Span: 'span',
- SpanAttribute: 'span_attribute',
- SpanResourceAttribute: 'span_resource_attribute',
+export const SpanPropertyFilterTypeApi = {
+ Span: 'span',
+ SpanAttribute: 'span_attribute',
+ SpanResourceAttribute: 'span_resource_attribute',
} as const
export interface SpanPropertyFilterApi {
@@ -935,231 +675,6 @@ export interface BehavioralPropertyFilterApi {
value: InlineBehavioralTypeApi
}
-export interface PropertyGroupFilterValueApi {
- type: FilterLogicalOperatorApi
- values: (
- | PropertyGroupFilterValueApi
- | EventPropertyFilterApi
- | PersonPropertyFilterApi
- | PersonMetadataPropertyFilterApi
- | ElementPropertyFilterApi
- | EventMetadataPropertyFilterApi
- | SessionPropertyFilterApi
- | CohortPropertyFilterApi
- | RecordingPropertyFilterApi
- | LogEntryPropertyFilterApi
- | GroupPropertyFilterApi
- | FeaturePropertyFilterApi
- | FlagPropertyFilterApi
- | HogQLPropertyFilterApi
- | EmptyPropertyFilterApi
- | DataWarehousePropertyFilterApi
- | DataWarehousePersonPropertyFilterApi
- | ErrorTrackingIssueFilterApi
- | LogPropertyFilterApi
- | MetricPropertyFilterApi
- | SpanPropertyFilterApi
- | RevenueAnalyticsPropertyFilterApi
- | AccountCustomPropertyFilterApi
- | WorkflowVariablePropertyFilterApi
- | BehavioralPropertyFilterApi
- )[]
-}
-
-export interface PropertyGroupFilterApi {
- type: FilterLogicalOperatorApi
- values: PropertyGroupFilterValueApi[]
-}
-
-export interface BoxPlotDatumApi {
- day: string
- label: string
- max: number
- mean: number
- median: number
- min: number
- p25: number
- p75: number
- series_index?: number | null
- series_label?: string | null
-}
-
-export interface ClickhouseQueryProgressApi {
- active_cpu_time: number
- bytes_read: number
- estimated_rows_total: number
- rows_read: number
- time_elapsed: number
-}
-
-export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
-
-export const QueryScanFixLocationApi = {
- Query: 'query',
- Subquery: 'subquery',
- View: 'view',
- InsightDateRange: 'insight_date_range',
- DashboardDateFilter: 'dashboard_date_filter',
-} as const
-
-export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
-
-export const QueryScanFindingKindApi = {
- NoEventFilter: 'no_event_filter',
- NoStartDate: 'no_start_date',
- PersonsJoin: 'persons_join',
-} as const
-
-export interface QueryScanWarningApi {
- /** 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
- /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
- by_design?: boolean | null
- /** 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 | null
- /** The one fact the finding rests on. */
- evidence?: string | null
- /** What "Fix with AI" and the assistant are told to do. */
- fix: string
- /** Where the change goes. Absent means the query itself. */
- fix_location?: QueryScanFixLocationApi | null
- kind: QueryScanFindingKindApi
- /** Shown to the person: what happened and what to do. */
- message: string
-}
-
-export interface QueryScanAnalysisApi {
- /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
- assistant_prompt?: string | null
- /** Every finding, fixable or not. Empty when the analysis found none. */
- findings: QueryScanWarningApi[]
- /** How much of all the project's events the query read, 0 to 1. */
- project_share?: number | null
- /** How much of the project's events in the query's date range the query read, 0 to 1. */
- range_share?: number | null
-}
-
-export interface QueryScanSummaryApi {
- /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */
- analysis?: QueryScanAnalysisApi | null
- /** 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 | null
- /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */
- duration_ms: number
- /** True when ClickHouse stopped the run instead of finishing it. */
- killed?: boolean | null
- /** Rows ClickHouse read for the last fresh run, all tables included. */
- rows_read: number
-}
-
-export interface QueryStatusApi {
- budget_remaining_bytes?: number | null
- bytes_read?: number | null
- /** Cache key of the run that failed, so clients can ask for its query scan. */
- cache_key?: string | null
- /** 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. */
- complete?: boolean | null
- dashboard_id?: number | null
- /** When did the query execution task finish (whether successfully or not). */
- end_time?: string | null
- /** If the query failed, this will be set to true. More information can be found in the error_message field. */
- error?: boolean | null
- /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */
- error_code?: string | null
- error_message?: string | null
- expiration_time?: string | null
- id: string
- insight_id?: number | null
- labels?: string[] | null
- /** When was the query execution task picked up by a worker. */
- pickup_time?: string | null
- /** ONLY async queries use QueryStatus. */
- query_async?: true
- query_progress?: ClickhouseQueryProgressApi | null
- query_scan?: QueryScanSummaryApi | null
- results?: unknown
- /** When was query execution task enqueued. */
- start_time?: string | null
- task_id?: string | null
- team_id: number
-}
-
-export interface ResolvedDateRangeResponseApi {
- date_from: string
- date_to: string
-}
-
-export interface QueryTimingApi {
- /** Key. Shortened to 'k' to save on data. */
- k: string
- /** Time in seconds. Shortened to 't' to save on data. */
- t: number
-}
-
-export interface DataWarehouseSourceUsageApi {
- /** ExternalDataSource id */
- id: string
- /** Connector type of the source (e.g. Stripe, Postgres), if known */
- source_type?: string | null
- /** Warehouse table name that was referenced */
- table_name: string
-}
-
-export interface DataWarehouseSyncWarningApi {
- /** 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 | null
- /** Human-readable warning shown to the user */
- message: string
- /** Name of the ExternalDataSchema responsible for syncing the table */
- schema_name: string
- /** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */
- source_id?: string | null
- /** Source type, e.g. "Stripe", "Hubspot" */
- source_type: string
- /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
- status: string
- /** Name of the warehouse table the warning refers to */
- table_name: string
- /** Tells warning kinds apart in the shared `warnings` list */
- type?: 'warehouse_sync'
-}
-
-export interface AccessControlFilterWarningApi {
- /** Human-readable warning shown to the user */
- message: string
- /** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */
- resources: string[]
- /** Tells warning kinds apart in the shared `warnings` list */
- type?: 'access_control'
-}
-
-export type TrendsQueryResponseApiResultsItem = { [key: string]: unknown }
-
-export interface TrendsQueryResponseApi {
- boxplot_data?: BoxPlotDatumApi[] | null
- /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
- error?: string | null
- /** Wether more breakdown values are available. */
- hasMore?: boolean | null
- /** Generated HogQL query. */
- hogql?: string | null
- /** Modifiers used when performing the query */
- modifiers?: HogQLQueryModifiersApi | null
- /** Query status indicates whether next to the provided data, a query is still running. */
- query_status?: QueryStatusApi | null
- /** The resolved previous/comparison period date range, when comparing against another period */
- resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
- /** The date range used for the query */
- resolved_date_range?: ResolvedDateRangeResponseApi | null
- results: TrendsQueryResponseApiResultsItem[]
- /** Measured timings for different parts of the query generation process */
- timings?: QueryTimingApi[] | null
- /** Connector-synced data warehouse sources referenced by this query, if any. */
- used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null
- /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
- warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
-}
-
export type BaseMathTypeApi = (typeof BaseMathTypeApi)[keyof typeof BaseMathTypeApi]
export const BaseMathTypeApi = {
@@ -1403,9 +918,599 @@ export const CurrencyCodeApi = {
Zmw: 'ZMW',
} as const
-export interface RevenueCurrencyPropertyConfigApi {
- property?: string | null
- static?: CurrencyCodeApi | null
+export interface RevenueCurrencyPropertyConfigApi {
+ property?: string | null
+ static?: CurrencyCodeApi | null
+}
+
+export type DataWarehouseNodeApiResponse = { [key: string]: unknown } | null
+
+export interface DataWarehouseNodeApi {
+ custom_name?: string | null
+ distinct_id_field: string
+ dw_source_type?: string | null
+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
+ fixedProperties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+ | null
+ id: string
+ id_field: string
+ kind?: 'DataWarehouseNode'
+ math?:
+ | BaseMathTypeApi
+ | FunnelMathTypeApi
+ | PropertyMathTypeApi
+ | CountPerActorMathTypeApi
+ | GroupMathTypeApi
+ | ExperimentMetricMathTypeApi
+ | CalendarHeatmapMathTypeApi
+ | 'hogql'
+ | null
+ math_group_type_index?: MathGroupTypeIndexApi | null
+ math_hogql?: string | null
+ math_multiplier?: number | null
+ math_property?: string | null
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
+ math_property_type?: string | null
+ name?: string | null
+ optionalInFunnel?: boolean | null
+ /** Properties configurable in the interface */
+ properties?:
+ | (
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+ | null
+ response?: DataWarehouseNodeApiResponse
+ table_name: string
+ timestamp_field: string
+ /** version of the node, used for schema migrations */
+ version?: number | null
+}
+
+export interface MarketingAnalyticsCostFallbackApi {
+ /**
+ * @minItems 1
+ * @maxItems 200
+ */
+ series: DataWarehouseNodeApi[]
+ /**
+ * @minItems 1
+ * @maxItems 200
+ */
+ sourceIds: string[]
+}
+
+export type BounceRatePageViewModeApi = (typeof BounceRatePageViewModeApi)[keyof typeof BounceRatePageViewModeApi]
+
+export const BounceRatePageViewModeApi = {
+ CountPageviews: 'count_pageviews',
+ UniqUrls: 'uniq_urls',
+ UniqPageScreenAutocaptures: 'uniq_page_screen_autocaptures',
+} as const
+
+export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]
+
+export const FilterLogicalOperatorApi = {
+ And: 'AND',
+ Or: 'OR',
+} as const
+
+export type CustomBotFieldApi = (typeof CustomBotFieldApi)[keyof typeof CustomBotFieldApi]
+
+export const CustomBotFieldApi = {
+ 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',
+ GeoipCountryCode: '$geoip_country_code',
+ Referrer: '$referrer',
+ ReferringDomain: '$referring_domain',
+} as const
+
+export type CustomBotMatcherApi = (typeof CustomBotMatcherApi)[keyof typeof CustomBotMatcherApi]
+
+export const CustomBotMatcherApi = {
+ Contains: 'contains',
+ Regex: 'regex',
+ Exact: 'exact',
+ Cidr: 'cidr',
+} as const
+
+export interface CustomBotConditionApi {
+ id: string
+ /** The event property this condition reads. */
+ key: CustomBotFieldApi
+ matcher: CustomBotMatcherApi
+ /** Matched against the property named by `key`. */
+ pattern: string
+}
+
+export interface CustomBotRuleApi {
+ /** Reported by `$virt_traffic_category`. Defaults to `custom`. */
+ category?: string | null
+ /** Whether every condition must match (AND) or any one of them (OR). */
+ combiner: FilterLogicalOperatorApi
+ id: string
+ items: CustomBotConditionApi[]
+ /** Reported by `$virt_bot_name` and `$virt_bot_operator` when the rule matches. */
+ name: string
+}
+
+export type CustomChannelFieldApi = (typeof CustomChannelFieldApi)[keyof typeof CustomChannelFieldApi]
+
+export const CustomChannelFieldApi = {
+ UtmSource: 'utm_source',
+ UtmMedium: 'utm_medium',
+ UtmCampaign: 'utm_campaign',
+ ReferringDomain: 'referring_domain',
+ Url: 'url',
+ Pathname: 'pathname',
+ Hostname: 'hostname',
+} as const
+
+export type CustomChannelOperatorApi = (typeof CustomChannelOperatorApi)[keyof typeof CustomChannelOperatorApi]
+
+export const CustomChannelOperatorApi = {
+ Exact: 'exact',
+ IsNot: 'is_not',
+ IsSet: 'is_set',
+ IsNotSet: 'is_not_set',
+ Icontains: 'icontains',
+ NotIcontains: 'not_icontains',
+ Regex: 'regex',
+ NotRegex: 'not_regex',
+} as const
+
+export interface CustomChannelConditionApi {
+ id: string
+ key: CustomChannelFieldApi
+ op: CustomChannelOperatorApi
+ value?: string | string[] | null
+}
+
+export interface CustomChannelRuleApi {
+ channel_type: string
+ combiner: FilterLogicalOperatorApi
+ id: string
+ items: CustomChannelConditionApi[]
+}
+
+export interface DataWarehouseEventsModifierApi {
+ distinct_id_field: string
+ id_field: string
+ table_name: string
+ timestamp_field: string
+}
+
+export type InCohortViaApi = (typeof InCohortViaApi)[keyof typeof InCohortViaApi]
+
+export const InCohortViaApi = {
+ Auto: 'auto',
+ Leftjoin: 'leftjoin',
+ Subquery: 'subquery',
+ LeftjoinConjoined: 'leftjoin_conjoined',
+} as const
+
+export type InlineCohortCalculationApi = (typeof InlineCohortCalculationApi)[keyof typeof InlineCohortCalculationApi]
+
+export const InlineCohortCalculationApi = {
+ Off: 'off',
+ Auto: 'auto',
+ Always: 'always',
+} as const
+
+export type MaterializationModeApi = (typeof MaterializationModeApi)[keyof typeof MaterializationModeApi]
+
+export const MaterializationModeApi = {
+ Auto: 'auto',
+ LegacyNullAsString: 'legacy_null_as_string',
+ LegacyNullAsNull: 'legacy_null_as_null',
+ Disabled: 'disabled',
+} as const
+
+export type MaterializedColumnsOptimizationModeApi =
+ (typeof MaterializedColumnsOptimizationModeApi)[keyof typeof MaterializedColumnsOptimizationModeApi]
+
+export const MaterializedColumnsOptimizationModeApi = {
+ Disabled: 'disabled',
+ Optimized: 'optimized',
+} as const
+
+export type ParserModeApi = (typeof ParserModeApi)[keyof typeof ParserModeApi]
+
+export const ParserModeApi = {
+ CppOnly: 'cpp_only',
+ CppWithRustShadow: 'cpp_with_rust_shadow',
+ CppWithRustPyShadow: 'cpp_with_rust_py_shadow',
+ RustWithCppShadow: 'rust_with_cpp_shadow',
+ RustOnly: 'rust_only',
+ RustPyOnly: 'rust_py_only',
+ RustPyWithCppShadow: 'rust_py_with_cpp_shadow',
+} as const
+
+export type PersonsArgMaxVersionApi = (typeof PersonsArgMaxVersionApi)[keyof typeof PersonsArgMaxVersionApi]
+
+export const PersonsArgMaxVersionApi = {
+ Auto: 'auto',
+ V1: 'v1',
+ V2: 'v2',
+} as const
+
+export type PersonsJoinModeApi = (typeof PersonsJoinModeApi)[keyof typeof PersonsJoinModeApi]
+
+export const PersonsJoinModeApi = {
+ Inner: 'inner',
+ Left: 'left',
+} as const
+
+export type PersonsOnEventsModeApi = (typeof PersonsOnEventsModeApi)[keyof typeof PersonsOnEventsModeApi]
+
+export const PersonsOnEventsModeApi = {
+ Disabled: 'disabled',
+ PersonIdNoOverridePropertiesOnEvents: 'person_id_no_override_properties_on_events',
+ PersonIdOverridePropertiesOnEvents: 'person_id_override_properties_on_events',
+ PersonIdOverridePropertiesJoined: 'person_id_override_properties_joined',
+} as const
+
+export type PropertyGroupsModeApi = (typeof PropertyGroupsModeApi)[keyof typeof PropertyGroupsModeApi]
+
+export const PropertyGroupsModeApi = {
+ Enabled: 'enabled',
+ Disabled: 'disabled',
+ Optimized: 'optimized',
+} as const
+
+export type SessionTableVersionApi = (typeof SessionTableVersionApi)[keyof typeof SessionTableVersionApi]
+
+export const SessionTableVersionApi = {
+ Auto: 'auto',
+ V1: 'v1',
+ V2: 'v2',
+ V3: 'v3',
+} as const
+
+export type SessionsV2JoinModeApi = (typeof SessionsV2JoinModeApi)[keyof typeof SessionsV2JoinModeApi]
+
+export const SessionsV2JoinModeApi = {
+ String: 'string',
+ Uuid: 'uuid',
+} as const
+
+export interface HogQLQueryModifiersApi {
+ bounceRateDurationSeconds?: number | null
+ bounceRatePageViewMode?: BounceRatePageViewModeApi | null
+ convertToProjectTimezone?: boolean | null
+ /** 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
+ customBotDefinitions?: CustomBotRuleApi[] | null
+ customChannelTypeRules?: CustomChannelRuleApi[] | null
+ dataWarehouseEventsModifiers?: DataWarehouseEventsModifierApi[] | null
+ debug?: boolean | null
+ /** If these are provided, the query will fail if these skip indexes are not used */
+ forceClickhouseDataSkippingIndexes?: string[] | null
+ formatCsvAllowDoubleQuotes?: boolean | null
+ inCohortVia?: InCohortViaApi | null
+ inlineCohortCalculation?: InlineCohortCalculationApi | null
+ materializationMode?: MaterializationModeApi | null
+ materializedColumnsOptimizationMode?: MaterializedColumnsOptimizationModeApi | null
+ /** Merge sibling aggregating LEFT JOINs over federated Postgres tables into one UNION ALL join, so their scans overlap */
+ mergeFederatedAggregateJoins?: boolean | null
+ /** 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 | null
+ optimizeJoinedFilters?: boolean | null
+ optimizeProjections?: boolean | null
+ /** 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?: ParserModeApi | null
+ /** 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 | null
+ personsArgMaxVersion?: PersonsArgMaxVersionApi | null
+ personsJoinMode?: PersonsJoinModeApi | null
+ personsOnEventsMode?: PersonsOnEventsModeApi | null
+ propertyGroupsMode?: PropertyGroupsModeApi | null
+ pushDownPredicates?: boolean | null
+ s3TableUseInvalidColumns?: boolean | null
+ /** 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 | null
+ /** 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 | null
+ sessionTableVersion?: SessionTableVersionApi | null
+ /** 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?: number | null
+ sessionsV2JoinMode?: SessionsV2JoinModeApi | null
+ timings?: boolean | null
+ /** Remove provably redundant casts and nullability wrappers (e.g. `toString(String)`, `assumeNotNull(non_nullable)`, dead `ifNull` fallbacks) using inferred expression types */
+ typeAwareCastSimplification?: boolean | null
+ useMaterializedViews?: boolean | null
+ /** Read this query from the native events cluster and native JSON events table (`true`), or keep its existing connection (`false` or unset). This is an internal rollout switch for eligible projects. PostHog staff manage eligibility through instance settings. Each query must opt in; project defaults cannot enable it. Only synchronous HogQLQuery SQL comparisons are supported. */
+ useNewEventsCluster?: boolean | null
+ /** Read events from the native JSON events table (`true`) or the legacy events table (`false`). When unset, the project's stored value applies, then the `CLICKHOUSE_HOGQL_USE_NEW_EVENTS_SCHEMA` instance settings. This is an internal rollout switch. PostHog staff set the project value in Django admin and the project settings API ignores it. */
+ useNewEventsSchema?: boolean | null
+ usePreaggregatedIntermediateResults?: boolean | null
+ /** Try to automatically convert HogQL queries to use preaggregated tables at the AST level * */
+ usePreaggregatedTableTransforms?: boolean | null
+ useWebAnalyticsPreAggregatedTables?: boolean | null
+ /** 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 | null
+}
+
+export interface PropertyGroupFilterValueApi {
+ type: FilterLogicalOperatorApi
+ values: (
+ | PropertyGroupFilterValueApi
+ | EventPropertyFilterApi
+ | PersonPropertyFilterApi
+ | PersonMetadataPropertyFilterApi
+ | ElementPropertyFilterApi
+ | EventMetadataPropertyFilterApi
+ | SessionPropertyFilterApi
+ | CohortPropertyFilterApi
+ | RecordingPropertyFilterApi
+ | LogEntryPropertyFilterApi
+ | GroupPropertyFilterApi
+ | FeaturePropertyFilterApi
+ | FlagPropertyFilterApi
+ | HogQLPropertyFilterApi
+ | EmptyPropertyFilterApi
+ | DataWarehousePropertyFilterApi
+ | DataWarehousePersonPropertyFilterApi
+ | ErrorTrackingIssueFilterApi
+ | LogPropertyFilterApi
+ | MetricPropertyFilterApi
+ | SpanPropertyFilterApi
+ | RevenueAnalyticsPropertyFilterApi
+ | AccountCustomPropertyFilterApi
+ | WorkflowVariablePropertyFilterApi
+ | BehavioralPropertyFilterApi
+ )[]
+}
+
+export interface PropertyGroupFilterApi {
+ type: FilterLogicalOperatorApi
+ values: PropertyGroupFilterValueApi[]
+}
+
+export interface BoxPlotDatumApi {
+ day: string
+ label: string
+ max: number
+ mean: number
+ median: number
+ min: number
+ p25: number
+ p75: number
+ series_index?: number | null
+ series_label?: string | null
+}
+
+export interface ClickhouseQueryProgressApi {
+ active_cpu_time: number
+ bytes_read: number
+ estimated_rows_total: number
+ rows_read: number
+ time_elapsed: number
+}
+
+export type QueryScanFixLocationApi = (typeof QueryScanFixLocationApi)[keyof typeof QueryScanFixLocationApi]
+
+export const QueryScanFixLocationApi = {
+ Query: 'query',
+ Subquery: 'subquery',
+ View: 'view',
+ InsightDateRange: 'insight_date_range',
+ DashboardDateFilter: 'dashboard_date_filter',
+} as const
+
+export type QueryScanFindingKindApi = (typeof QueryScanFindingKindApi)[keyof typeof QueryScanFindingKindApi]
+
+export const QueryScanFindingKindApi = {
+ NoEventFilter: 'no_event_filter',
+ NoStartDate: 'no_start_date',
+ PersonsJoin: 'persons_join',
+} as const
+
+export interface QueryScanWarningApi {
+ /** 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
+ /** True when the query reads this much on purpose, so reading less would change the answer. Absent means no. */
+ by_design?: boolean | null
+ /** 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 | null
+ /** The one fact the finding rests on. */
+ evidence?: string | null
+ /** What "Fix with AI" and the assistant are told to do. */
+ fix: string
+ /** Where the change goes. Absent means the query itself. */
+ fix_location?: QueryScanFixLocationApi | null
+ kind: QueryScanFindingKindApi
+ /** Shown to the person: what happened and what to do. */
+ message: string
+}
+
+export interface QueryScanAnalysisApi {
+ /** The message the Fix with AI button sends to the assistant. Absent when no finding can be fixed in the query. */
+ assistant_prompt?: string | null
+ /** Every finding, fixable or not. Empty when the analysis found none. */
+ findings: QueryScanWarningApi[]
+ /** How much of all the project's events the query read, 0 to 1. */
+ project_share?: number | null
+ /** How much of the project's events in the query's date range the query read, 0 to 1. */
+ range_share?: number | null
+}
+
+export interface QueryScanSummaryApi {
+ /** The stored analysis, put on the response when it is served. Absent while the analysis runs, and when none was requested. */
+ analysis?: QueryScanAnalysisApi | null
+ /** 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 | null
+ /** ClickHouse time for the last fresh run, summed over its ClickHouse queries. */
+ duration_ms: number
+ /** True when ClickHouse stopped the run instead of finishing it. */
+ killed?: boolean | null
+ /** Rows ClickHouse read for the last fresh run, all tables included. */
+ rows_read: number
+}
+
+export interface QueryStatusApi {
+ budget_remaining_bytes?: number | null
+ bytes_read?: number | null
+ /** Cache key of the run that failed, so clients can ask for its query scan. */
+ cache_key?: string | null
+ /** 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. */
+ complete?: boolean | null
+ dashboard_id?: number | null
+ /** When did the query execution task finish (whether successfully or not). */
+ end_time?: string | null
+ /** If the query failed, this will be set to true. More information can be found in the error_message field. */
+ error?: boolean | null
+ /** Stable machine-readable code for the error, when known: the DRF exception code, or the ClickHouse error name. */
+ error_code?: string | null
+ error_message?: string | null
+ expiration_time?: string | null
+ id: string
+ insight_id?: number | null
+ labels?: string[] | null
+ /** When was the query execution task picked up by a worker. */
+ pickup_time?: string | null
+ /** ONLY async queries use QueryStatus. */
+ query_async?: true
+ query_progress?: ClickhouseQueryProgressApi | null
+ query_scan?: QueryScanSummaryApi | null
+ results?: unknown
+ /** When was query execution task enqueued. */
+ start_time?: string | null
+ task_id?: string | null
+ team_id: number
+}
+
+export interface ResolvedDateRangeResponseApi {
+ date_from: string
+ date_to: string
+}
+
+export interface QueryTimingApi {
+ /** Key. Shortened to 'k' to save on data. */
+ k: string
+ /** Time in seconds. Shortened to 't' to save on data. */
+ t: number
+}
+
+export interface DataWarehouseSourceUsageApi {
+ /** ExternalDataSource id */
+ id: string
+ /** Connector type of the source (e.g. Stripe, Postgres), if known */
+ source_type?: string | null
+ /** Warehouse table name that was referenced */
+ table_name: string
+}
+
+export interface DataWarehouseSyncWarningApi {
+ /** 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 | null
+ /** Human-readable warning shown to the user */
+ message: string
+ /** Name of the ExternalDataSchema responsible for syncing the table */
+ schema_name: string
+ /** ID of the ExternalDataSource, used to link to its management page. Null for self-managed tables. */
+ source_id?: string | null
+ /** Source type, e.g. "Stripe", "Hubspot" */
+ source_type: string
+ /** Sync status that triggered the warning, e.g. "Failed", "Paused", "BillingLimitReached" */
+ status: string
+ /** Name of the warehouse table the warning refers to */
+ table_name: string
+ /** Tells warning kinds apart in the shared `warnings` list */
+ type?: 'warehouse_sync'
+}
+
+export interface AccessControlFilterWarningApi {
+ /** Human-readable warning shown to the user */
+ message: string
+ /** Resource types the user has access restrictions on, referenced by the query, e.g. ["insight", "dashboard"] */
+ resources: string[]
+ /** Tells warning kinds apart in the shared `warnings` list */
+ type?: 'access_control'
+}
+
+export type TrendsQueryResponseApiResultsItem = { [key: string]: unknown }
+
+export interface TrendsQueryResponseApi {
+ boxplot_data?: BoxPlotDatumApi[] | null
+ /** Query error. Returned only if 'explain' or `modifiers.debug` is true. Throws an error otherwise. */
+ error?: string | null
+ /** Wether more breakdown values are available. */
+ hasMore?: boolean | null
+ /** Generated HogQL query. */
+ hogql?: string | null
+ /** Modifiers used when performing the query */
+ modifiers?: HogQLQueryModifiersApi | null
+ /** Query status indicates whether next to the provided data, a query is still running. */
+ query_status?: QueryStatusApi | null
+ /** The resolved previous/comparison period date range, when comparing against another period */
+ resolved_compare_date_range?: ResolvedDateRangeResponseApi | null
+ /** The date range used for the query */
+ resolved_date_range?: ResolvedDateRangeResponseApi | null
+ results: TrendsQueryResponseApiResultsItem[]
+ /** Measured timings for different parts of the query generation process */
+ timings?: QueryTimingApi[] | null
+ /** Connector-synced data warehouse sources referenced by this query, if any. */
+ used_data_warehouse_sources?: DataWarehouseSourceUsageApi[] | null
+ /** Warnings about data warehouse sources referenced by the query whose latest sync failed, is paused, hit a billing limit, or is otherwise stale. Results may not reflect current source data. Accumulated across every HogQL execution that contributes to this response — so insights backed by warehouse tables (Trends, Funnels, etc.) receive the same warnings as raw HogQL queries. Also carries access control warnings when a system-table query filters out objects the user can't access. */
+ warnings?: (DataWarehouseSyncWarningApi | AccessControlFilterWarningApi)[] | null
}
export type EventsNodeApiResponse = { [key: string]: unknown } | null
@@ -1586,98 +1691,6 @@ export interface ActionsNodeApi {
version?: number | null
}
-export type DataWarehouseNodeApiResponse = { [key: string]: unknown } | null
-
-export interface DataWarehouseNodeApi {
- custom_name?: string | null
- distinct_id_field: string
- dw_source_type?: string | null
- /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
- fixedProperties?:
- | (
- | EventPropertyFilterApi
- | PersonPropertyFilterApi
- | PersonMetadataPropertyFilterApi
- | ElementPropertyFilterApi
- | EventMetadataPropertyFilterApi
- | SessionPropertyFilterApi
- | CohortPropertyFilterApi
- | RecordingPropertyFilterApi
- | LogEntryPropertyFilterApi
- | GroupPropertyFilterApi
- | FeaturePropertyFilterApi
- | FlagPropertyFilterApi
- | HogQLPropertyFilterApi
- | EmptyPropertyFilterApi
- | DataWarehousePropertyFilterApi
- | DataWarehousePersonPropertyFilterApi
- | ErrorTrackingIssueFilterApi
- | LogPropertyFilterApi
- | MetricPropertyFilterApi
- | SpanPropertyFilterApi
- | RevenueAnalyticsPropertyFilterApi
- | AccountCustomPropertyFilterApi
- | WorkflowVariablePropertyFilterApi
- | BehavioralPropertyFilterApi
- )[]
- | null
- id: string
- id_field: string
- kind?: 'DataWarehouseNode'
- math?:
- | BaseMathTypeApi
- | FunnelMathTypeApi
- | PropertyMathTypeApi
- | CountPerActorMathTypeApi
- | GroupMathTypeApi
- | ExperimentMetricMathTypeApi
- | CalendarHeatmapMathTypeApi
- | 'hogql'
- | null
- math_group_type_index?: MathGroupTypeIndexApi | null
- math_hogql?: string | null
- math_multiplier?: number | null
- math_property?: string | null
- math_property_revenue_currency?: RevenueCurrencyPropertyConfigApi | null
- math_property_type?: string | null
- name?: string | null
- optionalInFunnel?: boolean | null
- /** Properties configurable in the interface */
- properties?:
- | (
- | EventPropertyFilterApi
- | PersonPropertyFilterApi
- | PersonMetadataPropertyFilterApi
- | ElementPropertyFilterApi
- | EventMetadataPropertyFilterApi
- | SessionPropertyFilterApi
- | CohortPropertyFilterApi
- | RecordingPropertyFilterApi
- | LogEntryPropertyFilterApi
- | GroupPropertyFilterApi
- | FeaturePropertyFilterApi
- | FlagPropertyFilterApi
- | HogQLPropertyFilterApi
- | EmptyPropertyFilterApi
- | DataWarehousePropertyFilterApi
- | DataWarehousePersonPropertyFilterApi
- | ErrorTrackingIssueFilterApi
- | LogPropertyFilterApi
- | MetricPropertyFilterApi
- | SpanPropertyFilterApi
- | RevenueAnalyticsPropertyFilterApi
- | AccountCustomPropertyFilterApi
- | WorkflowVariablePropertyFilterApi
- | BehavioralPropertyFilterApi
- )[]
- | null
- response?: DataWarehouseNodeApiResponse
- table_name: string
- timestamp_field: string
- /** version of the node, used for schema migrations */
- version?: number | null
-}
-
export type GroupNodeApiResponse = { [key: string]: unknown } | null
export interface GroupNodeApi {
@@ -2078,6 +2091,8 @@ export interface TrendsQueryApi {
/** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */
interval?: IntervalTypeApi | null
kind?: 'TrendsQuery'
+ /** Live series for a Marketing cost trend when materialization coverage is incomplete. */
+ marketingAnalyticsCostFallback?: MarketingAnalyticsCostFallbackApi | null
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiersApi | null
/** Property filters for all series */
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0b07d7c7b16b..f463153b3e20 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -5270,6 +5270,48 @@ export namespace Schemas {
explicitDate?: boolean | null;
}
+ export type DataWarehouseNodeResponse = { [key: string]: unknown } | null;
+
+ export interface DataWarehouseNode {
+ custom_name?: string | null;
+ distinct_id_field: string;
+ dw_source_type?: string | null;
+ /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
+ fixedProperties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;
+ id: string;
+ id_field: string;
+ kind?: 'DataWarehouseNode';
+ math?: BaseMathType | FunnelMathType | PropertyMathType | CountPerActorMathType | GroupMathType | ExperimentMetricMathType | CalendarHeatmapMathType | 'hogql' | null;
+ math_group_type_index?: MathGroupTypeIndex | null;
+ math_hogql?: string | null;
+ math_multiplier?: number | null;
+ math_property?: string | null;
+ math_property_revenue_currency?: RevenueCurrencyPropertyConfig | null;
+ math_property_type?: string | null;
+ name?: string | null;
+ optionalInFunnel?: boolean | null;
+ /** Properties configurable in the interface */
+ properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;
+ response?: DataWarehouseNodeResponse;
+ table_name: string;
+ timestamp_field: string;
+ /** version of the node, used for schema migrations */
+ version?: number | null;
+ }
+
+ export interface MarketingAnalyticsCostFallback {
+ /**
+ * @minItems 1
+ * @maxItems 200
+ */
+ series: DataWarehouseNode[];
+ /**
+ * @minItems 1
+ * @maxItems 200
+ */
+ sourceIds: string[];
+ }
+
export interface PropertyGroupFilter {
type: FilterLogicalOperator;
values: PropertyGroupFilterValue[];
@@ -5343,35 +5385,6 @@ export namespace Schemas {
version?: number | null;
}
- export type DataWarehouseNodeResponse = { [key: string]: unknown } | null;
-
- export interface DataWarehouseNode {
- custom_name?: string | null;
- distinct_id_field: string;
- dw_source_type?: string | null;
- /** Fixed properties in the query, can't be edited in the interface (e.g. scoping down by person) */
- fixedProperties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;
- id: string;
- id_field: string;
- kind?: 'DataWarehouseNode';
- math?: BaseMathType | FunnelMathType | PropertyMathType | CountPerActorMathType | GroupMathType | ExperimentMetricMathType | CalendarHeatmapMathType | 'hogql' | null;
- math_group_type_index?: MathGroupTypeIndex | null;
- math_hogql?: string | null;
- math_multiplier?: number | null;
- math_property?: string | null;
- math_property_revenue_currency?: RevenueCurrencyPropertyConfig | null;
- math_property_type?: string | null;
- name?: string | null;
- optionalInFunnel?: boolean | null;
- /** Properties configurable in the interface */
- properties?: (EventPropertyFilter | PersonPropertyFilter | PersonMetadataPropertyFilter | ElementPropertyFilter | EventMetadataPropertyFilter | SessionPropertyFilter | CohortPropertyFilter | RecordingPropertyFilter | LogEntryPropertyFilter | GroupPropertyFilter | FeaturePropertyFilter | FlagPropertyFilter | HogQLPropertyFilter | EmptyPropertyFilter | DataWarehousePropertyFilter | DataWarehousePersonPropertyFilter | ErrorTrackingIssueFilter | LogPropertyFilter | MetricPropertyFilter | SpanPropertyFilter | RevenueAnalyticsPropertyFilter | AccountCustomPropertyFilter | WorkflowVariablePropertyFilter | BehavioralPropertyFilter)[] | null;
- response?: DataWarehouseNodeResponse;
- table_name: string;
- timestamp_field: string;
- /** version of the node, used for schema migrations */
- version?: number | null;
- }
-
export type GroupNodeResponse = { [key: string]: unknown } | null;
export interface GroupNode {
@@ -5708,6 +5721,8 @@ export namespace Schemas {
/** Granularity of the response. Can be one of `hour`, `day`, `week` or `month` */
interval?: IntervalType | null;
kind?: 'TrendsQuery';
+ /** Live series for a Marketing cost trend when materialization coverage is incomplete. */
+ marketingAnalyticsCostFallback?: MarketingAnalyticsCostFallback | null;
/** Modifiers used when performing the query */
modifiers?: HogQLQueryModifiers | null;
/** Property filters for all series */
diff --git a/tach.toml b/tach.toml
index c6e17f82e885..cea82a5b99ff 100644
--- a/tach.toml
+++ b/tach.toml
@@ -779,6 +779,7 @@ layer = "modules"
path = "products.product_analytics"
depends_on = [
"products.cohorts",
+ "products.marketing_analytics",
"ee",
"posthog",
"products.actions",