Skip to content

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

feat(warehouse): run managed sql editor connections on trino (#113435)

Eric Duongac84ad0ac029
diff --git a/docs/internal/managed-warehouse-monitoring.md b/docs/internal/managed-warehouse-monitoring.md
index 1c320255e4d9..904dd570dbb4 100644
--- a/docs/internal/managed-warehouse-monitoring.md
+++ b/docs/internal/managed-warehouse-monitoring.md
@@ -1,7 +1,7 @@
# Managed warehouse monitoring
The **Monitoring** tab in Data ops gives every project in an organization the same operational view of its managed warehouse.
-It has two variants. Organizations on `data-warehouse-scene` see the DuckDB worker variant described first. Organizations on `data-warehouse-scene-trino` see the Trino variant described under "Trino variant". The Trino flag wins when both are on.
+It has two variants. Organizations on `data-warehouse-scene` see the DuckDB worker variant described first. Organizations on `managed-warehouse-trino-query` see the Trino variant described under "Trino variant". The Trino flag wins when both are on.
## Request path and tenant boundary
@@ -64,7 +64,7 @@ If a refresh fails, the UI preserves the last successful data and shows how to r
## Trino variant
-Organizations on `data-warehouse-scene-trino` query through Trino, so the tab shows query activity instead of workers.
+Organizations on `managed-warehouse-trino-query` query through Trino, so the tab shows query activity instead of workers.
The browser calls:
@@ -87,7 +87,7 @@ The query counts are best-effort on a very busy warehouse and are not billing to
Changing the Monitoring time range clears the previous range while the new metrics load.
A failed refresh within the same range keeps the last successful data and shows a warning.
-MCP clients get the same data through `managed-warehouse-trino-monitoring-get` and `managed-warehouse-trino-metric-history-get`, available when `data-warehouse-scene-trino` is enabled.
+MCP clients get the same data through `managed-warehouse-trino-monitoring-get` and `managed-warehouse-trino-metric-history-get`, available when `managed-warehouse-trino-query` is enabled.
An organization with both flags still sees the two DuckDB tools listed. Those calls return the 404 that names the Trino endpoints.
## Usage scope
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.md
index c1f36bcfc518..e6647e8f5ca0 100644
--- a/docs/internal/managed-warehouse-sql-editor.md
+++ b/docs/internal/managed-warehouse-sql-editor.md
@@ -1,10 +1,14 @@
# Managed warehouse connections in the SQL editor
-The `data-warehouse-scene` feature flag gates user access to managed warehouse provisioning. It does not select a SQL-editor authentication mode. Once a provision, onboarding, or generation-fenced recovery lifecycle action runs, a genuinely missing managed source is created unconditionally as a secretless `duckgres_service` source and presented as `PostHog (Managed warehouse)`.
+The `data-warehouse-scene` and `managed-warehouse-trino-query` organization flags gate managed warehouse provisioning. Once a provision, onboarding, or generation-fenced recovery lifecycle action runs, a genuinely missing managed source is created unconditionally as a secretless `duckgres_service` source and presented as `PostHog (Managed warehouse)`.
-A `duckgres_service` row persists no host, username, password, or credential ID. It persists only the non-secret lifecycle generation that created it. Dynamic raw queries use the native Duckgres pgwire adapter. At physical connection acquisition, PostHog mints a short-lived organization-root-shaped service credential for a principal containing the project ID and stable PostHog user ID. Email addresses are never used. Schema discovery uses a distinct project-scoped system principal, so background work never impersonates an interactive user. The connection must include `sslmode=require`, and there is no stored-root fallback.
+The secretless built-in connection uses Trino when `managed-warehouse-trino-query` is enabled for the organization; otherwise it uses Duckgres. This applies to existing provisioned connections as well as new ones. The persisted source ID and its Postgres source type stay stable, while the connection option reports the selected engine. Ordinary external connections and existing stored project-reader or organization-login sources retain their configured engine and grants.
-Existing live sources keep their stored authentication mode unless an actual warehouse lifecycle action requires replacement. A live dynamic source remains dynamic, a configured `project_reader` retains its stored project credential, and a static organization-login source retains its stored root credential and external-source access controls. The database chooser prefers a dynamic source, then a ready `project_reader`; when neither exists, it exposes the canonical valid legacy source as an ordinary external connection. Merely changing a product feature flag does not create, convert, or hide a source.
+Trino raw SQL and connection-scoped HogQL both use short-lived hosted service credentials, bounded execution, and asynchronous cancellation. Schema discovery also uses Trino with a separate project-scoped system principal and updates existing table projections in place. Its catalog queries share a 60-second deadline. Flag evaluation runs outside source and lifecycle locking transactions. A Trino failure produces an error without falling back to Duckgres. Query caches are partitioned by the selected engine. Turning the flag off restores Duckgres routing immediately; schema reconciliation refreshes the table projections on its existing schedule, so compiled queries can require a catalog refresh after either switch.
+
+A `duckgres_service` row persists no host, username, password, or credential ID. It persists only the non-secret lifecycle generation that created it. In the DuckDB variant, dynamic raw queries use the native Duckgres pgwire adapter. At physical connection acquisition, PostHog mints a short-lived organization-root-shaped service credential for a principal containing the project ID and stable PostHog user ID. Email addresses are never used. Schema discovery uses a distinct project-scoped system principal, so background work never impersonates an interactive user. The connection must include `sslmode=require`, and there is no stored-root fallback.
+
+Existing live sources keep their stored authentication mode unless an actual warehouse lifecycle action requires replacement. A live dynamic source remains dynamic, a configured `project_reader` retains its stored project credential for Duckgres, and a static organization-login source retains its stored root credential and external-source access controls. The database chooser prefers a dynamic source, then a ready `project_reader`; when neither exists, it exposes the canonical valid legacy source as an ordinary external connection. Merely changing a product feature flag does not create, convert, or hide a source.
PostHog application-encrypts credentials in shared Redis. The cache key is a hash of the organization, principal, and lifecycle generation, and the entry expires one minute before the credential. A per-key Redis lock lets query-django and Celery workers share one mint without making unrelated principals wait. Refresh always mints an independent credential and never rotates a cached credential ID. A rapid deprovision and reprovision therefore cannot reuse a credential from the old generation.
@@ -16,7 +20,7 @@ An organization-scoped generation fence orders source work around remote provisi
Reconciliation treats dynamic, project-reader, and static sources as independent catalogs and introspects each with its own credential mode. A failure in one source does not block the others. Dynamic discovery requires TLS and uses its system principal. Reconciliation runs when warehouse status is read, coalesced to once a minute, and in a twice-hourly periodic sweep. For an active generation with a missing source, reconciliation creates dynamic authentication without reading `DuckgresServer`.
-The native adapter sends one PostgreSQL-compatible statement unchanged, supports asynchronous cancellation, applies the existing connection deadline and statement timeout, and rejects results above 50,000 rows. Non-raw project-reader and static-source queries continue through their existing PostgreSQL/HogQL path; the PostgreSQL adapter is unchanged.
+The Duckgres native adapter sends one PostgreSQL-compatible statement unchanged, supports asynchronous cancellation, applies the existing connection deadline and statement timeout, and rejects results above 50,000 rows. Non-raw project-reader and static-source queries continue through their existing PostgreSQL/HogQL path; the PostgreSQL adapter is unchanged.
Deprovision captures the active generation before the control-plane request and deactivates only that generation. A direct 404 is authoritative absence. If the request times out or returns 409, PostHog reads warehouse status. It converges local cleanup only when the warehouse is `deleting`, `deleted`, or absent. A ready warehouse remains active.
@@ -42,3 +46,11 @@ If source setup fails after successful provision or onboarding, the versioned re
If deprovision reports that the control plane accepted deletion but local SQL connection state could not be updated, retry deprovision. PostHog checks authoritative status before changing local state. If source cleanup fails after local deactivation, the versioned cleanup task retries with the exact inactive generation.
If Redis is unavailable, SQL editor queries and managed warehouse schema discovery continue by minting one credential per request. Restore Redis to resume cross-worker reuse. There is no process-local or Postgres credential cache to clear during recovery. Use `posthog_managed_warehouse_service_credential_cache_events_total` to compare cache hits, misses, invalid payloads, Redis errors, lock timeouts, store failures, and direct fallbacks. Its `outcome` label has no tenant or credential identifiers.
+
+## Hosted Trino opt-in
+
+The same `managed-warehouse-trino-query` organization feature flag adds **PostHog (Trino)** directly below **PostHog (ClickHouse)** in the SQL editor connection selector. The default PostHog target remains unchanged. The backend checks the same flag before execution and cache reads; selecting the target in a URL does not grant access.
+
+Hosted Trino runs the current HogQL query through the Django-backed Trino compiler, preserving project scoping and the requesting user's table permissions. It resolves logical table names to the project's managed warehouse tables without requiring a stored model translation. Data must already exist in the Trino target; unsupported expressions and missing tables produce query errors. The target accepts HogQL only and cannot be combined with an external connection or raw SQL mode.
+
+Each connection uses a short-lived hosted Trino service credential with a project/user principal. It does not read external-source passwords. Interactive queries retain a deadline and bounded result size, and asynchronous cancellation uses the existing direct-query cancellation token. Queries without an explicit limit use the existing SQL editor pagination and report whether more rows exist. SQL alerts use the same completeness probe as the default target. HTTP polling and prepared statements share the query deadline, and cursor cleanup makes one bounded cancellation attempt. Choosing another target preserves the query text, filters, and variables; the selection is saved with the query and editor URL.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 2ea91c9fdaa4..0b324d2854f9 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10082,6 +10082,10 @@ snapshots:
hash: v1.k794b7964.57136a6dbeab9ac511a2a5e0c7401b23a4cb0ac00d82a2be177b84f74a60ebb0.QicPm3hXLpA9re3ShhfrqX6bKcWmuAvRBCtbRpHrSFQ
scenes-app-data-warehouse-sql-editor--edited-view--light:
hash: v1.k794b7964.1bada9403e11b62a50423adde53ce13fcd10a5bd6c33a210f5dd58a10a956cf8.2N9MES9JfDzATg0m-6cJnj7FWTzNt6ZlLxGqqoAI54A
+ scenes-app-data-warehouse-sql-editor--hosted-trino--dark:
+ hash: v1.k794b7964.f9994745acd14c1637efcaaba80d853b1c407ab0b9f67f94dae27b0a754e77f5.jeo7IYSV-jC6k5vgl8opPAG8O1Y2Cbw37y2QrEnt6F0
+ scenes-app-data-warehouse-sql-editor--hosted-trino--light:
+ hash: v1.k794b7964.1a069b0d0e4660900fa7731adde3ee7738bafa27fc0030ec10ce49d50997beba.KMUhJe60oAoeJ8wuGV4biL24SWSc2byQh15_c7ydid4
scenes-app-data-warehouse-sql-editor--lazy-schema--dark:
hash: v1.k794b7964.377c5cbd365fb00f334e2ad85570c373fc29c7aaddb4fc942b53081f882a02d7.EG98MhlU_8eOPCG85eUQL3egUoLrtejgaMCkD8v4BFo
scenes-app-data-warehouse-sql-editor--lazy-schema--light:
diff --git a/frontend/src/lib/components/Search/searchListsLogic.test.ts b/frontend/src/lib/components/Search/searchListsLogic.test.ts
index 8d59f28c66f2..cc74393d982e 100644
--- a/frontend/src/lib/components/Search/searchListsLogic.test.ts
+++ b/frontend/src/lib/components/Search/searchListsLogic.test.ts
@@ -27,7 +27,7 @@ describe('searchListsLogic', () => {
])('shows Data ops with DuckDB=%s and Trino=%s', (duckdb, trino, visible) => {
featureFlagLogic.actions.setFeatureFlags([], {
[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: duckdb,
- [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]: trino,
+ [FEATURE_FLAGS.MANAGED_TRINO_QUERY]: trino,
})
expect(logic.values.productsItems.some((item) => item.id === 'product-Data warehouse')).toBe(visible)
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 1a1db051aeab..c71e23cbedd9 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -324,7 +324,6 @@ export const FEATURE_FLAGS = {
DATA_WAREHOUSE_CUSTOM_SOURCE_AI_BUILDER: 'dwh-custom-source-ai-builder', // owner: #team-warehouse-sources
DATA_WAREHOUSE_CUSTOM_SOURCE_OAUTH2: 'dwh-custom-source-oauth2', // owner: #team-warehouse-sources
DATA_WAREHOUSE_SCENE: 'data-warehouse-scene', // owner: #team-data-modeling
- DATA_WAREHOUSE_SCENE_TRINO: 'data-warehouse-scene-trino', // owner: #team-data-modeling
DISCUSSIONS_SLACK_SYNC: 'discussions-slack-sync', // owner: #team-platform-features
DROP_PERSON_LIST_ORDER_BY: 'drop-person-list-order-by', // owner: @arthurdedeus #team-customer-analytics
DWH_POSTGRES_CDC: 'dwh-postgres-cdc', // owner: #team-warehouse-sources
@@ -416,6 +415,7 @@ export const FEATURE_FLAGS = {
LOGS_TRANSFORMATIONS: 'logs-transformations', // owner: #team-logs
MANAGED_MIGRATIONS_IAM_ROLE_AUTH: 'managed-migrations-iam-role-auth', // owner: #team-ingestion, gates IAM role auth for S3 batch imports
MANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrations
+ MANAGED_TRINO_QUERY: 'managed-warehouse-trino-query', // owner: #team-data-modeling
MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics
MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_AMAZON_ADS: 'marketing-analytics-amazon-ads', // owner: @jabahamondes #team-web-analytics
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index e1ff54b0678d..68ba64bc4ac9 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -2559,7 +2559,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [
searchKeywords: ['managed warehouse', 'data lake', 'lakehouse'],
searchTabs: [{ name: 'Monitoring', href: urls.dataOps('monitoring') }],
flag: FEATURE_FLAGS.DATA_WAREHOUSE_SCENE,
- alternativeFlags: [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO],
+ alternativeFlags: [FEATURE_FLAGS.MANAGED_TRINO_QUERY],
iconType: 'data_warehouse',
iconColor: ['var(--color-product-data-warehouse-light)'],
sceneKey: 'DataOps',
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 11ae76534bce..9a323bf7b68b 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -30094,6 +30094,11 @@
"description": "Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled.",
"type": "string"
},
+ "executionTarget": {
+ "description": "Compile and run this query against the hosted Trino target.",
+ "enum": ["default", "managed_trino"],
+ "type": "string"
+ },
"explain": {
"deprecated": "use modifiers.debug instead",
"type": "boolean"
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 4d341b76cc8d..de335d0a4c97 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -724,6 +724,8 @@ export interface HogQLQuery extends DataNode<HogQLQueryResponse> {
query: string
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string
+ /** Compile and run this query against the hosted Trino target. */
+ executionTarget?: 'default' | 'managed_trino'
/** Run the selected connection query directly without translating it through HogQL first */
sendRawQuery?: boolean
/** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */
diff --git a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx
index 31fb76b86126..78eaa3cd7907 100644
--- a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx
@@ -3,8 +3,10 @@ import { router } from 'kea-router'
import { IconGear } from '@posthog/icons'
+import { FEATURE_FLAGS } from 'lib/constants'
import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { LemonSelect, LemonSelectOption } from 'lib/lemon-ui/LemonSelect'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { newInternalTab } from 'lib/utils/newInternalTab'
import { urls } from 'scenes/urls'
@@ -34,12 +36,17 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elem
const { connectionOptions, connectionOptionsLoading, connectionSelectOptions } =
useValues(connectionSelectorLogic())
const { maybeLoadConnectionOptions } = useActions(connectionSelectorLogic())
- const { setSourceQuery, syncUrlWithQuery } = useActions(logic)
+ const { setSourceQuery, syncUrlWithQuery, setExecutionTarget } = useActions(logic)
+ const { featureFlags } = useValues(featureFlagLogic)
+ const hostedTrinoEnabled = !!featureFlags[FEATURE_FLAGS.MANAGED_TRINO_QUERY]
useOnMountEffect(() => {
maybeLoadConnectionOptions()
})
- const connectionSelectorValue = getConnectionSelectorValue(connectionOptionsLoading, selectedConnectionId)
+ const connectionSelectorValue =
+ sourceQuery.source.executionTarget === 'managed_trino'
+ ? 'managed_trino'
+ : getConnectionSelectorValue(connectionOptionsLoading, selectedConnectionId)
const displayedConnectionSelectOptions = addHiddenSelectedConnectionOption(
connectionSelectOptions,
connectionOptions,
@@ -54,6 +61,7 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elem
return (
<LemonSelect
+ data-attr="sql-editor-connection-selector"
size="small"
fullWidth
// min-w-0 lets the flex item shrink past the label's min-content width, and
@@ -63,11 +71,16 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elem
truncateText={{ maxWidthClass: 'max-w-full' }}
value={connectionSelectorValue}
onChange={(nextValue) => {
+ if (nextValue === 'managed_trino') {
+ setExecutionTarget('managed_trino')
+ return
+ }
if (!nextValue || nextValue === POSTHOG_WAREHOUSE) {
setSourceQuery({
...sourceQueryWithoutLegacyConnectionId,
source: {
...sourceQuery.source,
+ executionTarget: undefined,
connectionId: undefined,
sendRawQuery: undefined,
},
@@ -93,6 +106,7 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elem
...sourceQueryWithoutLegacyConnectionId,
source: {
...sourceQuery.source,
+ executionTarget: undefined,
connectionId: nextValue,
sendRawQuery: undefined,
},
@@ -100,7 +114,26 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elem
syncUrlWithQuery()
}}
options={displayedConnectionSelectOptions.map((group) => ({
- options: group.options.map(toLemonSelectOption),
+ options: group.options.flatMap((option) => {
+ const connectionOption = toLemonSelectOption(option)
+ if (
+ option.value === POSTHOG_WAREHOUSE &&
+ (hostedTrinoEnabled || sourceQuery.source.executionTarget === 'managed_trino')
+ ) {
+ return [
+ connectionOption,
+ {
+ label: 'PostHog (Trino)',
+ value: 'managed_trino',
+ icon: connectionOption.icon,
+ disabledReason: hostedTrinoEnabled
+ ? undefined
+ : 'PostHog (Trino) queries are not enabled for this organization',
+ },
+ ]
+ }
+ return [connectionOption]
+ }),
}))}
/>
)
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index 10ab449989df..bd341d32fcae 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -203,6 +203,21 @@ export default meta
type Story = StoryObj<{}>
export const TopToolsPerServer: Story = {}
+export const HostedTrino: Story = {
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.MANAGED_TRINO_QUERY],
+ pageUrl: `${urls.sqlEditor({ query: 'SELECT event FROM events' })}#engine=managed_trino`,
+ msw: {
+ mocks: {
+ get: {
+ '/api/projects/:team_id/warehouse_expressions/': { results: [] },
+ '/api/environments/:team_id/warehouse_expressions/': { results: [] },
+ },
+ },
+ },
+ },
+}
+
export const LoadingInsight: Story = {
parameters: {
pageUrl: `${urls.sqlEditor()}?open_insight=loading1`,
@@ -218,6 +233,7 @@ export const LoadingInsight: Story = {
return [200, { results: [] }]
},
'/api/projects/:team_id/warehouse_expressions/': { results: [] },
+ '/api/environments/:team_id/warehouse_expressions/': { results: [] },
},
},
},
@@ -500,6 +516,7 @@ export const BIModeWorksheet: Story = {
mocks: {
get: {
'/api/projects/:team_id/warehouse_expressions/': { results: [] },
+ '/api/environments/:team_id/warehouse_expressions/': { results: [] },
},
post: {
// The specific path wins over the catch-all query mock on the meta
@@ -734,6 +751,7 @@ export const LazySchema: Story = {
mocks: {
get: {
'/api/projects/:team_id/warehouse_expressions/': { results: [] },
+ '/api/environments/:team_id/warehouse_expressions/': { results: [] },
'/api/projects/:team_id/warehouse_saved_queries/': {
results: [
{
@@ -950,6 +968,7 @@ const chartExperimentParameters = (approved: boolean, decisionDelay = 0, queryDe
is_ai_data_processing_approved: approved,
},
'/api/projects/:team_id/warehouse_expressions/': { results: [] },
+ '/api/environments/:team_id/warehouse_expressions/': { results: [] },
},
post: {
'/api/environments/:team_id/query/HogQLMetadata': async ({ request }: MockResolverInfo) => {
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 225f110399c7..b73c2ec7d4cc 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -1319,6 +1319,33 @@ describe('sqlEditorLogic', () => {
})
describe('open_insight URL parameter', () => {
+ it.each([
+ [undefined, 'managed_trino', 'managed_trino'],
+ ['managed_trino', 'posthog', undefined],
+ ['managed_trino', undefined, 'managed_trino'],
+ ] as const)('restores saved target %s with URL override %s', async (savedTarget, urlTarget, expectedTarget) => {
+ const savedQuery = MOCK_INSIGHT_QUERY
+ const query: DataVisualizationNode = {
+ ...savedQuery,
+ source: { ...savedQuery.source, executionTarget: savedTarget },
+ }
+ const getInsight = jest.spyOn(insightsApi, 'getByShortId').mockResolvedValueOnce({ ...MOCK_INSIGHT, query })
+ try {
+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
+ logic.mount()
+ router.actions.push(
+ urls.sqlEditor(),
+ { open_insight: MOCK_INSIGHT_SHORT_ID },
+ { q: savedQuery.source.query, ...(urlTarget ? { engine: urlTarget } : {}) }
+ )
+ await expectLogic(logic).toDispatchActions(['editInsight', 'createTab', 'updateTab'])
+ expect(logic.values.sourceQuery.source.executionTarget).toEqual(expectedTarget)
+ expect(router.values.hashParams.engine).toEqual(urlTarget ?? expectedTarget)
+ } finally {
+ getInsight.mockRestore()
+ }
+ })
+
it.each([MOCK_INSIGHT_SHORT_ID, MOCK_DATA_TABLE_INSIGHT_SHORT_ID])(
'sets the editing insight and file tree reference when opening %s',
async (shortId) => {
@@ -2643,6 +2670,39 @@ describe('sqlEditorLogic', () => {
expect(router.values.hashParams.c).toEqual('conn-123')
})
+ it('switches hosted execution without rewriting the query and persists the target in the URL', async () => {
+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
+ logic.mount()
+ router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT event FROM events', c: 'conn-123', raw: '1' })
+ await expectLogic(logic).toDispatchActions(['setSourceQuery', 'createTab', 'updateTab'])
+ const query = logic.values.queryInput
+ logic.actions.setLastRunQuery({
+ ...logic.values.sourceQuery,
+ source: { ...logic.values.sourceQuery.source, query: query ?? '' },
+ })
+ expect(logic.values.isSourceQueryLastRun).toEqual(true)
+ logic.actions.setExecutionTarget('managed_trino')
+ expect(logic.values.isSourceQueryLastRun).toEqual(false)
+ expect(logic.values.sourceQuery.source).toMatchObject({ query, executionTarget: 'managed_trino' })
+ expect(logic.values.sourceQuery.source.connectionId).toBeUndefined()
+ expect(logic.values.sourceQuery.source.sendRawQuery).toBeUndefined()
+ expect(router.values.hashParams.engine).toEqual('managed_trino')
+ expect(router.values.hashParams.c).toBeUndefined()
+ await runDebouncedAction(() => logic.actions.setQueryInput('SELECT count() FROM events'))
+ expect(router.values.hashParams.engine).toEqual('managed_trino')
+ logic.actions.setExecutionTarget(undefined)
+ expect(logic.values.sourceQuery.source.query).toEqual('SELECT count() FROM events')
+ expect(router.values.hashParams.engine).toBeUndefined()
+ })
+
+ it('restores the hosted target from the URL', async () => {
+ logic = sqlEditorLogic({ tabId: TAB_ID, monaco: createMockMonaco(), editor: createMockEditor() })
+ logic.mount()
+ router.actions.push(urls.sqlEditor(), undefined, { q: 'SELECT 1', engine: 'managed_trino' })
+ await expectLogic(logic).toDispatchActions(['setSourceQuery', 'createTab', 'updateTab'])
+ expect(logic.values.sourceQuery.source.executionTarget).toEqual('managed_trino')
+ })
+
it('reads send raw query from hash and keeps it in URL sync', async () => {
logic = sqlEditorLogic({
tabId: TAB_ID,
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index 51f6a811fe27..3831b4f3997a 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -480,6 +480,11 @@ function getTabHash(values: sqlEditorLogicType['values']): Record<string, any> {
q: values.queryInput ?? '',
output_tab: values.outputActiveTab,
}
+ if (values.sourceQuery?.source.executionTarget) {
+ hash['engine'] = values.sourceQuery.source.executionTarget
+ } else if (toDataVisualizationNode(values.activeTab?.insight?.query)?.source.executionTarget) {
+ hash['engine'] = 'posthog'
+ }
const connectionId = values.sourceQuery?.source.connectionId
if (connectionId) {
hash['c'] = connectionId
@@ -1083,6 +1088,9 @@ export interface sqlEditorLogicActions {
setError: (error: string | null) => {
error: string | null
}
+ setExecutionTarget: (executionTarget: HogQLQuery['executionTarget']) => {
+ executionTarget: 'default' | 'managed_trino' | undefined
+ }
setFinishedLoading: (loading: boolean) => {
loading: boolean
}
@@ -1494,6 +1502,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
fixIndexUsageWithAI: (prompt: string) => ({ prompt }),
setEditorSource: (source: SqlEditorSource) => ({ source }),
runSubquery: true,
+ setExecutionTarget: (executionTarget: HogQLQuery['executionTarget']) => ({ executionTarget }),
setSendRawQuery: (sendRawQuery: boolean) => ({ sendRawQuery }),
enforceConnectionRawQueryMode: true,
setDashboardId: (dashboardId: number | null) => ({ dashboardId }),
@@ -2174,6 +2183,19 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
}
persistEditorDraft()
},
+ setExecutionTarget: ({ executionTarget }) => {
+ actions.setSourceQuery({
+ ...values.sourceQuery,
+ source: {
+ ...values.sourceQuery.source,
+ query: values.queryInput ?? values.sourceQuery.source.query,
+ executionTarget,
+ connectionId: undefined,
+ sendRawQuery: undefined,
+ },
+ })
+ actions.syncUrlWithQuery()
+ },
setSendRawQuery: ({ sendRawQuery }) => {
const currentSourceQuery = values.sourceQuery
@@ -3739,6 +3761,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
sourceQuery: DataVisualizationNode,
splitRanges: QueryRange[]
) => {
+ if (
+ lastRunQuery &&
+ (lastRunQuery.source.executionTarget ?? 'default') !==
+ (sourceQuery.source.executionTarget ?? 'default')
+ ) {
+ return false
+ }
const lastRunQueryText = (lastRunQuery?.source.query ?? sourceQuery.source.query ?? '').trim()
if ((queryInput ?? '').trim() === lastRunQueryText) {
return true
@@ -3935,6 +3964,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
!hasOwnProperty(hashParams, 'q') &&
!hashParams.c &&
!hashParams.raw &&
+ !hasOwnProperty(hashParams, 'engine') &&
!hasFiltersHashParam &&
!hashParams.view &&
!hashParams.insight &&
@@ -3954,6 +3984,14 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const connectionIdFromHash =
typeof hashParams.c === 'string' && hashParams.c !== '' ? hashParams.c : undefined
const sendRawQueryFromHash = connectionIdFromHash !== undefined && String(hashParams.raw) === '1'
+ const hasEngineOverride = hasOwnProperty(hashParams, 'engine')
+ const executionTargetFromHash = hasEngineOverride
+ ? hashParams.engine === 'managed_trino'
+ ? 'managed_trino'
+ : undefined
+ : connectionIdFromHash
+ ? undefined
+ : values.sourceQuery.source.executionTarget
const currentConnectionId = values.sourceQuery.source.connectionId || undefined
const currentSendRawQuery = values.sourceQuery.source.sendRawQuery ?? false
const filtersForSourceQuery = applyFiltersFromUrl(values.sourceQuery).source.filters
@@ -3965,6 +4003,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
)
if (
+ executionTargetFromHash !== values.sourceQuery.source.executionTarget ||
connectionIdFromHash !== currentConnectionId ||
sendRawQueryFromHash !== currentSendRawQuery ||
shouldSyncFilters
@@ -3973,6 +4012,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
...values.sourceQuery,
source: {
...values.sourceQuery.source,
+ executionTarget: executionTargetFromHash,
connectionId: connectionIdFromHash,
sendRawQuery: sendRawQueryFromHash || undefined,
filters: filtersForSourceQuery,
@@ -4153,21 +4193,44 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const queryToOpen =
searchParams.open_query ?? (hasOwnProperty(hashParams, 'q') ? String(hashParams.q) : query)
- if (insightVisualizationQuery) {
- let insightSource = applyFiltersFromUrl(insightVisualizationQuery)
- if (localDraft || hasOwnProperty(hashParams, 'c') || hasOwnProperty(hashParams, 'raw')) {
+ let insightSource = insightVisualizationQuery
+ ? applyFiltersFromUrl(insightVisualizationQuery)
+ : undefined
+ if (insightSource) {
+ if (
+ localDraft ||
+ hasOwnProperty(hashParams, 'c') ||
+ hasOwnProperty(hashParams, 'raw') ||
+ hasEngineOverride
+ ) {
insightSource = {
...insightSource,
source: {
...insightSource.source,
+ executionTarget: connectionIdFromHash
+ ? undefined
+ : hasEngineOverride
+ ? executionTargetFromHash
+ : insightSource.source.executionTarget,
connectionId: connectionIdFromHash,
sendRawQuery: sendRawQueryFromHash || undefined,
},
}
}
+ }
+ if (insightSource) {
actions.setSourceQuery(insightSource)
}
actions.editInsight(queryToOpen, insight, biEditorStateFromUrl ?? undefined)
+ if (hasEngineOverride) {
+ actions.setSourceQuery({
+ ...values.sourceQuery,
+ source: {
+ ...values.sourceQuery.source,
+ executionTarget: connectionIdFromHash ? undefined : executionTargetFromHash,
+ },
+ })
+ }
if (!outputTabFromUrl) {
actions.setActiveTab(OutputTab.Visualization)
}
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.py
index 7c2555bbf514..3e3a86a96d88 100644
--- a/posthog/hogql/database/database.py
+++ b/posthog/hogql/database/database.py
@@ -2653,7 +2653,11 @@ class Database(BaseModel):
table_chain,
table_for_key,
case_insensitive=table.external_data_source.is_direct_query
- and table.external_data_source.direct_engine in {"snowflake", "trino"},
+ and (
+ table.external_data_source.direct_engine in {"snowflake", "trino"}
+ or table.external_data_source.is_managed_warehouse
+ and table.url_pattern == "direct://trino"
+ ),
),
table_conflict_mode=table_conflict_mode,
)
diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.py
index 4fb4a6b6f6f2..3e9b0339e6ce 100644
--- a/posthog/hogql/direct_sql/__init__.py
+++ b/posthog/hogql/direct_sql/__init__.py
@@ -1,3 +1,5 @@
+from typing import TYPE_CHECKING
+
from posthog.hogql.direct_sql.adapter import (
DirectQueryPrincipal,
DirectQueryRequest,
@@ -16,10 +18,14 @@ from posthog.hogql.direct_sql.redshift_adapter import RedshiftAdapter
from posthog.hogql.direct_sql.registry import get_adapter, register_adapter, registered_engines
from posthog.hogql.direct_sql.snowflake_adapter import SnowflakeAdapter
from posthog.hogql.direct_sql.trino_adapter import TrinoAdapter
+from posthog.hogql.errors import ExposedHogQLError
from products.warehouse_sources.backend.facade.models import ExternalDataSource
from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode
+if TYPE_CHECKING:
+ from posthog.models import Team
+
register_adapter(PostgresAdapter())
register_adapter(MySQLAdapter())
register_adapter(SnowflakeAdapter())
@@ -30,12 +36,30 @@ register_adapter(TrinoAdapter())
register_adapter(BigQueryAdapter())
-def get_raw_adapter_for_source(source: ExternalDataSource) -> DirectSQLAdapter | None:
+def get_adapter_for_source(source: ExternalDataSource, *, team: "Team | None" = None) -> DirectSQLAdapter | None:
+ if source.is_dynamic_managed_warehouse:
+ from products.managed_warehouse.backend.facade.sql_editor import ( # noqa: PLC0415 -- optional managed engine drivers stay off startup paths
+ managed_trino_adapter,
+ managed_warehouse_sql_editor_uses_trino,
+ )
+
+ resolved_team = team or source._state.fields_cache.get("team")
+ if resolved_team is None:
+ raise ExposedHogQLError("The project context is missing. Refresh the SQL editor and try again.")
+ if managed_warehouse_sql_editor_uses_trino(resolved_team.organization_id):
+ return managed_trino_adapter()
+ return get_adapter(source.direct_engine)
+
+
+def get_raw_adapter_for_source(source: ExternalDataSource, *, team: "Team | None" = None) -> DirectSQLAdapter | None:
if source.has_managed_warehouse_prefix:
managed_warehouse_mode = source.managed_warehouse_sql_mode
if not source.is_managed_warehouse or not is_direct_capable(source):
return None
if managed_warehouse_mode == ManagedWarehouseSQLMode.BUILT_IN:
+ adapter = get_adapter_for_source(source, team=team)
+ if adapter is not None and adapter.engine == "trino":
+ return adapter
return DuckgresRawAdapter()
if managed_warehouse_mode == ManagedWarehouseSQLMode.UNAVAILABLE:
return None
@@ -60,6 +84,7 @@ __all__ = [
"is_direct_capable",
"ensure_single_direct_statement",
"get_adapter",
+ "get_adapter_for_source",
"get_raw_adapter_for_source",
"register_adapter",
"registered_engines",
diff --git a/posthog/hogql/direct_sql/test/test_trino_adapter.py b/posthog/hogql/direct_sql/test/test_trino_adapter.py
index 371f8be0ccef..98685e27d9f5 100644
--- a/posthog/hogql/direct_sql/test/test_trino_adapter.py
+++ b/posthog/hogql/direct_sql/test/test_trino_adapter.py
@@ -49,6 +49,7 @@ def test_execute_returns_rows_and_types(
request = MagicMock()
request.sql = request_sql
request.values = request_values
+ request.cancellation_token = None
request.team.pk = 1
request.source.id = "source-id"
request.settings.max_execution_time = 30
@@ -76,3 +77,54 @@ def test_execute_returns_rows_and_types(
assert result.results == [(1, True)]
assert result.print_columns == ["id", "active"]
assert result.types == [("id", "Nullable(Int64)"), ("active", "Nullable(Bool)")]
+
+
+def test_cancellation_during_prepare_prevents_starting_the_main_query() -> None:
+ import json
+ import threading
+ from contextlib import nullcontext
+
+ import requests
+ from trino.dbapi import connect
+
+ from posthog.hogql.direct_sql.trino_adapter import TrinoQueryRequest, execute_trino_query
+ from posthog.hogql.timings import HogQLTimings
+
+ polled = threading.Event()
+ statements: list[str] = []
+ session = requests.Session()
+
+ def cancelled(*args: object) -> bool:
+ polled.set()
+ return True
+
+ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:
+ body = request.body
+ statements.append(body.decode() if isinstance(body, bytes) else str(body))
+ assert polled.wait(2)
+ response = requests.Response()
+ response.status_code = 200
+ response._content = json.dumps(
+ {"id": "prepare", "infoUri": "https://trino.example.com/query", "stats": {}, "data": []}
+ ).encode()
+ return response
+
+ connection = connect(host="trino.example.com", user="test", http_session=session, legacy_prepared_statements=True)
+ with (
+ patch.object(session, "send", side_effect=send),
+ patch("posthog.hogql.direct_sql.trino_adapter.is_direct_query_cancellation_requested", side_effect=cancelled),
+ pytest.raises(ExposedHogQLError, match="Trino query was canceled"),
+ ):
+ execute_trino_query(
+ TrinoQueryRequest(
+ sql="SELECT %(value)s",
+ values={"value": 1},
+ timeout_seconds=10,
+ timings=HogQLTimings(),
+ team_id=1,
+ cancellation_token="token",
+ ),
+ nullcontext(connection),
+ )
+ assert len(statements) == 1
+ assert statements[0].startswith("PREPARE ")
diff --git a/posthog/hogql/direct_sql/trino_adapter.py b/posthog/hogql/direct_sql/trino_adapter.py
index fe9c8322c4b4..a3ec46f1ea7b 100644
--- a/posthog/hogql/direct_sql/trino_adapter.py
+++ b/posthog/hogql/direct_sql/trino_adapter.py
@@ -1,9 +1,13 @@
from __future__ import annotations
+import time
import threading
-from typing import TYPE_CHECKING, cast
+from collections.abc import Iterator
+from contextlib import AbstractContextManager, contextmanager
+from typing import TYPE_CHECKING, Any, cast
import sqlparse
+import structlog
from opentelemetry import trace
from sqlparse import tokens as sqlparse_tokens
@@ -13,9 +17,15 @@ from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResu
from posthog.hogql.direct_sql.capability import is_direct_capable
from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement
from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.timings import HogQLTimings
from posthog.hogql.trino_parameters import convert_pyformat_placeholders
+from posthog.dataclasses import frozen
+from posthog.direct_query_cancellation import is_direct_query_cancellation_requested
+
if TYPE_CHECKING:
+ from trino.dbapi import Connection, Cursor
+
from posthog.models.team import Team
from products.warehouse_sources.backend.facade.models import ExternalDataSource
@@ -25,6 +35,8 @@ if TYPE_CHECKING:
from products.warehouse_sources.backend.temporal.data_imports.sources.trino.source import TrinoSource
+log = structlog.get_logger(__name__)
+
DIRECT_TRINO_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600
DIRECT_TRINO_MAX_ROWS = 1_000_000
RAW_TRINO_READ_ONLY_ERROR = "Raw Trino queries must be read-only SELECT statements."
@@ -46,31 +58,186 @@ def ensure_read_only_raw_trino_statement(sql: str) -> str:
class _CancelWatchdog:
- def __init__(self, cursor: object, timeout_seconds: float) -> None:
+ def __init__(
+ self, cursor: Cursor, timeout_seconds: float, *, team_id: int = 0, cancellation_token: str | None = None
+ ) -> None:
self._fired = threading.Event()
-
- def _cancel() -> None:
- self._fired.set()
- try:
- cursor.cancel() # type: ignore[attr-defined]
- except Exception:
- pass
-
- self._timer = threading.Timer(timeout_seconds, _cancel)
+ self._finished = threading.Event()
+ self._cancelled = threading.Event()
+ self._cancel_lock = threading.Lock()
+ self._team_id = team_id
+ self._cancellation_token = cancellation_token
+ self._cursor = cursor
+ self.deadline = time.monotonic() + max(timeout_seconds, 1)
+ self._timer = threading.Timer(max(timeout_seconds, 1), self._fired.set)
self._timer.daemon = True
+ self._thread = threading.Thread(target=self._watch_cancellation, daemon=True, name="trino-query-cancel")
def __enter__(self) -> _CancelWatchdog:
self._timer.start()
+ self._thread.start()
return self
def __exit__(self, *args: object) -> None:
+ with self._cancel_lock:
+ self._finished.set()
self._timer.cancel()
+ # A Redis poll may outlive the query. The lock and finished check prevent it from touching a closed cursor.
+ self._thread.join(timeout=1)
+
+ def _watch_cancellation(self) -> None:
+ delay = 0.5
+ while not self._finished.wait(delay):
+ try:
+ if (
+ not self.cancelled
+ and self._cancellation_token
+ and is_direct_query_cancellation_requested(self._team_id, self._cancellation_token)
+ ):
+ self._cancelled.set()
+ if self.cancelled or self.fired:
+ with self._cancel_lock:
+ if self._finished.is_set():
+ return
+ self._cursor.cancel()
+ delay = 0.5
+ except Exception:
+ if delay == 0.5:
+ log.warning("trino.cancellation_poll_failed", team_id=self._team_id, exc_info=True)
+ delay = min(delay * 2, 5)
+
+ def check(self) -> None:
+ if time.monotonic() >= self.deadline:
+ self._fired.set()
+ if self.cancelled:
+ raise ExposedHogQLError("Trino query was canceled.")
+ if self.fired:
+ raise ExposedHogQLError(DIRECT_TRINO_TIMEOUT_ERROR)
+
+ @property
+ def cancelled(self) -> bool:
+ return self._cancelled.is_set()
@property
def fired(self) -> bool:
return self._fired.is_set()
+@contextmanager
+def bounded_trino_cursor(
+ connection: Connection, timeout_seconds: float, *, team_id: int = 0, cancellation_token: str | None = None
+) -> Iterator[tuple[Cursor, _CancelWatchdog]]:
+ cursor = connection.cursor()
+ watchdog = _CancelWatchdog(cursor, timeout_seconds, team_id=team_id, cancellation_token=cancellation_token)
+ # The driver shares this session with capability probes and PREPARE, which cursor.cancel() cannot reach.
+ session = connection._http_session
+ original_request = session.request
+ original_delete = cursor._request._delete
+
+ def bounded_request(method: str, url: str, **kwargs: Any) -> Any:
+ if method.upper() == "DELETE":
+ remaining = 1.0
+ else:
+ watchdog.check()
+ remaining = max(watchdog.deadline - time.monotonic(), 0.001)
+ timeout = kwargs.get("timeout")
+ if isinstance(timeout, tuple):
+ kwargs["timeout"] = tuple(min(value or remaining / 2, remaining / 2) for value in timeout)
+ else:
+ kwargs["timeout"] = min(timeout or remaining / 2, remaining / 2)
+ return original_request(method, url, **kwargs)
+
+ session.request = bounded_request # type: ignore[method-assign, assignment] # ty: ignore[invalid-assignment]
+ # Cancellation gets one bounded HTTP attempt; driver retries would extend the statement deadline during cleanup.
+ cursor._request._delete = session.delete
+ try:
+ with watchdog:
+ yield cursor, watchdog
+ finally:
+ try:
+ cursor.close()
+ except Exception:
+ log.warning("trino.cursor_cleanup_failed", team_id=team_id, exc_info=True)
+ finally:
+ session.request = original_request # type: ignore[method-assign] # ty: ignore[invalid-assignment]
+ cursor._request._delete = original_delete
+
+
+@frozen
+class TrinoQueryRequest:
+ sql: str
+ values: dict[str, object] | None
+ timeout_seconds: float
+ timings: HogQLTimings
+ team_id: int
+ debug: bool = False
+ cancellation_token: str | None = None
+
+
+def execute_trino_query(
+ request: TrinoQueryRequest, connection_context: AbstractContextManager[Connection]
+) -> DirectQueryResult:
+ from products.warehouse_sources.backend.facade.models import (
+ trino_column_to_dwh_column, # noqa: PLC0415 -- optional result mapping belongs to warehouse sources
+ )
+ from products.warehouse_sources.backend.facade.source_management import (
+ trino_error_to_message, # noqa: PLC0415 -- avoids loading connector drivers during Django startup
+ )
+
+ span = trace.get_current_span()
+ span.set_attribute("team_id", request.team_id)
+ sql, values = (
+ convert_pyformat_placeholders(request.sql, request.values) if request.values is not None else (request.sql, [])
+ )
+ try:
+ with request.timings.measure("trino_execute"), observe_direct_query("trino"):
+ with connection_context as connection:
+ with bounded_trino_cursor(
+ connection,
+ request.timeout_seconds,
+ team_id=request.team_id,
+ cancellation_token=request.cancellation_token,
+ ) as (cursor, watchdog):
+ try:
+ if values:
+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- values are passed as parameters; the trino client escapes them, this code never concatenates them
+ sql, values
+ )
+ else:
+ cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- raw SQL is intentionally user-authored and SELECT-gated
+ sql
+ )
+ results = cursor.fetchmany(DIRECT_TRINO_MAX_ROWS + 1)
+ except Exception:
+ watchdog.check()
+ raise
+ watchdog.check()
+ description = cursor.description or []
+ except Exception as error:
+ span.set_attribute("error_type", error.__class__.__name__)
+ message = str(error) if isinstance(error, ExposedHogQLError) else trino_error_to_message(error)
+ if request.debug:
+ return DirectQueryResult(results=[], types=[], print_columns=[], error=message)
+ if isinstance(error, ExposedHogQLError):
+ raise
+ raise ExposedHogQLError(message) from error
+
+ if len(results) > DIRECT_TRINO_MAX_ROWS:
+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="trino").inc()
+ raise ExposedHogQLError(DIRECT_TRINO_ROW_CAP_ERROR)
+
+ span.set_attribute("row_count", len(results))
+ types = []
+ for column in description:
+ mapped = trino_column_to_dwh_column(str(column[0]), str(column[1]), True)
+ types.append((str(column[0]), str(mapped["clickhouse"])))
+ return DirectQueryResult(
+ results=list(results),
+ types=types,
+ print_columns=[str(column[0]) for column in description],
+ )
+
+
class TrinoAdapter:
engine = "trino"
dialect: HogQLDialect | None = "trino"
@@ -97,12 +264,8 @@ class TrinoAdapter:
return ensure_read_only_raw_trino_statement(sql)
def execute(self, request: DirectQueryRequest) -> DirectQueryResult:
- from products.warehouse_sources.backend.facade.models import (
- trino_column_to_dwh_column, # noqa: PLC0415 — product mapper is needed only for Trino results
- )
from products.warehouse_sources.backend.facade.source_management import ( # noqa: PLC0415 — keeps the optional driver off startup paths
connect_trino,
- trino_error_to_message,
)
_, config = self.validate_source_config(request.source, request.team)
@@ -114,57 +277,15 @@ class TrinoAdapter:
span.set_attribute("team_id", request.team.pk)
span.set_attribute("query_type", request.query_type)
span.set_attribute("source_id", str(request.source.id))
- sql, values = (
- convert_pyformat_placeholders(request.sql, request.values)
- if request.values is not None
- else (request.sql, [])
- )
-
- try:
- with request.timings.measure("trino_execute"), observe_direct_query("trino"):
- with connect_trino(config) as connection:
- cursor = connection.cursor()
- with _CancelWatchdog(cursor, timeout_seconds) as watchdog:
- try:
- if values:
- cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- values are passed as parameters; the trino client escapes them, this code never concatenates them
- sql, values
- )
- else:
- cursor.execute( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute -- raw SQL is intentionally user-authored and SELECT-gated
- sql
- )
- results = cursor.fetchmany(DIRECT_TRINO_MAX_ROWS + 1)
- except Exception as error:
- if watchdog.fired:
- raise ExposedHogQLError(DIRECT_TRINO_TIMEOUT_ERROR) from error
- raise
- # The parameterized path runs a capability probe and a PREPARE before the
- # main query exists, where cancel() is a no-op. Refuse results that arrive
- # past the deadline so the timeout holds through that window.
- if watchdog.fired:
- raise ExposedHogQLError(DIRECT_TRINO_TIMEOUT_ERROR)
- description = cursor.description or []
- except Exception as error:
- span.set_attribute("error_type", error.__class__.__name__)
- message = str(error) if isinstance(error, ExposedHogQLError) else trino_error_to_message(error)
- if request.debug:
- return DirectQueryResult(results=[], types=[], print_columns=[], error=message)
- if isinstance(error, ExposedHogQLError):
- raise
- raise ExposedHogQLError(message) from error
-
- if len(results) > DIRECT_TRINO_MAX_ROWS:
- DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="trino").inc()
- raise ExposedHogQLError(DIRECT_TRINO_ROW_CAP_ERROR)
-
- span.set_attribute("row_count", len(results))
- types = []
- for column in description:
- mapped = trino_column_to_dwh_column(str(column[0]), str(column[1]), True)
- types.append((str(column[0]), str(mapped["clickhouse"])))
- return DirectQueryResult(
- results=list(results),
- types=types,
- print_columns=[str(column[0]) for column in description],
+ return execute_trino_query(
+ TrinoQueryRequest(
+ sql=request.sql,
+ values=request.values,
+ timeout_seconds=timeout_seconds,
+ timings=request.timings,
+ team_id=request.team.pk,
+ debug=request.debug,
+ cancellation_token=request.cancellation_token,
+ ),
+ connect_trino(config),
)
diff --git a/posthog/hogql/metadata.py b/posthog/hogql/metadata.py
index abca856f1a2e..db4988f367ac 100644
--- a/posthog/hogql/metadata.py
+++ b/posthog/hogql/metadata.py
@@ -29,7 +29,7 @@ from posthog.hogql.constants import HogQLDialect
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.database import Database
from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
-from posthog.hogql.direct_sql import get_adapter
+from posthog.hogql.direct_sql import get_adapter_for_source
from posthog.hogql.errors import (
ExposedHogQLError,
NotImplementedError as HogQLNotImplementedError,
@@ -187,7 +187,7 @@ def get_hogql_metadata(
response.table_names = hogql_table_names
if not printed_sql or not prepared_ast:
- direct_adapter = get_adapter(source.direct_engine) if source else None
+ direct_adapter = get_adapter_for_source(source, team=team) if source else None
direct_dialect: HogQLDialect = (
direct_adapter.dialect if direct_adapter and direct_adapter.dialect else "postgres"
)
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index d4c61755f75a..783cfe05ba37 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -46,7 +46,7 @@ from posthog.hogql.direct_sql import (
DirectQueryRequest,
DirectSQLAdapter,
ensure_single_direct_statement,
- get_adapter,
+ get_adapter_for_source,
get_raw_adapter_for_source,
)
from posthog.hogql.errors import BaseHogQLError, ExposedHogQLError, InternalHogQLError, QueryError, ResolutionError
@@ -132,6 +132,7 @@ class HogQLQueryExecutor:
direct_values: dict[str, object] | None = None
direct_dialect: Optional[HogQLDialect] = None
connection_id: Optional[str] = None
+ expected_direct_engine: str | None = None
send_raw_query: bool = False
user: Optional[User] = None
bypass_warehouse_access_control: bool = False
@@ -173,6 +174,7 @@ class HogQLQueryExecutor:
self.used_data_warehouse_sources: list[WarehouseSourceUsage] = []
self._direct_source: Optional[ExternalDataSource] = None
self._direct_source_resolved = False
+ self._compilation_adapter: DirectSQLAdapter | None = None
self._prompt_jev_tables: list[PromptJevTable] = []
self._prompt_jev_warehouse_sources: list[WarehouseSourceUsage] = []
self._executing = False
@@ -444,8 +446,7 @@ class HogQLQueryExecutor:
if self.connection_id != direct_source_id:
raise ExposedHogQLError("The query references a different source than the selected connection.")
- source = self._direct_source
- adapter = get_adapter(source.direct_engine) if source is not None else None
+ adapter = self._compilation_adapter
if adapter is not None and adapter.dialect is None:
# A raw-only engine (BigQuery) has no HogQL printer; falling back to another
# dialect would send SQL the engine cannot parse.
@@ -627,9 +628,17 @@ class HogQLQueryExecutor:
if source is None:
raise ExposedHogQLError("Connection not found or has been deleted")
- adapter = adapter or get_adapter(source.direct_engine)
+ adapter = adapter or get_adapter_for_source(source, team=self.team)
if adapter is None:
raise InternalHogQLError(f"No direct SQL adapter registered for engine: {source.direct_engine}")
+ if self.expected_direct_engine is not None and (
+ (self.expected_direct_engine == "trino") != (adapter.engine == "trino")
+ ):
+ raise ExposedHogQLError("The warehouse engine changed. Run the query again.")
+ if source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN and (
+ (self.direct_dialect == "trino") != (adapter.engine == "trino")
+ ):
+ raise ExposedHogQLError("The warehouse engine changed. Run the query again.")
stats = query_stats.get_active()
if stats is not None:
@@ -826,7 +835,9 @@ class HogQLQueryExecutor:
self.context.limit_top_select = False
source = self._resolve_direct_source()
- if source is not None and source.direct_engine == "trino":
+ adapter = get_adapter_for_source(source, team=self.team) if source is not None else None
+ self._compilation_adapter = adapter
+ if adapter is not None and adapter.engine == "trino":
trino_execution = self._prepare_pure_trino_query()
if trino_execution is not None:
return trino_execution
@@ -875,7 +886,7 @@ class HogQLQueryExecutor:
self.connection_id = str(source.id)
self.direct_source_id = self.connection_id
managed_warehouse_mode = source.managed_warehouse_sql_mode if source.has_managed_warehouse_prefix else None
- adapter = get_raw_adapter_for_source(source)
+ adapter = get_raw_adapter_for_source(source, team=self.team)
if adapter is None:
raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)
if managed_warehouse_mode != ManagedWarehouseSQLMode.BUILT_IN and raw_query_denied_by_table_access(
diff --git a/posthog/hogql/test/test_direct_duckgres_query.py b/posthog/hogql/test/test_direct_duckgres_query.py
index 83c40423a2aa..7228a8698519 100644
--- a/posthog/hogql/test/test_direct_duckgres_query.py
+++ b/posthog/hogql/test/test_direct_duckgres_query.py
@@ -1,6 +1,8 @@
import socket
import threading
from collections.abc import Generator
+from contextlib import contextmanager, nullcontext
+from uuid import UUID
from posthog.test.base import APIBaseTest
from unittest.mock import MagicMock, patch
@@ -20,7 +22,7 @@ from posthog.hogql.errors import ExposedHogQLError, QueryError, TableAccessDenie
from posthog.hogql.query import HogQLQueryExecutor
from posthog.constants import AvailableFeature
-from posthog.models import OrganizationMembership
+from posthog.models import OrganizationMembership, Team
from products.access_control.backend.models.access_control import AccessControl
from products.warehouse_sources.backend.facade.models import (
@@ -32,6 +34,12 @@ from products.warehouse_sources.backend.facade.types import ExternalDataSourceTy
class TestDuckgresRawAdapterSelection(SimpleTestCase):
+ def setUp(self) -> None:
+ super().setUp()
+ flag = patch("posthoganalytics.feature_enabled", return_value=False)
+ flag.start()
+ self.addCleanup(flag.stop)
+
def _source(self, **overrides: object) -> ExternalDataSource:
source = ExternalDataSource(
team_id=123,
@@ -53,6 +61,7 @@ class TestDuckgresRawAdapterSelection(SimpleTestCase):
"reader_configured": True,
},
)
+ source.team = Team(id=123, organization_id=UUID("00000000-0000-0000-0000-000000000001"))
for field, value in overrides.items():
setattr(source, field, value)
return source
@@ -205,6 +214,97 @@ class TestDirectDuckgresQuery(APIBaseTest):
self.resolve_hostaddr = resolver_patcher.start()
self.addCleanup(resolver_patcher.stop)
+ @parameterized.expand([(True,), (False,)])
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_managed_source_switches_raw_and_hogql_execution_to_trino(self, raw: bool, _flag: MagicMock) -> None:
+ _flag.side_effect = lambda flag, *_args, **_kwargs: flag == "managed-warehouse-trino-query"
+ source = self._dynamic_managed_source()
+ source.job_inputs = {}
+ source.save(update_fields=["job_inputs"])
+ DataWarehouseTable.objects.create(
+ team=self.team,
+ external_data_source=source,
+ name="posthog.events",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern="direct://trino",
+ columns={"uuid": {"hogql": "StringDatabaseField", "clickhouse": "String", "valid": True}},
+ options={
+ "direct_trino_catalog": "org_example",
+ "direct_trino_schema": "posthog",
+ "direct_trino_table": "events",
+ },
+ )
+ cursor = MagicMock()
+ cursor.fetchmany.return_value = [("row-uuid",)]
+ cursor.description = [("uuid", "varchar")]
+ connection = MagicMock()
+ connection.cursor.return_value = cursor
+ query = 'SELECT uuid FROM "posthog"."events"' if raw else "SELECT uuid FROM posthog.events"
+ with (
+ patch(
+ "products.managed_warehouse.backend.logic.sql_editor_trino.connect_managed_warehouse_trino",
+ return_value=nullcontext(connection),
+ ) as connect,
+ patch("posthog.hogql.direct_sql.duckgres_adapter.psycopg.connect") as duckgres,
+ ):
+ response = HogQLQueryExecutor(
+ query=query,
+ team=self.team,
+ user=self.user,
+ connection_id=str(source.id),
+ send_raw_query=raw,
+ ).execute()
+ with self.assertRaisesMessage(ExposedHogQLError, "warehouse engine changed"):
+ HogQLQueryExecutor(
+ query=query,
+ team=self.team,
+ user=self.user,
+ connection_id=str(source.id),
+ send_raw_query=raw,
+ expected_direct_engine="postgres",
+ ).execute()
+ self.assertEqual(response.results, [("row-uuid",)])
+ connect.assert_called_once_with(
+ str(self.team.organization_id), principal=f"posthog:sql-editor:team:{self.team.pk}:user:{self.user.pk}"
+ )
+ duckgres.assert_not_called()
+ self.assertIn('"posthog"."events"', cursor.execute.call_args.args[0])
+ if not raw:
+ self.assertIn('"org_example"', cursor.execute.call_args.args[0])
+ options = self.client.get(f"/api/projects/{self.team.pk}/external_data_sources/connections/").json()
+ self.assertEqual(options[0]["id"], str(source.pk))
+ self.assertEqual(options[0]["engine"], "trino")
+ self.assertTrue(options[0]["is_builtin_managed_warehouse"])
+
+ @parameterized.expand([("open",), ("enter",)])
+ @patch("posthoganalytics.feature_enabled", return_value=True)
+ def test_managed_trino_unavailable_does_not_fall_back_to_duckgres(self, stage: str, _flag: MagicMock) -> None:
+ from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTrinoConnectionUnavailable
+
+ source = self._dynamic_managed_source()
+ source.job_inputs = {}
+ source.save(update_fields=["job_inputs"])
+
+ @contextmanager
+ def unavailable() -> Generator[None]:
+ if stage == "enter":
+ raise ManagedWarehouseTrinoConnectionUnavailable("not ready")
+ yield None
+
+ with (
+ patch(
+ "products.managed_warehouse.backend.logic.sql_editor_trino.connect_managed_warehouse_trino",
+ side_effect=ManagedWarehouseTrinoConnectionUnavailable("not ready") if stage == "open" else None,
+ return_value=unavailable(),
+ ),
+ patch("posthog.hogql.direct_sql.duckgres_adapter.psycopg.connect") as duckgres,
+ self.assertRaisesMessage(ExposedHogQLError, "Trino is not ready"),
+ ):
+ HogQLQueryExecutor(
+ query="SELECT 1", team=self.team, user=self.user, connection_id=str(source.id), send_raw_query=True
+ ).execute()
+ duckgres.assert_not_called()
+
def _managed_source(
self,
*,
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 6225db4901ca..9dde15d47702 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -8,6 +8,7 @@ from posthog.schema import (
CacheMissResponse,
DashboardFilter,
DateRange,
+ ExecutionTarget,
HogQLFilters,
HogQLQuery,
HogQLQueryModifiers,
@@ -19,6 +20,7 @@ from posthog.hogql import ast
from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
from posthog.hogql.database.schema.activity_log_visibility import activity_log_visibility_policy_version
from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_source
+from posthog.hogql.direct_sql import get_adapter_for_source
from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.filters import replace_filters
from posthog.hogql.metadata import get_table_names
@@ -38,6 +40,10 @@ from posthog.models import User
from posthog.models.activity_logging.retention import get_activity_log_lookback_restriction
from products.managed_warehouse.backend.facade import query_labels as managed_warehouse_query_labels
+from products.managed_warehouse.backend.facade.query_execution import (
+ execute_managed_trino_query,
+ validate_managed_trino_query,
+)
from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode
_INFORMATION_SCHEMA_PREFIX = "system.information_schema."
@@ -70,8 +76,10 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
return last_refresh + staleness_threshold_map[ThresholdMode.LAZY if lazy else ThresholdMode.DEFAULT]["day"]
def _validate_direct_connection(self, *, user: Optional[User] = None, force: bool = False) -> None:
- if self._direct_connection_validated and not force:
+ if not force and self._direct_connection_validated:
return
+ if self.query.executionTarget == ExecutionTarget.MANAGED_TRINO:
+ validate_managed_trino_query(self.query, self.team, user if user is not None else self.user)
managed_warehouse_sql_mode: ManagedWarehouseSQLMode | None = None
direct_engine: str | None = None
if self.query.connectionId:
@@ -87,6 +95,9 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
managed_warehouse_sql_mode = source.managed_warehouse_sql_mode
if managed_warehouse_sql_mode == ManagedWarehouseSQLMode.UNAVAILABLE:
raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)
+ if managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN:
+ adapter = get_adapter_for_source(source, team=self.team)
+ direct_engine = adapter.engine if adapter is not None else None
self._managed_warehouse_sql_mode = managed_warehouse_sql_mode
self._direct_engine = direct_engine
self._direct_connection_validated = True
@@ -96,6 +107,8 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
payload = super().get_cache_payload()
if self._managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN:
payload["managed_warehouse_sql_mode"] = self._managed_warehouse_sql_mode.value
+ if self._direct_engine == "trino":
+ payload["managed_warehouse_engine"] = "trino"
if self._modifiers_override_provided and self.query.modifiers is not None:
# Old workers preferred query modifiers while new workers prefer the constructor override.
# Keep their cached results apart during a rolling deploy.
@@ -250,6 +263,19 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
self._validate_direct_connection()
+ if self.query.executionTarget == ExecutionTarget.MANAGED_TRINO:
+ if self.is_query_service:
+ validate_user_query(self._parse_query()[0], team=self.team)
+ return execute_managed_trino_query(
+ self.query.model_copy(update={"modifiers": self.modifiers}),
+ team=self.team,
+ user=self.user,
+ user_access_control=self.user_access_control,
+ settings=self.settings or HogQLGlobalSettings(),
+ timings=self.timings,
+ limit_context=self.limit_context,
+ )
+
if self.query.sendRawQuery and self.query.connectionId:
return execute_hogql_query(
query_type="HogQLQuery",
@@ -267,6 +293,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
ch_user=self.ch_user,
settings=self.settings,
send_raw_query=True,
+ expected_direct_engine=self._direct_engine,
)
query = self._parse_query()[0] if self._direct_engine == "trino" else self.to_query()
@@ -310,6 +337,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
workload=self.workload,
ch_user=self.ch_user,
settings=self.settings,
+ expected_direct_engine=self._direct_engine,
**context_kwargs,
)
if paginator:
diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.py
index 4fced43acdf7..9155d64088c7 100644
--- a/posthog/hogql_queries/test/test_hogql_query_runner.py
+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py
@@ -283,14 +283,24 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
with self.assertRaises(ExposedHogQLError):
runner.calculate()
+ @parameterized.expand(
+ [(False, "project_reader"), (False, "duckgres_service"), (True, "duckgres_service"), (True, "project_reader")]
+ )
+ @patch("posthoganalytics.feature_enabled")
@patch(
"posthog.permissions.posthog_feature_flag_enabled",
side_effect=AssertionError("managed warehouse query execution must not evaluate a product feature flag"),
)
@patch("posthog.hogql_queries.hogql_query_runner.execute_hogql_query")
- def test_managed_warehouse_cache_and_status_do_not_evaluate_a_feature_flag(
- self, mock_execute_hogql_query: MagicMock, feature_flag_lookup: MagicMock
+ def test_managed_warehouse_cache_and_status_follow_selected_engine(
+ self,
+ trino: bool,
+ credential_kind: str,
+ mock_execute_hogql_query: MagicMock,
+ feature_flag_lookup: MagicMock,
+ engine_flag: MagicMock,
) -> None:
+ engine_flag.return_value = trino
source = ExternalDataSource.objects.create(
source_id="managed-source",
connection_id="managed-connection",
@@ -304,8 +314,9 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
connection_metadata={
"engine": "duckdb",
"system_managed": True,
- "credential_kind": "project_reader",
+ "credential_kind": credential_kind,
"reader_configured": True,
+ "lifecycle_generation": 1,
},
job_inputs={
"host": "managed.example.com",
@@ -315,6 +326,9 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
"password": "reader-password",
},
)
+ if credential_kind == "duckgres_service":
+ source.job_inputs = {}
+ source.save(update_fields=["job_inputs"])
query = HogQLQuery(query="select 1::int as value", connectionId=str(source.id), sendRawQuery=True)
mock_execute_hogql_query.return_value = HogQLQueryResponse(results=[(1,)], columns=["value"], types=[])
@@ -347,8 +361,15 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
self.assertEqual(second_response.results, [(1,)])
+ with patch("posthoganalytics.feature_enabled", return_value=not trino):
+ if credential_kind == "duckgres_service":
+ self.assertNotEqual(self._create_runner(query).get_cache_key(), built_in_cache_key)
+ else:
+ self.assertEqual(self._create_runner(query).get_cache_key(), built_in_cache_key)
+
assert isinstance(source.connection_metadata, dict)
source.connection_metadata["reader_configured"] = False
+ source.connection_metadata["lifecycle_generation"] = -1
source.save(update_fields=["connection_metadata"])
with self.assertRaisesMessage(ExposedHogQLError, "Invalid connectionId"):
self._create_runner(query).run()
diff --git a/posthog/schema.py b/posthog/schema.py
index f83615b15b5d..ce89b0ef3e29 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -122,6 +122,7 @@ from posthog.schema_enums import (
ErrorTrackingReleasesOrderBy as ErrorTrackingReleasesOrderBy,
EvaluationRuntime as EvaluationRuntime,
EventMatchScope as EventMatchScope,
+ ExecutionTarget as ExecutionTarget,
ExperimentApiBreakdownAttributionType as ExperimentApiBreakdownAttributionType,
ExperimentApiPropertyBreakdownType as ExperimentApiPropertyBreakdownType,
ExperimentExposureHealthFindingActionKind as ExperimentExposureHealthFindingActionKind,
@@ -30744,6 +30745,10 @@ class HogQLQuery(BaseModel):
" direct query enabled."
),
)
+ executionTarget: ExecutionTarget | None = Field(
+ default=None,
+ description="Compile and run this query against the hosted Trino target.",
+ )
explain: bool | None = None
filters: HogQLFilters | None = Field(
default=None,
diff --git a/posthog/schema_enums.py b/posthog/schema_enums.py
index 2ba97bb05acc..d102e6ecc13e 100644
--- a/posthog/schema_enums.py
+++ b/posthog/schema_enums.py
@@ -1769,6 +1769,11 @@ class HogQLAlertEvaluation(StrEnum):
ANY_ROW = "any_row"
+class ExecutionTarget(StrEnum):
+ DEFAULT = "default"
+ MANAGED_TRINO = "managed_trino"
+
+
class BounceRatePageViewMode(StrEnum):
COUNT_PAGEVIEWS = "count_pageviews"
UNIQ_URLS = "uniq_urls"
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index cf7d4c4e1328..158369961f6f 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -6994,6 +6994,13 @@ export interface PathsV2ActorsQueryApi {
version?: number | null
}
+export type ExecutionTargetApi = (typeof ExecutionTargetApi)[keyof typeof ExecutionTargetApi]
+
+export const ExecutionTargetApi = {
+ Default: 'default',
+ ManagedTrino: 'managed_trino',
+} as const
+
export interface HogQLFiltersApi {
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilterApi | null
@@ -7090,6 +7097,8 @@ export type HogQLQueryApiVariables = { [key: string]: HogQLVariableApi } | null
export interface HogQLQueryApi {
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string | null
+ /** Compile and run this query against the hosted Trino target. */
+ executionTarget?: ExecutionTargetApi | null
explain?: boolean | null
/** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */
filters?: HogQLFiltersApi | null
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 75cefc6a6047..8ca5dc745204 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -65,6 +65,7 @@ _LAZY = {
"reproject_direct_mysql_table": "mysql_helpers",
"get_postgres_source_location": "postgres_helpers",
"reconcile_postgres_schemas": "postgres_helpers",
+ "reconcile_managed_trino_schemas": "trino_helpers",
"reproject_direct_postgres_table": "postgres_helpers",
"reconcile_snowflake_schemas": "snowflake_helpers",
"reproject_direct_snowflake_table": "snowflake_helpers",
diff --git a/products/data_warehouse/backend/presentation/views/expression.py b/products/data_warehouse/backend/presentation/views/expression.py
index b3b75665b6d0..f9860ccacb00 100644
--- a/products/data_warehouse/backend/presentation/views/expression.py
+++ b/products/data_warehouse/backend/presentation/views/expression.py
@@ -11,7 +11,7 @@ from posthog.hogql.constants import HogQLDialect
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.models import ExpressionField
from posthog.hogql.direct_connection import resolve_database_for_connection
-from posthog.hogql.direct_sql import get_adapter
+from posthog.hogql.direct_sql import get_adapter_for_source
from posthog.hogql.errors import BaseHogQLError, ExposedHogQLError
from posthog.hogql.parser import parse_expr
from posthog.hogql.printer import prepare_and_print_ast
@@ -172,7 +172,7 @@ class DataWarehouseExpressionSerializer(serializers.ModelSerializer):
try:
dialect: HogQLDialect = "clickhouse"
if source is not None:
- adapter = get_adapter(source.direct_engine)
+ adapter = get_adapter_for_source(source, team=team)
dialect = adapter.dialect if adapter is not None and adapter.dialect is not None else "postgres"
context = HogQLContext(
team_id=team_id,
@@ -184,7 +184,14 @@ class DataWarehouseExpressionSerializer(serializers.ModelSerializer):
select=[ast.Field(chain=[field_name])],
select_from=ast.JoinExpr(table=ast.Field(chain=cast(list[str | int], table_name.split(".")))),
)
- prepare_and_print_ast(probe_query, context, dialect)
+ if dialect == "trino":
+ from posthog.hogql.transforms.trino.manifest import (
+ transpile_hogql_to_trino_with_database, # noqa: PLC0415 -- load the pure compiler only for Trino expressions
+ )
+
+ transpile_hogql_to_trino_with_database(probe_query, database=database)
+ else:
+ prepare_and_print_ast(probe_query, context, dialect)
except ExposedHogQLError as e:
raise serializers.ValidationError({"expression": [str(e)]})
except RecursionError:
diff --git a/products/data_warehouse/backend/tests/api/test_expression.py b/products/data_warehouse/backend/tests/api/test_expression.py
index a782743f8eed..fcdd65ef6109 100644
--- a/products/data_warehouse/backend/tests/api/test_expression.py
+++ b/products/data_warehouse/backend/tests/api/test_expression.py
@@ -2,7 +2,7 @@ from types import SimpleNamespace
from uuid import uuid4
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
from rest_framework.exceptions import ValidationError as DRFValidationError
@@ -267,10 +267,12 @@ class TestExpressionApi(APIBaseTest):
"password": "password",
},
),
+ ("managed_trino", "Postgres", {}),
]
)
+ @patch("posthoganalytics.feature_enabled", return_value=True)
def test_connection_scoped_expression_saves_in_source_dialect(
- self, _name: str, source_type: str, job_inputs: dict[str, object]
+ self, _name: str, source_type: str, job_inputs: dict[str, object], _flag: MagicMock
) -> None:
source = ExternalDataSource.objects.create(
team=self.team,
@@ -282,12 +284,27 @@ class TestExpressionApi(APIBaseTest):
prefix="direct",
job_inputs=job_inputs,
)
+ if _name == "managed_trino":
+ source.prefix = "managed_warehouse"
+ source.direct_query_enabled = True
+ source.connection_metadata = {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ }
+ source.save(update_fields=["prefix", "direct_query_enabled", "connection_metadata"])
DataWarehouseTable.objects.create(
name="events",
format="Parquet",
team=self.team,
external_data_source=source,
- url_pattern="",
+ url_pattern="direct://trino" if _name == "managed_trino" else "",
+ options={
+ "direct_trino_catalog": "example",
+ "direct_trino_schema": "public",
+ "direct_trino_table": "events",
+ },
columns={
"id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},
"team_id": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True},
diff --git a/products/data_warehouse/backend/trino_helpers.py b/products/data_warehouse/backend/trino_helpers.py
index a1a1e605613f..f83a28e87be3 100644
--- a/products/data_warehouse/backend/trino_helpers.py
+++ b/products/data_warehouse/backend/trino_helpers.py
@@ -8,6 +8,7 @@ url_pattern, the option keys that encode source location on a direct table) live
from __future__ import annotations
from typing import TYPE_CHECKING, Any
+from uuid import UUID
import structlog
@@ -20,6 +21,7 @@ from products.data_warehouse.backend.direct_trino import (
)
from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
+ get_direct_external_data_source_for_connection,
get_schemas_for_direct_reconciliation,
trino_column_to_dwh_column,
trino_columns_to_dwh_columns,
@@ -164,6 +166,13 @@ def get_trino_source_location_for_schema_model(
)
+def reconcile_managed_trino_schemas(*, source_id: UUID, source_schemas: list[SourceSchema], team_id: int) -> list[str]:
+ source = get_direct_external_data_source_for_connection(team_id, str(source_id))
+ if source is None or not source.is_dynamic_managed_warehouse:
+ raise ValueError("Source is not a dynamic managed warehouse connection")
+ return reconcile_trino_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
+
def reconcile_trino_schemas(
*,
source: ExternalDataSource,
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts
index ceec7c4ba169..16df86974684 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/dataOpsVariant.ts
@@ -6,7 +6,7 @@ export type DataOpsVariant = 'trino' | 'duckdb'
// Mirrors data_ops_variant in products/managed_warehouse/backend/presentation/views.py.
// The backend enforces the same rule, so a change here needs the same change there.
export function dataOpsVariantFromFlags(featureFlags: FeatureFlagsSet): DataOpsVariant | null {
- if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]) {
+ if (featureFlags[FEATURE_FLAGS.MANAGED_TRINO_QUERY]) {
return 'trino'
}
if (featureFlags[FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]) {
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts b/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts
index e0afdd1a11a1..321db8431b8b 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/dataWarehouseSceneLogic.test.ts
@@ -68,8 +68,8 @@ describe('dataWarehouseSceneLogic', () => {
})
const useOnlyTheTrinoFlag = (): void => {
- flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO], {
- [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]: true,
+ flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.MANAGED_TRINO_QUERY], {
+ [FEATURE_FLAGS.MANAGED_TRINO_QUERY]: true,
})
}
@@ -81,10 +81,10 @@ describe('dataWarehouseSceneLogic', () => {
})
it('prefers the Trino variant when both flags are on', async () => {
- flagsLogic.actions.setFeatureFlags(
- [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE, FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO],
- { [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true, [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]: true }
- )
+ flagsLogic.actions.setFeatureFlags([FEATURE_FLAGS.DATA_WAREHOUSE_SCENE, FEATURE_FLAGS.MANAGED_TRINO_QUERY], {
+ [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE]: true,
+ [FEATURE_FLAGS.MANAGED_TRINO_QUERY]: true,
+ })
mountScene()
await waitForWarehouseStatus()
diff --git a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx
index fb769533011b..8f4d49b2fb6f 100644
--- a/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx
+++ b/products/data_warehouse/frontend/scenes/DataOpsScene/tabs/SettingsTab.test.tsx
@@ -59,7 +59,7 @@ describe('SettingsTab', () => {
},
},
}),
- [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO]
+ [FEATURE_FLAGS.MANAGED_TRINO_QUERY]
)
expect(await screen.findByText('Catalog')).toBeInTheDocument()
diff --git a/products/data_warehouse/manifest.tsx b/products/data_warehouse/manifest.tsx
index d1ade27e757d..242ea7d1fdcd 100644
--- a/products/data_warehouse/manifest.tsx
+++ b/products/data_warehouse/manifest.tsx
@@ -178,7 +178,7 @@ export const manifest: ProductManifest = {
searchKeywords: ['managed warehouse', 'data lake', 'lakehouse'],
searchTabs: [{ name: 'Monitoring', href: urls.dataOps('monitoring') }],
flag: FEATURE_FLAGS.DATA_WAREHOUSE_SCENE,
- alternativeFlags: [FEATURE_FLAGS.DATA_WAREHOUSE_SCENE_TRINO],
+ alternativeFlags: [FEATURE_FLAGS.MANAGED_TRINO_QUERY],
iconType: 'data_warehouse',
iconColor: ['var(--color-product-data-warehouse-light)'],
sceneKey: 'DataOps',
diff --git a/products/data_warehouse/mcp/tools.yaml b/products/data_warehouse/mcp/tools.yaml
index f2f03194cb03..8b1b3871407c 100644
--- a/products/data_warehouse/mcp/tools.yaml
+++ b/products/data_warehouse/mcp/tools.yaml
@@ -52,7 +52,7 @@ tools:
runs on Trino. Available metrics cover queries in flight by state, query rate and errors, query duration,
queue time, data scanned, CPU time, and storage size. The response includes units and labeled series. These
values are not billing totals.
- feature_flag: data-warehouse-scene-trino
+ feature_flag: managed-warehouse-trino-query
managed-warehouse-trino-monitoring-get:
operation: data_warehouse_managed_warehouse_trino_monitoring_retrieve
enabled: true
@@ -69,7 +69,7 @@ tools:
removed from their SQL. Use this to inspect current workload. When `available` is false the live data could
not be read, so the totals do not mean the warehouse is idle. These values describe operational activity,
not invoiced usage.
- feature_flag: data-warehouse-scene-trino
+ feature_flag: managed-warehouse-trino-query
saved-query-column-annotations-create:
operation: saved_query_column_annotations_create
enabled: true
diff --git a/products/desktop/packages/api-client/src/generated.ts b/products/desktop/packages/api-client/src/generated.ts
index 5433ff29687f..3abb8c1f949e 100644
--- a/products/desktop/packages/api-client/src/generated.ts
+++ b/products/desktop/packages/api-client/src/generated.ts
@@ -4225,6 +4225,7 @@ export namespace Schemas {
tags?: (QueryLogTags | null) | undefined;
version?: (number | null) | undefined;
};
+ export type ExecutionTarget = "default" | "managed_trino";
export type HogQLFilters = Partial<{
breakdownFilter: BreakdownFilter | null;
compareFilter: CompareFilter | null;
@@ -4383,6 +4384,7 @@ export namespace Schemas {
};
export type HogQLQuery = {
connectionId?: (string | null) | undefined;
+ executionTarget?: (ExecutionTarget | null) | undefined;
explain?: (boolean | null) | undefined;
filters?: (HogQLFilters | null) | undefined;
kind?: string | undefined;
@@ -8968,16 +8970,6 @@ export namespace Schemas {
* * `opt_in` - Opt In
*/
export type EmailTrackingConsentModeEnum = "off" | "opt_out" | "opt_in";
- /**
- * * `duckdb` - duckdb
- * * `postgres` - postgres
- * * `mysql` - mysql
- * * `snowflake` - snowflake
- * * `redshift` - redshift
- * * `clickhouse` - clickhouse
- * * `motherduck` - motherduck
- * * `trino` - trino
- */
export type EngineEnum =
| "duckdb"
| "postgres"
diff --git a/products/managed_warehouse/backend/README.md b/products/managed_warehouse/backend/README.md
index b08568e07b25..1ffb14ab5743 100644
--- a/products/managed_warehouse/backend/README.md
+++ b/products/managed_warehouse/backend/README.md
@@ -118,17 +118,17 @@ This path currently supports Parquet only. Support for Azure Blob Storage, CSV,
## Feature flag gating
-Each workflow evaluates a feature flag through `feature_enabled`. Create or update the appropriate flag locally. The copy flags target the project, while `data-warehouse-scene` and `data-warehouse-scene-trino` target the organization. Otherwise, the workflow will be skipped even if the rest of the configuration is correct.
+Each workflow evaluates a feature flag through `feature_enabled`. Create or update the appropriate flag locally. The copy flags target the project, while `data-warehouse-scene` and `managed-warehouse-trino-query` target the organization. Otherwise, the workflow will be skipped even if the rest of the configuration is correct.
-| Workflow | Feature Flag |
-| ------------------------ | ------------------------------------------------------ |
-| Data Modeling | `ducklake-data-modeling-copy-workflow` |
-| Data Imports | `ducklake-data-imports-copy-workflow` |
-| Data Import Registration | `data-warehouse-scene` or `data-warehouse-scene-trino` |
+| Workflow | Feature Flag |
+| ------------------------ | --------------------------------------------------------- |
+| Data Modeling | `ducklake-data-modeling-copy-workflow` |
+| Data Imports | `ducklake-data-imports-copy-workflow` |
+| Data Import Registration | `data-warehouse-scene` or `managed-warehouse-trino-query` |
The data-import copy and registration paths target the same stable DuckLake table. An organization with either managed warehouse flag enabled runs registration. Disable `ducklake-data-imports-copy-workflow` for its projects to avoid both paths applying the same import. If both run, the last atomic table swap wins.
-The two organization flags also select the Data ops variant. `data-warehouse-scene-trino` gives the Trino variant and wins when both are on. `data-warehouse-scene` alone gives the DuckDB variant. `data_ops_variant` in `presentation/views.py` is the single backend implementation of that rule.
+The two organization flags also select the Data ops variant. `managed-warehouse-trino-query` gives the Trino variant and wins when both are on. `data-warehouse-scene` alone gives the DuckDB variant. `data_ops_variant` in `presentation/views.py` is the single backend implementation of that rule.
## Data Ops workflow status
diff --git a/products/managed_warehouse/backend/facade/feature_flags.py b/products/managed_warehouse/backend/facade/feature_flags.py
index 15b8b97c6bbd..cf1004202adb 100644
--- a/products/managed_warehouse/backend/facade/feature_flags.py
+++ b/products/managed_warehouse/backend/facade/feature_flags.py
@@ -1,5 +1,5 @@
DATA_WAREHOUSE_SCENE_FLAG = "data-warehouse-scene"
-DATA_WAREHOUSE_SCENE_TRINO_FLAG = "data-warehouse-scene-trino"
+MANAGED_TRINO_QUERY_FLAG = "managed-warehouse-trino-query"
# Either flag gives an organization the managed warehouse.
-MANAGED_WAREHOUSE_ACCESS_FLAGS = (DATA_WAREHOUSE_SCENE_TRINO_FLAG, DATA_WAREHOUSE_SCENE_FLAG)
+MANAGED_WAREHOUSE_ACCESS_FLAGS = (MANAGED_TRINO_QUERY_FLAG, DATA_WAREHOUSE_SCENE_FLAG)
DATA_MODELING_SHADOW_FLAG = "managed-warehouse-data-modeling-shadow"
diff --git a/products/managed_warehouse/backend/facade/query_execution.py b/products/managed_warehouse/backend/facade/query_execution.py
new file mode 100644
index 000000000000..8072a6324cb5
--- /dev/null
+++ b/products/managed_warehouse/backend/facade/query_execution.py
@@ -0,0 +1,46 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from posthog.schema import HogQLQuery, HogQLQueryResponse
+
+ from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+ from posthog.hogql.timings import HogQLTimings
+
+ from posthog.models import Team, User
+
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+
+def validate_managed_trino_query(query: HogQLQuery, team: Team, user: User | None) -> None:
+ from products.managed_warehouse.backend.query_execution import (
+ validate_managed_trino_query as validate, # noqa: PLC0415 -- query compilation is optional during Django startup
+ )
+
+ validate(query, team, user)
+
+
+def execute_managed_trino_query(
+ query: HogQLQuery,
+ *,
+ team: Team,
+ user: User | None,
+ user_access_control: UserAccessControl | None,
+ settings: HogQLGlobalSettings,
+ timings: HogQLTimings,
+ limit_context: LimitContext | None,
+) -> HogQLQueryResponse:
+ from products.managed_warehouse.backend.query_execution import (
+ execute_managed_trino_query as execute, # noqa: PLC0415 -- query compilation is optional during Django startup
+ )
+
+ return execute(
+ query,
+ team=team,
+ user=user,
+ user_access_control=user_access_control,
+ settings=settings,
+ timings=timings,
+ limit_context=limit_context,
+ )
diff --git a/products/managed_warehouse/backend/facade/sql_editor.py b/products/managed_warehouse/backend/facade/sql_editor.py
index bc7507d1964b..1562d8a0bd35 100644
--- a/products/managed_warehouse/backend/facade/sql_editor.py
+++ b/products/managed_warehouse/backend/facade/sql_editor.py
@@ -1,5 +1,23 @@
+from typing import TYPE_CHECKING
+
+from products.managed_warehouse.backend.logic.sql_editor import managed_warehouse_sql_editor_uses_trino
from products.managed_warehouse.backend.logic.sql_editor_credentials import (
resolve_managed_warehouse_postgres_connection,
)
-__all__ = ["resolve_managed_warehouse_postgres_connection"]
+__all__ = [
+ "managed_trino_adapter",
+ "managed_warehouse_sql_editor_uses_trino",
+ "resolve_managed_warehouse_postgres_connection",
+]
+
+if TYPE_CHECKING:
+ from posthog.hogql.direct_sql.adapter import DirectSQLAdapter
+
+
+def managed_trino_adapter() -> "DirectSQLAdapter":
+ from products.managed_warehouse.backend.logic.sql_editor_trino import (
+ ManagedTrinoAdapter, # noqa: PLC0415 -- keeps optional query drivers off Django startup
+ )
+
+ return ManagedTrinoAdapter()
diff --git a/products/managed_warehouse/backend/logic/connection.py b/products/managed_warehouse/backend/logic/connection.py
index 313013c3bdde..66ca986afb2d 100644
--- a/products/managed_warehouse/backend/logic/connection.py
+++ b/products/managed_warehouse/backend/logic/connection.py
@@ -1,9 +1,10 @@
-"""Expose a managed Duckgres warehouse in the SQL editor as a Postgres connection.
+"""Expose a managed warehouse in the SQL editor using a stable source identity.
-Each member team gets a Postgres ``ExternalDataSource`` whose short-lived Duckgres
-credential is resolved when a connection is opened. Duckgres root sees every schema in
-the warehouse, so the connection discovers and exposes the whole org catalog without
-per-team namespace configuration. Setup happens in two steps:
+The persisted Postgres source identity remains compatible with existing saved queries
+and lifecycle jobs. The organization's Data ops flag selects Trino or Duckgres at
+connection acquisition and schema discovery. Both use organization warehouse grants,
+so discovery exposes the whole org catalog without per-team namespace configuration.
+Setup happens in two steps:
1. ``ensure_managed_warehouse_direct_source`` creates the source row after explicit
successful provision or onboarding, so the connection appears immediately.
@@ -34,8 +35,9 @@ from posthog.dataclasses import frozen
from posthog.models.organization import Organization
from posthog.models.team.team import Team
-from products.data_warehouse.backend.facade.api import reconcile_postgres_schemas
+from products.data_warehouse.backend.facade.api import reconcile_managed_trino_schemas, reconcile_postgres_schemas
from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseSourceAuth
+from products.managed_warehouse.backend.logic.sql_editor import managed_warehouse_sql_editor_uses_trino
from products.managed_warehouse.backend.logic.sql_editor_credentials import (
MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
resolve_managed_warehouse_postgres_connection,
@@ -49,7 +51,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSchema,
ExternalDataSource,
)
-from products.warehouse_sources.backend.facade.source_management import SourceRegistry
+from products.warehouse_sources.backend.facade.source_management import SourceRegistry, SourceSchema
from products.warehouse_sources.backend.facade.types import (
ExternalDataSourceAccessMethod,
ExternalDataSourceCreatedVia,
@@ -368,6 +370,7 @@ def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str |
lifecycle_snapshot = _lifecycle_snapshot(organization_id)
if not lifecycle_snapshot.desired_active:
return
+ trino_enabled = managed_warehouse_sql_editor_uses_trino(organization_id)
with transaction.atomic():
# Plain read on purpose — see ensure_managed_warehouse_direct_source for why the
# team row must never be locked from these periodic sweeps.
@@ -381,47 +384,28 @@ def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str |
source_id = source.id
source_api_version = source.api_version
credential_kind = _credential_kind(source)
+ use_trino = source.is_dynamic_managed_warehouse and trino_enabled
excluded_schemas = internal_schemas()
- source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
try:
- dynamic_connection = resolve_managed_warehouse_postgres_connection(
- source_auth=_source_auth(source),
- organization_id=organization_id,
- team_id=team_id,
- principal=_schema_discovery_principal(team_id),
- )
- source_config = (
- {
- "host": dynamic_connection.host,
- "port": dynamic_connection.port,
- "database": dynamic_connection.database,
- "user": dynamic_connection.username,
- "password": dynamic_connection.password,
- }
- if dynamic_connection is not None
- else dict(source.job_inputs or {})
- )
- config = source_impl.parse_config(source_config)
- discovered = source_impl.get_schemas(
- config,
- team_id,
- api_version=source_impl.resolve_api_version(source_api_version),
- require_ssl=dynamic_connection is not None and dynamic_connection.sslmode == "require",
- )
+ if use_trino:
+ from products.managed_warehouse.backend.logic.sql_editor_trino import (
+ discover_managed_trino_schemas, # noqa: PLC0415 -- optional Trino drivers load only for Trino discovery
+ )
+
+ discovered = discover_managed_trino_schemas(str(organization_id), team_id)
+ else:
+ discovered = _discover_postgres_schemas(source, organization_id, team_id, source_api_version)
except Exception:
- # A provisioning or briefly unreachable warehouse fails here on every periodic sweep;
- # skip and let the next run retry rather than surfacing a task error each time.
logger.warning("Managed warehouse introspection failed; will retry", team_id=team_id, exc_info=True)
return
source_schemas = [schema for schema in discovered if (schema.source_schema or "") not in excluded_schemas]
+ trino_still_enabled = managed_warehouse_sql_editor_uses_trino(organization_id)
with transaction.atomic():
if _lifecycle_snapshot(organization_id, lock=True) != lifecycle_snapshot:
return
- # Plain read on purpose — this atomic block runs get_or_create loops and
- # reconcile_postgres_schemas and can hold its locks for minutes; taking the team
- # row here would stall every writer for the team the whole time.
+ # A team row lock would block unrelated FK inserts throughout catalog reconciliation.
team = Team.objects.only("id").filter(id=team_id, organization_id=organization_id).first()
if team is None:
return
@@ -436,9 +420,9 @@ def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str |
)
.first()
)
- if source is None:
+ if source is None or _credential_kind(source) != credential_kind:
return
- if _credential_kind(source) != credential_kind:
+ if use_trino != (source.is_dynamic_managed_warehouse and trino_still_enabled):
return
for schema in source_schemas:
@@ -454,7 +438,40 @@ def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str |
schema_model.should_sync = True
schema_model.save(update_fields=["deleted", "deleted_at", "should_sync", "updated_at"])
- reconcile_postgres_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+ if use_trino:
+ reconcile_managed_trino_schemas(source_id=source.id, source_schemas=source_schemas, team_id=team_id)
+ else:
+ reconcile_postgres_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
+
+def _discover_postgres_schemas(
+ source: ExternalDataSource, organization_id: str | UUID, team_id: int, source_api_version: str | None
+) -> list[SourceSchema]:
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
+ dynamic_connection = resolve_managed_warehouse_postgres_connection(
+ source_auth=_source_auth(source),
+ organization_id=organization_id,
+ team_id=team_id,
+ principal=_schema_discovery_principal(team_id),
+ )
+ source_config = (
+ {
+ "host": dynamic_connection.host,
+ "port": dynamic_connection.port,
+ "database": dynamic_connection.database,
+ "user": dynamic_connection.username,
+ "password": dynamic_connection.password,
+ }
+ if dynamic_connection is not None
+ else dict(source.job_inputs or {})
+ )
+ config = source_impl.parse_config(source_config)
+ return source_impl.get_schemas(
+ config,
+ team_id,
+ api_version=source_impl.resolve_api_version(source_api_version),
+ require_ssl=dynamic_connection is not None and dynamic_connection.sslmode == "require",
+ )
def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:
diff --git a/products/managed_warehouse/backend/logic/sql_editor.py b/products/managed_warehouse/backend/logic/sql_editor.py
new file mode 100644
index 000000000000..71cfec051fd9
--- /dev/null
+++ b/products/managed_warehouse/backend/logic/sql_editor.py
@@ -0,0 +1,17 @@
+from uuid import UUID
+
+from posthog.ph_client import feature_enabled_or_false
+
+from products.managed_warehouse.backend.facade.feature_flags import MANAGED_TRINO_QUERY_FLAG
+
+
+def managed_warehouse_sql_editor_uses_trino(organization_id: UUID | str) -> bool:
+ org_id = str(organization_id)
+ return feature_enabled_or_false(
+ MANAGED_TRINO_QUERY_FLAG,
+ org_id,
+ groups={"organization": org_id},
+ group_properties={"organization": {"id": org_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
diff --git a/products/managed_warehouse/backend/logic/sql_editor_trino.py b/products/managed_warehouse/backend/logic/sql_editor_trino.py
new file mode 100644
index 000000000000..f9a5a3ce1c10
--- /dev/null
+++ b/products/managed_warehouse/backend/logic/sql_editor_trino.py
@@ -0,0 +1,99 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from posthog.hogql.constants import HogQLDialect
+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult
+from posthog.hogql.direct_sql.trino_adapter import (
+ DIRECT_TRINO_DEFAULT_STATEMENT_TIMEOUT_SECONDS,
+ TrinoQueryRequest,
+ bounded_trino_cursor,
+ ensure_read_only_raw_trino_statement,
+ execute_trino_query,
+)
+from posthog.hogql.errors import ExposedHogQLError
+
+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseTrinoConnectionUnavailable
+from products.managed_warehouse.backend.logic.sql_editor import managed_warehouse_sql_editor_uses_trino
+from products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino
+from products.warehouse_sources.backend.facade.source_management import SourceSchema, discover_trino_catalog
+
+if TYPE_CHECKING:
+ from posthog.models import Team
+
+ from products.warehouse_sources.backend.facade.models import ExternalDataSource
+
+
+MANAGED_TRINO_SCHEMA_DISCOVERY_TIMEOUT_SECONDS = 60
+
+
+class ManagedTrinoAdapter:
+ engine = "trino"
+ dialect: HogQLDialect | None = "trino"
+
+ def prepare_raw_sql(self, sql: str) -> str:
+ return ensure_read_only_raw_trino_statement(sql)
+
+ # nosemgrep: tuple-return-prefer-dataclass -- DirectSQLAdapter requires an implementation/config tuple.
+ def validate_source_config(self, source: ExternalDataSource, team: Team) -> tuple[None, None]:
+ if (
+ source.team_id != team.pk
+ or source.deleted
+ or not source.is_dynamic_managed_warehouse
+ or not managed_warehouse_sql_editor_uses_trino(team.organization_id)
+ ):
+ raise ExposedHogQLError(
+ "This managed Trino connection is unavailable. Refresh the SQL editor and try again."
+ )
+ return None, None
+
+ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:
+ self.validate_source_config(request.source, request.team)
+ if request.principal is None:
+ raise ExposedHogQLError("Sign in to query the managed warehouse.")
+ try:
+ return execute_trino_query(
+ TrinoQueryRequest(
+ sql=request.sql,
+ values=request.values,
+ timeout_seconds=request.settings.max_execution_time
+ or DIRECT_TRINO_DEFAULT_STATEMENT_TIMEOUT_SECONDS,
+ timings=request.timings,
+ team_id=request.team.pk,
+ debug=request.debug,
+ cancellation_token=request.cancellation_token,
+ ),
+ connect_managed_warehouse_trino(str(request.team.organization_id), principal=request.principal.value),
+ )
+ except (ExposedHogQLError, ManagedWarehouseTrinoConnectionUnavailable) as error:
+ if not isinstance(error, ManagedWarehouseTrinoConnectionUnavailable) and not isinstance(
+ error.__cause__, ManagedWarehouseTrinoConnectionUnavailable
+ ):
+ raise
+ raise ExposedHogQLError("Trino is not ready for this warehouse. Try again later.") from error
+
+
+def discover_managed_trino_schemas(organization_id: str, team_id: int) -> list[SourceSchema]:
+ with connect_managed_warehouse_trino(
+ organization_id, principal=f"posthog:sql-editor-schema-discovery:team:{team_id}"
+ ) as connection:
+ with bounded_trino_cursor(connection, MANAGED_TRINO_SCHEMA_DISCOVERY_TIMEOUT_SECONDS, team_id=team_id) as (
+ cursor,
+ watchdog,
+ ):
+ if not connection.catalog:
+ raise ManagedWarehouseTrinoConnectionUnavailable("Trino did not return a warehouse catalog")
+ tables = discover_trino_catalog(cursor, catalog=connection.catalog)
+ watchdog.check()
+ return [
+ SourceSchema(
+ name=f"{table.schema}.{table.name}",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[(column.name, column.data_type, column.nullable) for column in table.columns],
+ source_catalog=table.catalog,
+ source_schema=table.schema,
+ source_table_name=table.name,
+ )
+ for table in tables
+ ]
diff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.py
index fd6f5bd51c09..1e29048af702 100644
--- a/products/managed_warehouse/backend/presentation/views.py
+++ b/products/managed_warehouse/backend/presentation/views.py
@@ -27,10 +27,7 @@ from rest_framework.response import Response
from posthog.security.outbound_proxy import internal_requests
-from products.managed_warehouse.backend.facade.feature_flags import (
- DATA_WAREHOUSE_SCENE_FLAG,
- DATA_WAREHOUSE_SCENE_TRINO_FLAG,
-)
+from products.managed_warehouse.backend.facade.feature_flags import DATA_WAREHOUSE_SCENE_FLAG, MANAGED_TRINO_QUERY_FLAG
from products.managed_warehouse.backend.presentation import hogtower
logger = structlog.get_logger(__name__)
@@ -153,7 +150,7 @@ def data_ops_variant(organization_id: UUID | str) -> DataOpsVariant | None:
The Trino flag wins when both are on, so an organization never moves between variants
because of Trino's state.
"""
- if _organization_flag_enabled(DATA_WAREHOUSE_SCENE_TRINO_FLAG, organization_id):
+ if _organization_flag_enabled(MANAGED_TRINO_QUERY_FLAG, organization_id):
return "trino"
if _organization_flag_enabled(DATA_WAREHOUSE_SCENE_FLAG, organization_id):
return "duckdb"
diff --git a/products/managed_warehouse/backend/query_execution.py b/products/managed_warehouse/backend/query_execution.py
new file mode 100644
index 000000000000..610cf6644aa3
--- /dev/null
+++ b/products/managed_warehouse/backend/query_execution.py
@@ -0,0 +1,131 @@
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+import posthoganalytics
+
+from posthog.schema import HogQLQuery, HogQLQueryResponse
+
+from posthog.hogql import ast
+from posthog.hogql.constants import LimitContext
+from posthog.hogql.direct_sql.trino_adapter import (
+ DIRECT_TRINO_DEFAULT_STATEMENT_TIMEOUT_SECONDS,
+ TrinoQueryRequest,
+ ensure_read_only_raw_trino_statement,
+ execute_trino_query,
+)
+from posthog.hogql.errors import ExposedHogQLError
+
+from posthog.clickhouse.query_tagging import get_query_tags
+from posthog.direct_query_cancellation import build_direct_query_cancellation_token
+from posthog.hogql_queries.paginators import HogQLHasMorePaginator
+
+from products.managed_warehouse.backend.facade.contracts import TrinoExpansionMode
+from products.managed_warehouse.backend.facade.feature_flags import MANAGED_TRINO_QUERY_FLAG
+from products.managed_warehouse.backend.trino_compiler import TrinoTargetUnavailable, compile_hogql_to_trino_sql
+from products.managed_warehouse.backend.trino_connection import connect_managed_warehouse_trino
+
+if TYPE_CHECKING:
+ from posthog.hogql.constants import HogQLGlobalSettings
+ from posthog.hogql.timings import HogQLTimings
+
+ from posthog.models import Team, User
+
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
+
+def validate_managed_trino_query(query: HogQLQuery, team: Team, user: User | None) -> None:
+ if user is None or not user.is_authenticated:
+ raise ExposedHogQLError("Sign in to run a query against hosted Trino.")
+ org_id = str(team.organization_id)
+ try:
+ enabled = posthoganalytics.feature_enabled(
+ MANAGED_TRINO_QUERY_FLAG,
+ org_id,
+ groups={"organization": org_id},
+ group_properties={"organization": {"id": org_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ except Exception:
+ enabled = False
+ if not enabled:
+ raise ExposedHogQLError(
+ "Hosted Trino queries are not enabled for this organization. Select PostHog to run this query."
+ )
+ if query.connectionId or query.sendRawQuery:
+ raise ExposedHogQLError("Hosted Trino runs HogQL queries. Clear the external connection and raw SQL mode.")
+
+
+def execute_managed_trino_query(
+ query: HogQLQuery,
+ *,
+ team: Team,
+ user: User | None,
+ user_access_control: UserAccessControl | None,
+ settings: HogQLGlobalSettings,
+ timings: HogQLTimings,
+ limit_context: LimitContext | None,
+) -> HogQLQueryResponse:
+ validate_managed_trino_query(query, team, user)
+ assert user is not None
+ paginator: HogQLHasMorePaginator | None = None
+
+ def paginate(parsed: ast.SelectQuery | ast.SelectSetQuery) -> ast.SelectQuery | ast.SelectSetQuery:
+ nonlocal paginator
+ if limit_context == LimitContext.SQL_ALERT:
+ paginator = HogQLHasMorePaginator.from_alert_query(parsed, limit_context=limit_context)
+ elif isinstance(parsed, ast.SelectQuery) and not parsed.limit:
+ paginator = HogQLHasMorePaginator.from_limit_context(limit_context=limit_context or LimitContext.QUERY)
+ return paginator.paginate(parsed) if paginator is not None else parsed
+
+ try:
+ with timings.measure("trino_compile"):
+ compiled = compile_hogql_to_trino_sql(
+ team.pk,
+ query,
+ team=team,
+ user=user,
+ user_access_control=user_access_control,
+ expansion_mode=TrinoExpansionMode.DJANGO,
+ include_hogql=True,
+ limit_top_select=True,
+ limit_context=limit_context,
+ select_transform=paginate,
+ )
+ except TrinoTargetUnavailable as error:
+ raise ExposedHogQLError("Hosted Trino is not ready for this project. Try again later.") from error
+ tags = get_query_tags()
+ cancellation_token = (
+ build_direct_query_cancellation_token(tags.client_query_id, str(tags.celery_task_id))
+ if tags.client_query_id is not None and tags.celery_task_id is not None
+ else None
+ )
+ result = execute_trino_query(
+ TrinoQueryRequest(
+ sql=ensure_read_only_raw_trino_statement(compiled.sql),
+ values=compiled.values,
+ timeout_seconds=settings.max_execution_time or DIRECT_TRINO_DEFAULT_STATEMENT_TIMEOUT_SECONDS,
+ timings=timings,
+ team_id=team.pk,
+ cancellation_token=cancellation_token,
+ ),
+ connect_managed_warehouse_trino(
+ str(team.organization_id), principal=f"posthog:sql-editor:team:{team.pk}:user:{user.pk}"
+ ),
+ )
+ response = HogQLQueryResponse(
+ query=query.query,
+ hogql=compiled.hogql,
+ clickhouse=compiled.sql,
+ results=result.results,
+ columns=result.print_columns,
+ types=result.types,
+ error=result.error,
+ timings=timings.to_list(),
+ modifiers=query.modifiers,
+ )
+ if paginator is not None:
+ paginator.response = response
+ return response.model_copy(update={**paginator.response_params(), "results": paginator.trim_results()})
+ return response
diff --git a/products/managed_warehouse/backend/tests/api/test_presentation.py b/products/managed_warehouse/backend/tests/api/test_presentation.py
index d62c0c704f30..796aedf6df44 100644
--- a/products/managed_warehouse/backend/tests/api/test_presentation.py
+++ b/products/managed_warehouse/backend/tests/api/test_presentation.py
@@ -41,8 +41,8 @@ def _onboarding_side_effects():
@pytest.mark.parametrize(
"enabled_flags, expected_variant",
[
- ({"data-warehouse-scene-trino"}, "trino"),
- ({"data-warehouse-scene-trino", "data-warehouse-scene"}, "trino"),
+ ({"managed-warehouse-trino-query"}, "trino"),
+ ({"managed-warehouse-trino-query", "data-warehouse-scene"}, "trino"),
({"data-warehouse-scene"}, "duckdb"),
(set(), None),
],
@@ -57,7 +57,7 @@ def test_data_ops_variant_prefers_the_trino_flag(
assert managed_warehouse.data_ops_variant(organization_id) == expected_variant
assert managed_warehouse.is_enabled(organization_id) is (expected_variant is not None)
mock_feature_enabled.assert_any_call(
- "data-warehouse-scene-trino",
+ "managed-warehouse-trino-query",
str(organization_id),
groups={"organization": str(organization_id)},
group_properties={"organization": {"id": str(organization_id)}},
diff --git a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
index a9a7b88def7d..ac68bf446511 100644
--- a/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
+++ b/products/managed_warehouse/backend/tests/temporal/test_ducklake_register_data_imports_workflow.py
@@ -57,9 +57,9 @@ def _cp_no_rows():
"enabled_flags, failing_flags, expected",
[
({"data-warehouse-scene"}, set(), True),
- ({"data-warehouse-scene-trino"}, set(), True),
+ ({"managed-warehouse-trino-query"}, set(), True),
(set(), set(), False),
- ({"data-warehouse-scene"}, {"data-warehouse-scene-trino"}, True),
+ ({"data-warehouse-scene"}, {"managed-warehouse-trino-query"}, True),
],
)
async def test_registration_gate_accepts_either_managed_warehouse_flag(
diff --git a/products/managed_warehouse/backend/tests/test_connection.py b/products/managed_warehouse/backend/tests/test_connection.py
index 79731a06bc85..c6ed8e0bc281 100644
--- a/products/managed_warehouse/backend/tests/test_connection.py
+++ b/products/managed_warehouse/backend/tests/test_connection.py
@@ -1,3 +1,4 @@
+from contextlib import nullcontext
from copy import deepcopy
from typing import TypedDict
@@ -11,6 +12,7 @@ from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
from posthog.hogql.direct_connection import get_direct_connection_source
+from posthog.hogql.errors import ExposedHogQLError
from posthog.hogql.query import HogQLQueryExecutor
from posthog.models import Organization, Team
@@ -734,6 +736,68 @@ def _source_schema(table_name: str, source_schema: str = "posthog") -> SourceSch
@pytest.mark.django_db
class TestReconcileManagedWarehouseTables:
+ def test_flag_switch_reconciles_the_same_source_and_table_in_both_engines(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = _ensure(team)
+ transaction_depth = len(django_connection.savepoint_ids)
+
+ def trino_flag(*args: object, **kwargs: object) -> bool:
+ assert len(django_connection.savepoint_ids) == transaction_depth
+ return True
+
+ cursor = MagicMock()
+ cursor.fetchall.side_effect = [
+ [("posthog", "events")],
+ [("posthog", "events", "uuid", "varchar", "YES")],
+ ]
+ connection = MagicMock(catalog="org_example")
+ connection.cursor.return_value = cursor
+ with (
+ patch("posthoganalytics.feature_enabled", side_effect=trino_flag),
+ patch(
+ "products.managed_warehouse.backend.logic.sql_editor_trino.connect_managed_warehouse_trino",
+ return_value=nullcontext(connection),
+ ),
+ ):
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+ schema = ExternalDataSchema.objects.get(source=source, name="posthog.events")
+ assert schema.table is not None
+ table_id = schema.table_id
+ assert schema.table.url_pattern == "direct://trino"
+ assert schema.table.options["direct_trino_catalog"] == "org_example"
+ assert schema.table.columns is not None
+ assert schema.table.columns["uuid"]["hogql"] == "string"
+ source.refresh_from_db()
+ assert source.job_inputs == {}
+ assert source.is_dynamic_managed_warehouse
+
+ postgres_connection = ManagedWarehousePostgresConnection(
+ host=_CONNECTION["host"],
+ port=5432,
+ database="ducklake",
+ username="svc_reader",
+ password="example-secret",
+ sslmode="require",
+ )
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=False),
+ patch(
+ "products.managed_warehouse.backend.logic.connection.resolve_managed_warehouse_postgres_connection",
+ return_value=postgres_connection,
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ return_value=[_source_schema("events")],
+ ),
+ ):
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+ schema.refresh_from_db()
+ assert schema.table_id == table_id
+ assert schema.table is not None
+ assert schema.table.url_pattern == DIRECT_POSTGRES_URL_PATTERN
+ assert ExternalDataSource.objects.filter(team=team, deleted=False).count() == 1
+
def _setup(self) -> tuple[Organization, Team]:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
@@ -1665,3 +1729,60 @@ def test_source_recovery_scheduler_always_emits_the_generation_fenced_task() ->
with patch.object(ensure_managed_warehouse_direct_source_v2_task, "delay") as delay:
schedule_managed_warehouse_direct_source_ensure(team_id=42, organization_id="org-1", expected_generation=7)
delay.assert_called_once_with(team_id=42, organization_id="org-1", expected_generation=7)
+
+
[email protected]("operation", ["query", "discovery"])
+def test_deadline_bounds_polling_and_cleanup_without_masking_timeout(operation: str) -> None:
+ import json
+ from contextlib import nullcontext
+
+ import requests
+ from trino.dbapi import connect
+
+ from posthog.hogql.direct_sql.trino_adapter import TrinoQueryRequest, execute_trino_query
+ from posthog.hogql.timings import HogQLTimings
+
+ from products.managed_warehouse.backend.logic.sql_editor_trino import discover_managed_trino_schemas
+
+ clock = [0.0]
+ calls: list[tuple[str, object]] = []
+ session = requests.Session()
+
+ def send(request: requests.PreparedRequest, **kwargs: object) -> requests.Response:
+ calls.append((request.method or "", kwargs["timeout"]))
+ if request.method == "DELETE":
+ raise requests.ReadTimeout("cleanup timed out")
+ assert request.method == "POST"
+ clock[0] = 61
+ response = requests.Response()
+ response.status_code = 200
+ response._content = json.dumps(
+ {
+ "id": "query",
+ "infoUri": "https://trino.example.com/query",
+ "nextUri": "https://trino.example.com/next",
+ "stats": {},
+ "data": [],
+ }
+ ).encode()
+ return response
+
+ connection = connect(host="trino.example.com", user="test", catalog="example", http_session=session)
+ with (
+ patch.object(session, "send", side_effect=send),
+ patch("posthog.hogql.direct_sql.trino_adapter.time.monotonic", side_effect=lambda: clock[0]),
+ pytest.raises(ExposedHogQLError, match="Trino query timed out"),
+ ):
+ if operation == "query":
+ execute_trino_query(
+ TrinoQueryRequest(sql="SELECT 1", values=None, timeout_seconds=60, timings=HogQLTimings(), team_id=1),
+ nullcontext(connection),
+ )
+ else:
+ with patch(
+ "products.managed_warehouse.backend.logic.sql_editor_trino.connect_managed_warehouse_trino",
+ return_value=nullcontext(connection),
+ ):
+ discover_managed_trino_schemas("example-org", 1)
+ assert [method for method, _ in calls] == ["POST", "DELETE"]
+ assert calls[-1][1] == 0.5
diff --git a/products/managed_warehouse/backend/tests/test_query_execution.py b/products/managed_warehouse/backend/tests/test_query_execution.py
new file mode 100644
index 000000000000..3a20d7c4c8d9
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_query_execution.py
@@ -0,0 +1,139 @@
+from contextlib import nullcontext
+from uuid import UUID
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import HogQLQuery
+
+from posthog.hogql.constants import HogQLGlobalSettings, LimitContext
+from posthog.hogql.errors import ExposedHogQLError
+from posthog.hogql.timings import HogQLTimings
+
+from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode
+from posthog.models import Organization, Team, User
+
+from products.managed_warehouse.backend.facade.contracts import (
+ ManagedWarehouseTableNames,
+ ManagedWarehouseTeamMembership,
+)
+from products.managed_warehouse.backend.query_execution import execute_managed_trino_query, validate_managed_trino_query
+
+
+def team() -> Team:
+ return Team(id=7, organization_id=UUID("00000000-0000-0000-0000-000000000001"))
+
+
+def test_default_requests_keep_normal_execution_without_evaluating_the_flag(team: Team) -> None:
+ runner = object.__new__(HogQLQueryRunner)
+ runner.query = HogQLQuery(query="SELECT 1")
+ runner.team = team
+ runner.user = User(id=9)
+ runner._direct_connection_validated = False
+ with patch("posthoganalytics.feature_enabled", side_effect=AssertionError("default query evaluated hosted flag")):
+ runner._validate_direct_connection()
+ assert runner.query.executionTarget is None
+
+
[email protected]("flag_result", [False, None, RuntimeError("flag unavailable")])
+def test_disabled_target_rejects_cached_requests(team: Team, flag_result: object) -> None:
+ runner = object.__new__(HogQLQueryRunner)
+ runner.query = HogQLQuery(query="SELECT 1", executionTarget="managed_trino")
+ runner.team = team
+ runner.user = User(id=9)
+ with (
+ patch(
+ "posthoganalytics.feature_enabled",
+ side_effect=flag_result if isinstance(flag_result, Exception) else None,
+ return_value=flag_result,
+ ),
+ patch.object(AnalyticsQueryRunner, "run") as cached_run,
+ pytest.raises(ExposedHogQLError, match="not enabled"),
+ ):
+ runner.run(execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE)
+ cached_run.assert_not_called()
+
+
+ "user, connection_id, raw", [(None, None, False), (User(id=9), "external-source", False), (User(id=9), None, True)]
+)
+def test_hosted_target_rejects_unauthenticated_and_external_modes(
+ team: Team, user: User | None, connection_id: str | None, raw: bool
+) -> None:
+ with patch("posthoganalytics.feature_enabled", return_value=True), pytest.raises(ExposedHogQLError):
+ validate_managed_trino_query(
+ HogQLQuery(query="SELECT 1", connectionId=connection_id, sendRawQuery=raw), team, user
+ )
+
+
+ "limit_clause, limit_context, row_count, expected_limit, has_more",
+ [
+ ("", LimitContext.QUERY, 1, 100, False),
+ ("", LimitContext.QUERY, 101, 100, True),
+ (" LIMIT 1", LimitContext.SQL_ALERT, 1, 1, False),
+ (" LIMIT 1", LimitContext.SQL_ALERT, 2, 1, True),
+ ],
+)
+def test_live_query_binds_values_and_uses_hosted_service_credentials(
+ team: Team, limit_clause: str, limit_context: LimitContext, row_count: int, expected_limit: int, has_more: bool
+) -> None:
+ organization = Organization.objects.create(id=team.organization_id, name="Example organization")
+ team = Team.objects.create(organization=organization)
+ user = User.objects.create(email="[email protected]")
+ membership = ManagedWarehouseTeamMembership(
+ team_id=team.pk,
+ organization_id=str(organization.pk),
+ schema_name="production",
+ enabled=True,
+ backfill_enabled=True,
+ table_names=ManagedWarehouseTableNames(
+ events_table="events_example", persons_table="persons_example", data_imports_schema="imports_example"
+ ),
+ earliest_event_date=None,
+ )
+ cursor = MagicMock()
+ cursor.fetchmany.return_value = [("quoted ' value",)] * row_count
+ cursor.description = [("value", "varchar")]
+ connection = MagicMock()
+ connection.cursor.return_value = cursor
+ with (
+ patch("posthoganalytics.feature_enabled", return_value=True),
+ patch(
+ "products.managed_warehouse.backend.trino_compiler.get_ready_trino_catalog_name",
+ return_value="example_catalog",
+ ),
+ patch("products.managed_warehouse.backend.trino_compiler.get_org_team_membership", return_value=membership),
+ patch("products.managed_warehouse.backend.cp_teams.list_org_teams", return_value=[]),
+ patch(
+ "products.managed_warehouse.backend.query_execution.connect_managed_warehouse_trino",
+ return_value=nullcontext(connection),
+ ) as connect,
+ ):
+ response = execute_managed_trino_query(
+ HogQLQuery(
+ query="SELECT {value} AS value" + limit_clause,
+ values={"value": "quoted ' value"},
+ executionTarget="managed_trino",
+ ),
+ team=team,
+ user=user,
+ user_access_control=None,
+ settings=HogQLGlobalSettings(),
+ timings=HogQLTimings(),
+ limit_context=limit_context,
+ )
+ connect.assert_called_once_with(
+ str(team.organization_id), principal=f"posthog:sql-editor:team:{team.pk}:user:{user.pk}"
+ )
+ cursor.execute.assert_called_once_with(
+ f'SELECT ? AS "value" OFFSET 0 ROWS LIMIT {expected_limit + 1}', ["quoted ' value"]
+ )
+ cursor.close.assert_called_once()
+ assert response.results == [("quoted ' value",)] * min(row_count, expected_limit)
+ assert response.hasMore is has_more
+ assert response.limit == expected_limit
+ assert response.columns == ["value"]
diff --git a/products/managed_warehouse/backend/tests/test_trino_compiler.py b/products/managed_warehouse/backend/tests/test_trino_compiler.py
index df661dda849b..48222336e4a6 100644
--- a/products/managed_warehouse/backend/tests/test_trino_compiler.py
+++ b/products/managed_warehouse/backend/tests/test_trino_compiler.py
@@ -10,6 +10,7 @@ from structlog.testing import capture_logs
from posthog.schema import HogQLQuery
+from posthog.hogql.constants import LimitContext
from posthog.hogql.transforms.trino.manifest import (
TrinoCatalogManifest,
TrinoManifestColumn,
@@ -262,8 +263,9 @@ class TestCompileHogQLToTrinoSQL:
(" LIMIT 75000 OFFSET 3", " OFFSET 3 ROWS LIMIT 75000"),
],
)
+ @pytest.mark.parametrize("interactive", [False, True])
def test_populates_core_table_locators_from_control_plane_state(
- self, include_hogql: bool, limit_clause: str, trino_limit_clause: str
+ self, include_hogql: bool, limit_clause: str, trino_limit_clause: str, interactive: bool
) -> None:
organization = Organization.objects.create(name="trino-core-locators")
team = Team.objects.create(organization=organization)
@@ -286,13 +288,22 @@ class TestCompileHogQLToTrinoSQL:
team=team,
include_hogql=include_hogql,
expansion_mode=TrinoExpansionMode.DJANGO,
+ limit_top_select=interactive,
+ limit_context=LimitContext.QUERY,
)
+ if interactive:
+ if not limit_clause:
+ trino_limit_clause = " LIMIT 50000"
+ trino_limit_clause = trino_limit_clause.replace("75000", "50000")
+
assert compiled.sql == (
'SELECT "org_catalog"."posthog"."events_production"."event" '
'FROM "org_catalog"."posthog"."events_production"' + trino_limit_clause
)
assert compiled.values == {}
+ if interactive:
+ limit_clause = (limit_clause or " LIMIT 50000").replace("75000", "50000")
assert compiled.hogql == ("SELECT event FROM events" + limit_clause if include_hogql else None)
@pytest.mark.django_db
diff --git a/products/managed_warehouse/backend/trino_compiler.py b/products/managed_warehouse/backend/trino_compiler.py
index 886b32f311b9..204a031975c3 100644
--- a/products/managed_warehouse/backend/trino_compiler.py
+++ b/products/managed_warehouse/backend/trino_compiler.py
@@ -19,10 +19,13 @@ if TYPE_CHECKING:
from posthog.schema import HogQLQuery
from posthog.hogql import ast
+ from posthog.hogql.constants import LimitContext
from posthog.hogql.transforms.trino.manifest import PreparedTrinoCatalog, TrinoCatalogManifest
from posthog.models import Team, User
+ from products.access_control.backend.facade.user_access_control import UserAccessControl
+
logger = structlog.get_logger(__name__)
TRINO_COMPILATION_TOTAL = Counter(
@@ -209,6 +212,9 @@ def compile_hogql_to_trino_sql(
*,
team: Team | None = None,
user: User | None = None,
+ user_access_control: UserAccessControl | None = None,
+ limit_top_select: bool = False,
+ limit_context: LimitContext | None = None,
bypass_warehouse_access_control: bool = False,
include_hogql: bool = False,
expansion_mode: TrinoExpansionMode = TrinoExpansionMode.PURE,
@@ -280,6 +286,7 @@ def compile_hogql_to_trino_sql(
team_id,
team=team,
user=user,
+ user_access_control=user_access_control,
modifiers=query_modifiers,
# Preserve an explicit trusted-internal bypass; the public default remains fail-closed.
bypass_warehouse_access_control=bypass_warehouse_access_control,
@@ -310,8 +317,10 @@ def compile_hogql_to_trino_sql(
team_id=team_id,
team=team,
user=user,
+ user_access_control=user_access_control,
enable_select_queries=True,
- limit_top_select=False,
+ limit_top_select=limit_top_select,
+ limit_context=limit_context,
modifiers=query_modifiers,
# Match the access-controlled database above instead of widening it during resolution.
bypass_warehouse_access_control=bypass_warehouse_access_control,
@@ -327,8 +336,10 @@ def compile_hogql_to_trino_sql(
team_id=team_id,
team=team,
user=user,
+ user_access_control=user_access_control,
enable_select_queries=True,
- limit_top_select=False,
+ limit_top_select=limit_top_select,
+ limit_context=limit_context,
modifiers=query_modifiers,
bypass_warehouse_access_control=bypass_warehouse_access_control,
database=database,
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index ef5b6b9c607e..9be4f7d00a1a 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -5858,6 +5858,13 @@ export interface PathsV2ActorsQueryApi {
version?: number | null
}
+export type ExecutionTargetApi = (typeof ExecutionTargetApi)[keyof typeof ExecutionTargetApi]
+
+export const ExecutionTargetApi = {
+ Default: 'default',
+ ManagedTrino: 'managed_trino',
+} as const
+
export interface HogQLFiltersApi {
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilterApi | null
@@ -5954,6 +5961,8 @@ export type HogQLQueryApiVariables = { [key: string]: HogQLVariableApi } | null
export interface HogQLQueryApi {
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string | null
+ /** Compile and run this query against the hosted Trino target. */
+ executionTarget?: ExecutionTargetApi | null
explain?: boolean | null
/** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */
filters?: HogQLFiltersApi | null
diff --git a/products/warehouse_sources/backend/facade/source_management.py b/products/warehouse_sources/backend/facade/source_management.py
index d720ce3cb24e..9f4240ce559b 100644
--- a/products/warehouse_sources/backend/facade/source_management.py
+++ b/products/warehouse_sources/backend/facade/source_management.py
@@ -56,6 +56,7 @@ _LAZY = {
"pinned_host_kwargs": "sources.common.mixins",
"TemporaryHostResolutionError": "sources.common.mixins",
"SourceSchema": "sources.common.schema",
+ "discover_trino_catalog": "sources.trino.trino",
"build_default_schemas": "sources.common.schema",
"build_default_sync_settings": "sources.common.schema",
"RowFilterValidationError": "sources.common.sql",
diff --git a/products/warehouse_sources/backend/models/table.py b/products/warehouse_sources/backend/models/table.py
index eaf61778b053..9ae5f09a7b44 100644
--- a/products/warehouse_sources/backend/models/table.py
+++ b/products/warehouse_sources/backend/models/table.py
@@ -975,7 +975,12 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
keep_tuple_element_names=self.format in STRUCTURE_KEEPS_TUPLE_ELEMENT_NAMES,
)
- if self.external_data_source and self.external_data_source.is_direct_postgres:
+ is_managed_trino_table = (
+ self.external_data_source is not None
+ and self.external_data_source.is_managed_warehouse
+ and self.url_pattern == "direct://trino"
+ )
+ if self.external_data_source and self.external_data_source.is_direct_postgres and not is_managed_trino_table:
postgres_catalog = (
self.options.get(DIRECT_POSTGRES_CATALOG_OPTION)
if isinstance(self.options.get(DIRECT_POSTGRES_CATALOG_OPTION), str)
@@ -1116,7 +1121,7 @@ class DataWarehouseTable(CreatedMetaFields, UpdatedMetaFields, UUIDTModel, Delet
if (
self.external_data_source
and self.external_data_source.is_direct_query
- and self.external_data_source.direct_engine == "trino"
+ and (self.external_data_source.direct_engine == "trino" or is_managed_trino_table)
):
job_inputs = self.external_data_source.job_inputs or {}
trino_catalog = (
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
index ac0baf6231f3..8dee8bf21267 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source/connection_options.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from functools import cached_property
from typing import Any, cast
from django.db.models import Q
@@ -88,11 +89,7 @@ class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):
allow_null=True,
help_text="Default database schema used to group tables in the SQL editor.",
)
- engine = serializers.ChoiceField(
- source="connection_metadata.engine",
- read_only=True,
- allow_null=True,
- choices=helpers.DIRECT_CONNECTION_ENGINE_CHOICES,
+ engine = serializers.SerializerMethodField(
help_text="Backend engine detected for the direct connection.",
)
source_type = serializers.ChoiceField(
@@ -117,6 +114,21 @@ class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):
help_text="User-set description of the source, shown as its display name in the connection picker when set.",
)
+ @extend_schema_field(serializers.ChoiceField(choices=helpers.DIRECT_CONNECTION_ENGINE_CHOICES, allow_null=True))
+ def get_engine(self, source: ExternalDataSource) -> str | None:
+ if source.is_dynamic_managed_warehouse and self._managed_trino_enabled:
+ return "trino"
+ metadata = source.connection_metadata
+ return metadata.get("engine") if isinstance(metadata, dict) else None
+
+ @cached_property
+ def _managed_trino_enabled(self) -> bool:
+ from products.managed_warehouse.backend.facade.sql_editor import (
+ managed_warehouse_sql_editor_uses_trino, # noqa: PLC0415 -- flag evaluation is optional during startup
+ )
+
+ return managed_warehouse_sql_editor_uses_trino(self.context["team"].organization_id)
+
@extend_schema_field(serializers.BooleanField())
def get_supports_hogql(self, source: ExternalDataSource) -> bool:
# Function-local: keeps the direct-SQL driver imports off the django.setup() path.
@@ -230,7 +242,10 @@ class ExternalDataSourceConnectionOptionsMixin(base.ExternalDataSourceViewSetBas
serializer = ExternalDataSourceConnectionOptionSerializer(
options,
many=True,
- context={"builtin_managed_warehouse_source_id": managed_source.pk if managed_source is not None else None},
+ context={
+ "builtin_managed_warehouse_source_id": managed_source.pk if managed_source is not None else None,
+ "team": self.team,
+ },
)
return Response(status=status.HTTP_200_OK, data=serializer.data)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
index dc5a03926f9b..484abd3afa43 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/trino/trino.py
@@ -251,16 +251,22 @@ def connect_trino(config: TrinoSourceConfig, *, timezone: str | None = None) ->
def discover_trino_schemas(
cursor: Cursor, config: TrinoSourceConfig, names: list[str] | None = None
) -> list[DiscoveredTrinoTable]:
- escaped_catalog = config.catalog.replace(chr(34), chr(34) * 2)
+ return discover_trino_catalog(cursor, catalog=config.catalog, schema=config.schema, names=names)
+
+
+def discover_trino_catalog(
+ cursor: Cursor, *, catalog: str, schema: str | None = None, names: list[str] | None = None
+) -> list[DiscoveredTrinoTable]:
+ escaped_catalog = catalog.replace(chr(34), chr(34) * 2)
table_query = (
"SELECT table_schema, table_name "
f'FROM "{escaped_catalog}".information_schema.tables '
"WHERE table_schema <> 'information_schema'"
)
parameters: list[object] = []
- if config.schema:
+ if schema:
table_query += " AND table_schema = ?"
- parameters.append(config.schema)
+ parameters.append(schema)
table_query += " ORDER BY table_schema, table_name"
cursor.execute(table_query, parameters)
@@ -269,7 +275,7 @@ def discover_trino_schemas(
for schema_name, table_name in cursor.fetchall():
schema_name = str(schema_name)
table_name = str(table_name)
- display_name = table_name if config.schema else f"{schema_name}.{table_name}"
+ display_name = table_name if schema else f"{schema_name}.{table_name}"
if requested is not None and display_name not in requested:
continue
table_names_by_schema.setdefault(schema_name, []).append(table_name)
@@ -295,7 +301,7 @@ def discover_trino_schemas(
)
return [
DiscoveredTrinoTable(
- catalog=config.catalog,
+ catalog=catalog,
schema=schema_name,
name=table_name,
columns=tuple(columns),
diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.ts
index 68c92e934a17..4f148bcd23fd 100644
--- a/products/warehouse_sources/frontend/generated/api.schemas.ts
+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts
@@ -3520,16 +3520,6 @@ export const ExternalDataSourceAccessMethodEnumApi = {
Direct: 'direct',
} as const
-/**
- * * `duckdb` - duckdb
- * * `postgres` - postgres
- * * `mysql` - mysql
- * * `snowflake` - snowflake
- * * `redshift` - redshift
- * * `clickhouse` - clickhouse
- * * `motherduck` - motherduck
- * * `trino` - trino
- */
export type EngineEnumApi = (typeof EngineEnumApi)[keyof typeof EngineEnumApi]
export const EngineEnumApi = {
@@ -5553,16 +5543,7 @@ export interface ExternalDataSourceConnectionOptionApi {
readonly schema_name: string | null
/** @nullable */
readonly prefix: string | null
- /** Backend engine detected for the direct connection.
- *
- * * `duckdb` - duckdb
- * * `postgres` - postgres
- * * `mysql` - mysql
- * * `snowflake` - snowflake
- * * `redshift` - redshift
- * * `clickhouse` - clickhouse
- * * `motherduck` - motherduck
- * * `trino` - trino */
+ /** Backend engine detected for the direct connection. */
readonly engine: EngineEnumApi | null
/** The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').
*
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 0e1cbeee767e..ccffecd5b368 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -9176,7 +9176,7 @@
"openWorldHint": true,
"readOnlyHint": true
},
- "feature_flag": "data-warehouse-scene-trino"
+ "feature_flag": "managed-warehouse-trino-query"
},
"managed-warehouse-trino-monitoring-get": {
"description": "Get current Trino query activity for the active project's managed warehouse: queries in flight, running, queued, and blocked counts, concurrency and queue limits, and the in-flight queries with literal values removed from their SQL. Use this to inspect current workload. When `available` is false the live data could not be read, so the totals do not mean the warehouse is idle. These values describe operational activity, not invoiced usage.",
@@ -9191,7 +9191,7 @@
"openWorldHint": true,
"readOnlyHint": true
},
- "feature_flag": "data-warehouse-scene-trino"
+ "feature_flag": "managed-warehouse-trino-query"
},
"marketing-analytics-conversion-goals": {
"description": "List the configured marketing conversion goals for the current project. Each goal returns its conversion_goal_id — the value the explain, update and delete tools take — plus its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index 9f32153ce04a..cb863390bfa1 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -9555,7 +9555,7 @@
"openWorldHint": true,
"readOnlyHint": true
},
- "feature_flag": "data-warehouse-scene-trino"
+ "feature_flag": "managed-warehouse-trino-query"
},
"managed-warehouse-trino-monitoring-get": {
"description": "Get current Trino query activity for the active project's managed warehouse: queries in flight, running, queued, and blocked counts, concurrency and queue limits, and the in-flight queries with literal values removed from their SQL. Use this to inspect current workload. When `available` is false the live data could not be read, so the totals do not mean the warehouse is idle. These values describe operational activity, not invoiced usage.",
@@ -9570,7 +9570,7 @@
"openWorldHint": true,
"readOnlyHint": true
},
- "feature_flag": "data-warehouse-scene-trino"
+ "feature_flag": "managed-warehouse-trino-query"
},
"marketing-analytics-conversion-goals": {
"description": "List the configured marketing conversion goals for the current project. Each goal returns its conversion_goal_id — the value the explain, update and delete tools take — plus its kind (EventsNode / ActionsNode / DataWarehouseNode), target, last-30d count, and the integrated vs non-integrated split. Non-integrated breaks into two buckets with OPPOSITE fixes: events_without_utm_source (tag UTMs) vs events_with_unmatched_utm_source (add a custom source mapping). is_approximate is true when the 30d count may differ from the dashboard's attribution-windowed number.",
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 6f7c2daeb5a4..f9b19a6253cb 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7334,6 +7334,14 @@ export namespace Schemas {
version?: number | null;
}
+ export type ExecutionTarget = typeof ExecutionTarget[keyof typeof ExecutionTarget];
+
+
+ export const ExecutionTarget = {
+ Default: 'default',
+ ManagedTrino: 'managed_trino',
+ } as const;
+
export interface HogQLFilters {
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilter | null;
@@ -7510,6 +7518,8 @@ export namespace Schemas {
export interface HogQLQuery {
/** Optional id of a direct-query-capable external data source to run against instead of ClickHouse — a pure-direct source, or a synced source with direct query enabled. */
connectionId?: string | null;
+ /** Compile and run this query against the hosted Trino target. */
+ executionTarget?: ExecutionTarget | null;
explain?: boolean | null;
/** Extra filters applied to query via {filters} or the column-bound {filters(expr AS key, ...)} placeholder */
filters?: HogQLFilters | null;
@@ -40104,16 +40114,6 @@ export namespace Schemas {
version?: number | null;
}
- /**
- * * `duckdb` - duckdb
- * * `postgres` - postgres
- * * `mysql` - mysql
- * * `snowflake` - snowflake
- * * `redshift` - redshift
- * * `clickhouse` - clickhouse
- * * `motherduck` - motherduck
- * * `trino` - trino
- */
export type EngineEnum = typeof EngineEnum[keyof typeof EngineEnum];
@@ -48086,16 +48086,7 @@ export namespace Schemas {
readonly schema_name: string | null;
/** @nullable */
readonly prefix: string | null;
- /** Backend engine detected for the direct connection.
- *
- * * `duckdb` - duckdb
- * * `postgres` - postgres
- * * `mysql` - mysql
- * * `snowflake` - snowflake
- * * `redshift` - redshift
- * * `clickhouse` - clickhouse
- * * `motherduck` - motherduck
- * * `trino` - trino */
+ /** Backend engine detected for the direct connection. */
readonly engine: EngineEnum | null;
/** The source type (e.g. 'Postgres', 'MySQL', 'Snowflake').
*
diff --git a/services/mcp/tests/unit/tool-filtering.test.ts b/services/mcp/tests/unit/tool-filtering.test.ts
index d30b7ff458a3..ac14fd46b1dd 100644
--- a/services/mcp/tests/unit/tool-filtering.test.ts
+++ b/services/mcp/tests/unit/tool-filtering.test.ts
@@ -429,7 +429,7 @@ describe('Tool Filtering - API Scopes', () => {
it('should expose managed warehouse Trino monitoring only with its read scope and feature flag', async () => {
const trinoTools = ['managed-warehouse-trino-monitoring-get', 'managed-warehouse-trino-metric-history-get']
- const enabledOptions = { featureFlags: { 'data-warehouse-scene-trino': true } }
+ const enabledOptions = { featureFlags: { 'managed-warehouse-trino-query': true } }
const authorizedTools = await getToolsFromContext(createMockContext(['warehouse_view:read']), enabledOptions)
const wrongScopeTools = await getToolsFromContext(createMockContext(['query:read']), enabledOptions)
@@ -1088,7 +1088,7 @@ describe('Tool Filtering - Feature Flags', () => {
'scouts-tool-access',
'replay-vision-scanner-dashboard',
'metrics-dashboard-import',
- 'data-warehouse-scene-trino',
+ 'managed-warehouse-trino-query',
]
expect(allFlags).toEqual(expect.arrayContaining(branchFlags))
// The flags branches add are asserted on the line above and held out of the list and