:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(managed-warehouse): add built-in SQL editor connection (#82675)
Bill Guowei Yangaa0036966a23
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.mdindex 41b572ffb40a..15bb0cc602ab 100644--- a/docs/internal/managed-warehouse-sql-editor.md+++ b/docs/internal/managed-warehouse-sql-editor.md@@ -1,7 +1,22 @@# Managed warehouse connections in the SQL editor-Provisioning a managed warehouse creates a system-owned direct connection for each participating project. The connection uses a distinct Duckgres project-reader login and appears in the SQL editor's database chooser.+The `managed-warehouse-sql-editor` feature flag switches which managed warehouse connection appears for each project:-The project reader can query the project's event and person tables and every current or future table in its team, data-import, and modeled-data schemas. The exposed namespaces mirror the Duckgres org-team row (which credential setup never rewrites), so hand-set layouts such as legacy `posthog.events` tables stay in sync. Duckgres enforces the read-only project boundary for both PostgreSQL and Flight SQL queries.+- When disabled, which is the default, PostHog keeps the source as an ordinary external Duckgres connection. External-source access controls apply, the option uses DuckDB branding and source settings, and queries use the existing PostgreSQL direct adapter.+- When enabled, PostHog hides the external representation from the connection chooser. If the reserved source contains a configured Duckgres `project_reader` credential, it appears as `PostHog (Managed warehouse)` below `PostHog (ClickHouse)`. Every project member can use it without external-source access controls.-PostHog reconciles the connection's table catalog when the warehouse status is read (coalesced to once a minute) and in a twice-hourly periodic sweep. The sweep makes newly created tables visible without requiring a visit to Data ops; each reconcile opens a real warehouse session, which is why it is not more frequent. If a physical table is dropped and recreated with the same name, reconciliation revives its existing catalog entry.+Enabling the flag without a ready project reader shows neither representation. The flag only controls chooser visibility. It does not change a source row's adapter or access policy, revoke saved connection IDs, or create, rotate, or delete credentials or catalog metadata.++Duckgres enforces the reader's read-only, project-scoped query policy in built-in mode. PostHog requires the reserved source to be enabled, marked as a configured `project_reader`, and use the expected `posthog_team_<team_id>` login. Sources backed by the organization login and pending or malformed readers are not eligible for built-in mode. This integration assumes provisioning has already created the project reader.++A ready project-reader source always uses the built-in policy, even while hidden. Raw queries use a native pgwire adapter. The adapter uses the exact reader connection stored on the resolved source, sends one SQL statement unchanged, and does not build a HogQL database or load the third-party PostgreSQL source stack. It never falls back to the organization's stored login. Duckgres authorizes `project_reader` statements through its PostgreSQL query gateway, so raw statements must use PostgreSQL-compatible syntax. Queries that return more than 50,000 rows fail and ask the user to add a `LIMIT` clause. Non-raw queries continue through the PostgreSQL and HogQL path with the same source credential.++Hostname resolution is bounded to 15 seconds before libpq applies its per-attempt 15-second connection timeout. Canceling an asynchronous query signals the active pgwire connection instead of only revoking its Celery task.++A legacy source backed by the stored server login always remains an external connection, even while hidden from the chooser. It stays visible in external-source management, keeps external-source and table access controls, and uses the existing PostgreSQL direct adapter.++PostHog reconciles the legacy connection and a ready reader into separate table catalogs. A failure or missing credential in one mode does not block the other. Reconciliation runs when warehouse status is read, coalesced to once a minute, and in a twice-hourly periodic sweep. Duckgres limits reader discovery to the project's allowed namespaces. The sweep makes newly created tables visible without requiring a visit to Data ops. Each source reconcile opens a warehouse session, so it is not more frequent. If a physical table is dropped and recreated with the same name, reconciliation revives its existing catalog entry.++The configured source row is the local readiness marker for built-in mode. Query and picker paths use its encrypted reader connection directly. If the reader no longer exists in Duckgres, connection attempts fail without trying a broader credential.++Deploy this code to every web and Celery worker before provisioning project-reader rows. Older workers can mistake the newest reserved row for the legacy source and replace its credentials. Keep the feature flag disabled until a ready reader exists for the project.diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 55d939fd649d..907807c4f9f9 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -381,6 +381,7 @@ export const FEATURE_FLAGS = {MANAGED_MIGRATIONS_IAM_ROLE_AUTH: 'managed-migrations-iam-role-auth', // owner: #team-ingestion, gates IAM role auth for S3 batch importsMANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrationsMANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics+ MANAGED_WAREHOUSE_SQL_EDITOR: 'managed-warehouse-sql-editor', // owner: #team-managed-warehouse, gates managed warehouse connections in the SQL editorMARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analyticsMARKETING_ANALYTICS_ATTRIBUTION: 'marketing-analytics-attribution', // owner: @jabahamondes #team-web-analytics — gates the Attribution tabMARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute tablediff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.tsindex aaa847254d60..737d529a4615 100644--- a/frontend/src/queries/query.test.ts+++ b/frontend/src/queries/query.test.ts@@ -345,6 +345,20 @@ describe('query', () => {})})+ it('preserves a detail-only API error', async () => {+ jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce({+ data: {+ detail: 'This managed warehouse connection is no longer available. Select a source and run the query again.',+ code: 'managed_warehouse_connection_unavailable',+ },+ })++ await expect(pollForResults('test-query-id')).rejects.toMatchObject({+ detail: 'This managed warehouse connection is no longer available. Select a source and run the query again.',+ code: 'managed_warehouse_connection_unavailable',+ })+ })+it('handles undefined error message', async () => {jest.spyOn(api.queryStatus, 'get').mockRejectedValueOnce({data: {diff --git a/frontend/src/queries/query.ts b/frontend/src/queries/query.tsindex 43cc2e573792..d1cedfccce95 100644--- a/frontend/src/queries/query.ts+++ b/frontend/src/queries/query.ts@@ -139,11 +139,11 @@ export async function pollForResults(}} catch (e: any) {// Parse error message to extract clean message and code if present- const parsed = parseErrorMessage(e.data?.query_status?.error_message)+ const parsed = parseErrorMessage(e.data?.query_status?.error_message ?? e.data?.detail ?? e.detail)e.detail = parsed.message// Prefer the structured code from QueryStatus over one parsed out of the message- e.code = e.data?.query_status?.error_code ?? parsed.code ?? e.code+ e.code = e.data?.query_status?.error_code ?? e.data?.code ?? parsed.code ?? e.code// Attach queryId to error for downstream error handlinge.queryId = queryIddiff --git a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsxindex 2f3715a8a415..f41ad191b57d 100644--- a/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx+++ b/frontend/src/scenes/data-warehouse/editor/ConnectionSelector.tsx@@ -13,6 +13,7 @@ import {CONFIGURE_SOURCES,type ConnectionSelectOption,POSTHOG_WAREHOUSE,+ addHiddenSelectedConnectionOption,connectionSelectorLogic,getConnectionSelectorValue,} from './connectionSelectorLogic'@@ -37,7 +38,9 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.ElemuseOnMountEffect(() => {maybeLoadConnectionOptions()})- const connectionSelectorValue = getConnectionSelectorValue(+ const connectionSelectorValue = getConnectionSelectorValue(connectionOptionsLoading, selectedConnectionId)+ const displayedConnectionSelectOptions = addHiddenSelectedConnectionOption(+ connectionSelectOptions,connectionOptions,connectionOptionsLoading,selectedConnectionId@@ -95,7 +98,7 @@ export function ConnectionSelector({ tabId }: ConnectionSelectorProps): JSX.Elem} as typeof sourceQuery)syncUrlWithQuery()}}- options={connectionSelectOptions.map((group) => ({+ options={displayedConnectionSelectOptions.map((group) => ({options: group.options.map(toLemonSelectOption),}))}/>@@ -113,6 +116,7 @@ function toLemonSelectOption(option: ConnectionSelectOption): LemonSelectOption<value: option.value as string,label: option.label,icon,+ hidden: option.hidden,sideAction: option.managementUrl? {onClick: () => newInternalTab(option.managementUrl),diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsxindex 7360aea9df5d..f87cb4c87acc 100644--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx@@ -89,9 +89,10 @@ const MANAGED_WAREHOUSE_CONNECTIONS = [id: MANAGED_WAREHOUSE_CONNECTION_ID,prefix: 'managed_warehouse',engine: 'duckdb',- source_type: 'ManagedWarehouse',+ source_type: 'Postgres',access_method: 'direct',supports_hogql: true,+ is_builtin_managed_warehouse: true,description: null,},]diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.tsindex 162208dc9753..896f3eacea4d 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.test.ts@@ -5,8 +5,10 @@ import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'import { externalDataSourcesConnectionsList } from 'products/warehouse_sources/frontend/generated/api'+import type { ExternalDataSourceConnectionOptionApi } from 'products/warehouse_sources/frontend/generated/api.schemas'import {+ addHiddenSelectedConnectionOption,connectionSelectorLogic,getConnectionSelectorValue,LOADING_CONNECTIONS,@@ -32,6 +34,7 @@ describe('connectionSelectorLogic', () => {source_type: 'Postgres',access_method: 'direct',supports_hogql: true,+ is_builtin_managed_warehouse: false,},{id: 'conn-456',@@ -40,6 +43,7 @@ describe('connectionSelectorLogic', () => {source_type: 'MySQL',access_method: 'warehouse',supports_hogql: true,+ is_builtin_managed_warehouse: false,},])})@@ -86,17 +90,16 @@ describe('connectionSelectorLogic', () => {)})- // Pins the label the ManagedWarehouseConnection story relies on — it's long enough to need- // truncating in the sidebar, which is the regression that story guards (support ticket 65030).- it('labels a managed warehouse with its prefix and engine', async () => {+ it('shows a provisioned managed warehouse below ClickHouse', async () => {mockConnectionsList.mockResolvedValue([{id: 'conn-duck',prefix: 'managed_warehouse',engine: 'duckdb',- source_type: 'ManagedWarehouse',+ source_type: 'Postgres',access_method: 'direct',supports_hogql: true,+ is_builtin_managed_warehouse: true,},])logic = connectionSelectorLogic()@@ -105,28 +108,73 @@ describe('connectionSelectorLogic', () => {await expectLogic(logic).toFinishAllListeners()- expect(logic.values.connectionSelectOptions[0].options).toEqual(- expect.arrayContaining([- expect.objectContaining({ value: 'conn-duck', label: 'managed_warehouse (DuckDB)' }),- ])+ const [clickHouseOption, managedWarehouseOption] = logic.values.connectionSelectOptions[0].options+ expect(clickHouseOption).toEqual(+ expect.objectContaining({ value: POSTHOG_WAREHOUSE, label: 'PostHog (ClickHouse)' })+ )+ expect(managedWarehouseOption).toEqual(+ expect.objectContaining({ value: 'conn-duck', label: 'PostHog (Managed warehouse)' })+ )+ expect(managedWarehouseOption.iconSrc).toEqual(clickHouseOption.iconSrc)+ expect(managedWarehouseOption).not.toHaveProperty('managementUrl')+ })++ it('keeps the auto-provisioned Duckgres source external when the backend marks it external', async () => {+ mockConnectionsList.mockResolvedValue([+ {+ id: 'conn-duck',+ prefix: 'managed_warehouse',+ description: 'Managed warehouse (auto-provisioned)',+ engine: 'duckdb',+ source_type: 'Postgres',+ access_method: 'direct',+ supports_hogql: true,+ is_builtin_managed_warehouse: false,+ },+ ])+ logic = connectionSelectorLogic()+ logic.mount()+ logic.actions.maybeLoadConnectionOptions()++ await expectLogic(logic).toFinishAllListeners()++ const externalOption = logic.values.connectionSelectOptions[0].options[1]+ expect(externalOption).toEqual(+ expect.objectContaining({+ value: 'conn-duck',+ label: 'Managed warehouse (auto-provisioned) (DuckDB)',+ managementUrl: urls.dataWarehouseSource('managed-conn-duck'),+ }))})it('derives the selected connection value from sql editor state', async () => {- expect(getConnectionSelectorValue(null, true, undefined)).toEqual(LOADING_CONNECTIONS)- expect(- getConnectionSelectorValue(- [{ id: 'conn-123', prefix: 'warehouse', engine: 'postgres' }] as any,- false,- 'conn-123'- )- ).toEqual('conn-123')- expect(- getConnectionSelectorValue(- [{ id: 'conn-123', prefix: 'warehouse', engine: 'postgres' }] as any,- false,- 'missing'- )- ).toEqual(POSTHOG_WAREHOUSE)+ expect(getConnectionSelectorValue(true, undefined)).toEqual(LOADING_CONNECTIONS)+ expect(getConnectionSelectorValue(false, 'conn-123')).toEqual('conn-123')+ expect(getConnectionSelectorValue(false, 'missing')).toEqual('missing')+ })++ it.each([+ ['reader after the flag is disabled', 'reader-connection', 'legacy-connection'],+ ['legacy connection after the flag is enabled', 'legacy-connection', 'reader-connection'],+ ])('keeps a hidden selected %s instead of displaying ClickHouse', (_name, selectedId, visibleId) => {+ const optionGroups = [+ {+ options: [+ { value: POSTHOG_WAREHOUSE, label: 'PostHog (ClickHouse)' },+ { value: visibleId, label: 'Visible managed warehouse' },+ ],+ },+ ]+ const connectionOptions = [{ id: visibleId }] as ExternalDataSourceConnectionOptionApi[]++ const displayedOptions = addHiddenSelectedConnectionOption(optionGroups, connectionOptions, false, selectedId)++ expect(getConnectionSelectorValue(false, selectedId)).toEqual(selectedId)+ expect(displayedOptions[0].options).toContainEqual({+ value: selectedId,+ label: 'Selected connection (hidden)',+ hidden: true,+ })})})diff --git a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.tsindex 4ba46a624d64..7f47fc5d9ccf 100644--- a/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts+++ b/frontend/src/scenes/data-warehouse/editor/connectionSelectorLogic.ts@@ -37,6 +37,7 @@ export interface ConnectionSelectOption {value?: stringlabel: stringdisabled?: boolean+ hidden?: booleaniconSrc?: stringmanagementUrl?: stringoptions?: ConnectionSelectOption[]@@ -91,14 +92,20 @@ function getConnectionEngine(export function getConnectionOptionLabel(source: ExternalDataSourceConnectionOptionApi): string {const engine = getConnectionEngine(source)+ if (isManagedWarehouseConnection(source)) {+ return 'PostHog (Managed warehouse)'+ }const isSynced = source.access_method === 'warehouse'// Prefer the user-set description, then the prefix; fall back to the source type name (never the raw UUID).const name = source.description || source.prefix || source.source_type || source.idreturn `${name} (${ENGINE_LABELS[engine]}${isSynced ? ' · synced' : ''})`}+function isManagedWarehouseConnection(source: ExternalDataSourceConnectionOptionApi): boolean {+ return source.is_builtin_managed_warehouse+}+export function getConnectionSelectorValue(- connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,connectionOptionsLoading: boolean,selectedConnectionId: string | undefined): string {@@ -106,13 +113,48 @@ export function getConnectionSelectorValue(return LOADING_CONNECTIONS}- if (selectedConnectionId && (connectionOptions ?? []).some((source) => source.id === selectedConnectionId)) {+ if (selectedConnectionId) {return selectedConnectionId}return POSTHOG_WAREHOUSE}+export function addHiddenSelectedConnectionOption(+ optionGroups: ConnectionSelectOptionGroup[],+ connectionOptions: ExternalDataSourceConnectionOptionApi[] | null,+ connectionOptionsLoading: boolean,+ selectedConnectionId: string | undefined+): ConnectionSelectOptionGroup[] {+ if (+ connectionOptionsLoading ||+ !selectedConnectionId ||+ (connectionOptions ?? []).some((source) => source.id === selectedConnectionId)+ ) {+ return optionGroups+ }++ const [sourceGroup, ...remainingGroups] = optionGroups+ if (!sourceGroup) {+ return optionGroups+ }++ return [+ {+ ...sourceGroup,+ options: [+ ...sourceGroup.options,+ {+ value: selectedConnectionId,+ label: 'Selected connection (hidden)',+ hidden: true,+ },+ ],+ },+ ...remainingGroups,+ ]+}+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface connectionSelectorLogicValues {connectionOptions: ExternalDataSourceConnectionOptionApi[] | null@@ -263,12 +305,17 @@ export const connectionSelectorLogic = kea<connectionSelectorLogicType>([): ConnectionSelectOptionGroup[] => {const sourceOptions = connectionOptionsLoading? [{ value: LOADING_CONNECTIONS, label: 'Loading...', disabled: true }]- : (connectionOptions ?? []).map((source) => ({- value: source.id,- label: getConnectionOptionLabel(source),- iconSrc: ENGINE_ICONS[getConnectionEngine(source)],- managementUrl: urls.dataWarehouseSource(`managed-${source.id}`),- }))+ : (connectionOptions ?? []).map((source) => {+ const isManagedWarehouse = isManagedWarehouseConnection(source)+ return {+ value: source.id,+ label: getConnectionOptionLabel(source),+ iconSrc: isManagedWarehouse ? IconPostHog : ENGINE_ICONS[getConnectionEngine(source)],+ ...(isManagedWarehouse+ ? {}+ : { managementUrl: urls.dataWarehouseSource(`managed-${source.id}`) }),+ }+ })// Driven by the backend direct-SQL capability surface so the menu never drifts from// the engines we actually support (a new direct source shows up with no frontend change).diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.tsindex 6f3a2aa2c835..0fd7a8e90613 100644--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts@@ -2106,6 +2106,7 @@ describe('sqlEditorLogic', () => {source_type: 'Postgres',access_method: 'direct',supports_hogql: true,+ is_builtin_managed_warehouse: false,},],],@@ -2175,6 +2176,7 @@ describe('sqlEditorLogic', () => {source_type: 'Postgres',access_method: 'direct',supports_hogql: true,+ is_builtin_managed_warehouse: false,},],],@@ -2224,6 +2226,7 @@ describe('sqlEditorLogic', () => {source_type: 'MSSQL',access_method: 'direct',supports_hogql: false,+ is_builtin_managed_warehouse: false,},],],diff --git a/posthog/api/query.py b/posthog/api/query.pyindex 75bcee3c59fd..dd5be378f024 100644--- a/posthog/api/query.py+++ b/posthog/api/query.py@@ -46,7 +46,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.services.query import process_query_modelfrom posthog.api.streaming import sse_streaming_responsefrom posthog.api.utils import action, is_async_query, is_insight_actors_options_query, is_insight_actors_query-from posthog.clickhouse.client.execute_async import cancel_query, get_query_status+from posthog.clickhouse.client.execute_async import QueryNotFoundError, cancel_query, get_query_statusfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tag_value, get_query_tags, tag_queriesfrom posthog.constants import AvailableFeature@@ -71,6 +71,9 @@ from posthog.rate_limit import (from posthog.rbac.user_access_control import UserAccessControlErrorfrom posthog.schema_migrations.upgrade import upgrade+from products.managed_warehouse.backend.facade import feature_flags as managed_warehouse_feature_flags+from products.warehouse_sources.backend.facade.models import is_managed_warehouse_connection_ready+from common.hogvm.python.utils import HogVMExceptionlogger = structlog.get_logger(__name__)@@ -81,6 +84,10 @@ tracer = trace.get_tracer(__name__)# exception embeds an internal Redis key + task id, so we log that for debugging and surface this# friendly message instead of leaking implementation details into the UI.CONCURRENCY_LIMIT_USER_MESSAGE = "Too many queries are running right now — please try again in a moment."+MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE = (+ "This managed warehouse connection is no longer available. Select a source and run the query again."+)+MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE = "managed_warehouse_connection_unavailable"QUERY_VALIDATION_ERROR_TOTAL = Counter("posthog_query_validation_error_total",@@ -384,6 +391,27 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMishow_progress or request.query_params.get("showProgress", False) == "true") # TODO: Remove this once we have a consistent naming conventionquery_status = get_query_status(team_id=self.team.pk, query_id=pk, show_progress=show_progress)+ managed_connection_id = next(+ (+ label.removeprefix(managed_warehouse_feature_flags.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX)+ for label in query_status.labels or []+ if label.startswith(managed_warehouse_feature_flags.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX)+ ),+ None,+ )+ if managed_connection_id is not None and not is_managed_warehouse_connection_ready(+ self.team.pk, managed_connection_id+ ):+ logger.info(+ "Managed warehouse query result is unavailable",+ team_id=self.team.pk,+ query_id=pk,+ connection_id=managed_connection_id,+ )+ raise QueryNotFoundError(+ detail=MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE,+ code=MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE,+ )query_status_response = QueryStatusResponse(query_status=query_status)http_code: int = status.HTTP_202_ACCEPTEDdiff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.pyindex 28e33ba66dd1..2f8b95ac16d4 100644--- a/posthog/api/test/test_query.py+++ b/posthog/api/test/test_query.py@@ -36,7 +36,11 @@ from posthog.schema import (from posthog.hogql.constants import LimitContext-from posthog.api.query import CONCURRENCY_LIMIT_USER_MESSAGE+from posthog.api.query import (+ CONCURRENCY_LIMIT_USER_MESSAGE,+ MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE,+ MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE,+)from posthog.api.services.query import process_query_dict, process_query_modelfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.limit import ConcurrencyLimitExceeded@@ -47,7 +51,10 @@ from posthog.llm.completions import OpenAICompletionfrom posthog.models.utils import UUIDTfrom products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType+from products.managed_warehouse.backend.facade.feature_flags import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIXfrom products.product_analytics.backend.models.insight_variable import InsightVariable+from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX, ExternalDataSource+from products.warehouse_sources.backend.facade.types import ExternalDataSourceTypeclass TestQuery(ClickhouseTestMixin, APIBaseTest):@@ -1254,6 +1261,65 @@ class TestQueryRetrieve(APIBaseTest):self.assertEqual(response.status_code, 202)self.assertFalse(response.json()["query_status"]["complete"])+ @parameterized.expand(+ [+ ("enabled_ready", True, True, 200),+ ("disabled_ready", False, True, 200),+ ("enabled_revoked", True, False, 404),+ ("disabled_revoked", False, False, 404),+ ]+ )+ def test_managed_warehouse_query_status_checks_reader_readiness_without_flag_revocation(+ self, _name: str, flag_enabled: bool, reader_configured: bool, expected_status: int+ ) -> None:+ source = ExternalDataSource.objects.create(+ source_id="managed-source",+ connection_id="managed-connection",+ destination_id="managed-destination",+ team=self.team,+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.POSTGRES,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=True,+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": reader_configured,+ },+ job_inputs={+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": f"posthog_team_{self.team.id}",+ "password": "reader-password",+ },+ )+ self.redis_client_mock.get.return_value = json.dumps(+ {+ "id": self.valid_query_id,+ "team_id": self.team_id,+ "complete": True,+ "labels": [f"{MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX}{source.id}"],+ "results": ["result1"],+ }+ ).encode()++ with patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ return_value=flag_enabled,+ ) as managed_warehouse_sql_editor_flag:+ response = self.client.get(f"/api/environments/{self.team.id}/query/{self.valid_query_id}/")++ self.assertEqual(response.status_code, expected_status)+ managed_warehouse_sql_editor_flag.assert_not_called()+ if not reader_configured:+ self.assertEqual(response.json()["detail"], MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE)+ self.assertEqual(response.json()["code"], MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE)+ self.assertNotIn(self.valid_query_id, response.json()["detail"])+ self.assertNotIn(str(self.team_id), response.json()["detail"])+def test_failed_query_with_internal_error(self):self.redis_client_mock.get.return_value = json.dumps({diff --git a/posthog/clickhouse/client/async_task_chain.py b/posthog/clickhouse/client/async_task_chain.pyindex 641c9b25d477..c46f107c7075 100644--- a/posthog/clickhouse/client/async_task_chain.py+++ b/posthog/clickhouse/client/async_task_chain.py@@ -76,14 +76,16 @@ def execute_task_chain() -> None:"""task_chain = get_task_chain()if task_chain:- chained_tasks = chain(*[args[0] for args in task_chain])- result = chained_tasks.apply_async()-- for args in task_chain:- args[2].task_id = result.id- args[2].labels = ["chained", *(args[2].labels or [])]- args[1].store_query_status(args[2])-+ task_signatures: list[Signature] = []+ for task_signature, manager, query_status in task_chain:+ task_id = str(uuid.uuid4())+ task_signature.set(task_id=task_id)+ query_status.task_id = task_id+ query_status.labels = ["chained", *(query_status.labels or [])]+ manager.store_query_status(query_status)+ task_signatures.append(task_signature)++ chain(*task_signatures).apply_async()_thread_locals.task_chain = []diff --git a/posthog/clickhouse/client/execute_async.py b/posthog/clickhouse/client/execute_async.pyindex 892f6dd98458..9e3b2634254f 100644--- a/posthog/clickhouse/client/execute_async.py+++ b/posthog/clickhouse/client/execute_async.py@@ -19,6 +19,7 @@ from posthog.clickhouse.client.async_task_chain import add_task_to_on_commitfrom posthog.clickhouse.client.limit import ConcurrencyLimitExceededfrom posthog.clickhouse.query_tagging import get_query_tags, tag_queriesfrom posthog.constants import AvailableFeature+from posthog.direct_query_cancellation import build_direct_query_cancellation_token, request_direct_query_cancellationfrom posthog.errors import ExposedCHQueryErrorfrom posthog.exceptions import ClickHouseAtCapacityfrom posthog.exceptions_capture import capture_exception@@ -243,6 +244,12 @@ def execute_process_query(if query_status.complete:return+ if query_status.task_id:+ try:+ tag_queries(celery_task_id=uuid.UUID(query_status.task_id))+ except ValueError:+ logger.warning("Async query has a non-UUID task id", query_id=query_id)+query_status.pickup_time = datetime.datetime.now(datetime.UTC)manager.store_query_status(query_status)@@ -332,6 +339,7 @@ def enqueue_process_query_task(dashboard_id: Optional[int] = None,query_id: Optional[str] = None,cache_key: Optional[str] = None,+ labels: list[str] | None = None,# Attention: This is to pierce through the _manager_ cache, query runner will always refreshrefresh_requested: bool = False,force: bool = False,@@ -386,6 +394,7 @@ def enqueue_process_query_task(start_time=datetime.datetime.now(datetime.UTC),insight_id=insight_id,dashboard_id=dashboard_id,+ labels=labels,)query_tags = get_query_tags().model_dump()manager.store_query_status(query_status)@@ -451,6 +460,15 @@ def cancel_query(team_id: int, query_id: str, dequeue_only: bool = False) -> strif query_status.complete:return "Query already complete"+ if not dequeue_only and query_status.task_id:+ try:+ request_direct_query_cancellation(+ team_id,+ build_direct_query_cancellation_token(query_id, query_status.task_id),+ )+ except Exception:+ logger.exception("Failed to request direct query cancellation", team_id=team_id, query_id=query_id)+if query_status.task_id:logger.info("Got task id %s, attempting to revoke", query_status.task_id)celery.app.control.revoke(query_status.task_id)diff --git a/posthog/clickhouse/client/test/test_execute_async.py b/posthog/clickhouse/client/test/test_execute_async.pyindex 64b3274115f5..7fc596e75918 100644--- a/posthog/clickhouse/client/test/test_execute_async.py+++ b/posthog/clickhouse/client/test/test_execute_async.py@@ -20,10 +20,14 @@ from posthog.clickhouse.client import (execute_async as client,sync_execute,)-from posthog.clickhouse.client.async_task_chain import task_chain_context+from posthog.clickhouse.client.async_task_chain import execute_task_chain, task_chain_contextfrom posthog.clickhouse.client.execute_async import QueryNotFoundError, QueryStatusManager, execute_process_query-from posthog.clickhouse.query_tagging import tag_queries+from posthog.clickhouse.query_tagging import get_query_tags, tag_queriesfrom posthog.constants import AvailableFeature+from posthog.direct_query_cancellation import (+ build_direct_query_cancellation_token,+ is_direct_query_cancellation_requested,+)from posthog.errors import ExposedCHQueryErrorfrom posthog.exceptions import ClickHouseAtCapacity, ClickHouseQueryMemoryLimitExceededfrom posthog.models import Organization, Team@@ -98,6 +102,22 @@ class TestQueryStatusManager(SimpleTestCase):self.query_status.expiration_time = None # We don't care about expiration time in this testself.assertEqual(self.manager.get_query_status(True), self.query_status)+ @patch("posthog.clickhouse.cancel.cancel_query_on_cluster")+ @patch("posthog.clickhouse.client.execute_async.celery.app.control.revoke")+ def test_cancel_query_signals_a_running_direct_query(+ self, revoke: MagicMock, cancel_query_on_cluster: MagicMock+ ) -> None:+ task_id = str(uuid.uuid4())+ self.query_status.task_id = task_id+ self.manager.store_query_status(self.query_status)++ client.cancel_query(self.team_id, self.query_id)++ cancellation_token = build_direct_query_cancellation_token(self.query_id, task_id)+ self.assertTrue(is_direct_query_cancellation_requested(self.team_id, cancellation_token))+ revoke.assert_called_once_with(task_id)+ cancel_query_on_cluster.assert_called_once_with(self.team_id, self.query_id)+def test_update_clickhouse_query_progresses(self):self.manager.store_query_status(self.query_status)@@ -128,6 +148,35 @@ class TestQueryStatusManager(SimpleTestCase):self.assertEqual(self.manager.get_query_status(show_progress=True), self.query_status)+class TestAsyncTaskChain(SimpleTestCase):+ @patch("posthog.clickhouse.client.async_task_chain.uuid.uuid4")+ @patch("posthog.clickhouse.client.async_task_chain.chain")+ def test_persists_each_task_identity_before_dispatch(self, chain_mock: MagicMock, uuid4_mock: MagicMock) -> None:+ task_ids = [+ uuid.UUID("11111111-1111-4111-8111-111111111111"),+ uuid.UUID("22222222-2222-4222-8222-222222222222"),+ ]+ uuid4_mock.side_effect = task_ids+ signatures = [MagicMock(), MagicMock()]+ managers = [MagicMock(), MagicMock()]+ statuses = [QueryStatus(id="query-1", team_id=1), QueryStatus(id="query-2", team_id=1)]+ queued_tasks = list(zip(signatures, managers, statuses, strict=True))++ def assert_ready_for_dispatch() -> None:+ for task_id, signature, manager, status in zip(task_ids, signatures, managers, statuses, strict=True):+ self.assertEqual(status.task_id, str(task_id))+ self.assertIn("chained", status.labels or [])+ signature.set.assert_called_once_with(task_id=str(task_id))+ manager.store_query_status.assert_called_once_with(status)++ chain_mock.return_value.apply_async.side_effect = assert_ready_for_dispatch+ with patch("posthog.clickhouse.client.async_task_chain.get_task_chain", return_value=queued_tasks):+ execute_task_chain()++ chain_mock.assert_called_once_with(*signatures)+ chain_mock.return_value.apply_async.assert_called_once_with()++class TestExecuteProcessQuery(TestCase):def setUp(self):self.user = User.objects.create(email="[email protected]")@@ -143,8 +192,15 @@ class TestExecuteProcessQuery(TestCase):@patch("posthog.api.services.query.process_query_dict")def test_execute_process_query(self, mock_process_query_dict, mock_redis_client):mock_redis = MagicMock()+ task_id = uuid.uuid4()mock_redis.get.return_value = json.dumps(- {"id": self.query_id, "team_id": self.team.id, "complete": False, "error": False}+ {+ "id": self.query_id,+ "team_id": self.team.id,+ "complete": False,+ "error": False,+ "task_id": str(task_id),+ }).encode()mock_redis_client.return_value = mock_redis@@ -154,6 +210,7 @@ class TestExecuteProcessQuery(TestCase):mock_redis_client.assert_called_once()mock_process_query_dict.assert_called_once()+ self.assertEqual(get_query_tags().celery_task_id, task_id)# Assert that Redis set method was called with the correct argumentsself.assertEqual(mock_redis.set.call_count, 2) # Once on pickup, once on completiondiff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.mdindex 4e6899186038..3dcc1f4476cc 100644--- a/posthog/dags/README_DUCKLINGS.md+++ b/posthog/dags/README_DUCKLINGS.md@@ -145,13 +145,12 @@ class DucklingBackfillConfig:2. Enable another team's backfill with the "Enable warehouse backfill for a team" adminaction or the managed warehouse onboarding API. This creates the control-plane team rowwith backfill enabled. The discovery sensor will pick up the team on its next run.- The enablement flow also creates a- managed Postgres live-query connection with a distinct Duckgres reader for the team. Once the- warehouse is ready, background schema discovery exposes every table in the team's event/person,- data-import, team, and modeled-data namespaces in the SQL editor. Duckgres enforces read-only- access to those namespaces for both HogQL and raw SQL. Legacy teams that still use the shared- unsuffixed `events` and `persons` tables are not exposed because those tables contain rows for- multiple teams.+ By default, the SQL editor exposes the auto-provisioned Duckgres source as an external connection+ backed by the stored server login. When the `managed-warehouse-sql-editor` flag is enabled, the chooser+ replaces it with the built-in connection only if a reserved source already contains a configured Duckgres+ `project_reader` credential. Reader provisioning and rotation are separate from this enablement flow.+ Background discovery for a ready reader exposes only the project namespaces allowed by Duckgres. If the+ flag is enabled without a valid reader, neither managed connection appears in the chooser.3. To trigger immediate historical backfill, reset the full backfill sensor cursordiff --git a/posthog/direct_query_cancellation.py b/posthog/direct_query_cancellation.pynew file mode 100644index 000000000000..98d0b0e48604--- /dev/null+++ b/posthog/direct_query_cancellation.py@@ -0,0 +1,26 @@+import hashlib++from posthog import redis++DIRECT_QUERY_CANCELLATION_TTL_SECONDS = 60 * 20+DIRECT_QUERY_CANCELLATION_KEY_PREFIX = "direct_query_cancellation"+++def build_direct_query_cancellation_token(query_id: str, task_id: str) -> str:+ return hashlib.sha256(f"{query_id}\0{task_id}".encode()).hexdigest()+++def _direct_query_cancellation_key(team_id: int, cancellation_token: str) -> str:+ return f"{DIRECT_QUERY_CANCELLATION_KEY_PREFIX}:{team_id}:{cancellation_token}"+++def request_direct_query_cancellation(team_id: int, cancellation_token: str) -> None:+ redis.get_client().set(+ _direct_query_cancellation_key(team_id, cancellation_token),+ "1",+ ex=DIRECT_QUERY_CANCELLATION_TTL_SECONDS,+ )+++def is_direct_query_cancellation_requested(team_id: int, cancellation_token: str) -> bool:+ return bool(redis.get_client().get(_direct_query_cancellation_key(team_id, cancellation_token)))diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 42459638fb3c..a1e6fd8341aa 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -1320,6 +1320,7 @@ class Database(BaseModel):from products.warehouse_sources.backend.facade.models import ( # noqa: PLC0415DataWarehouseTable,ExternalDataSource,+ ManagedWarehouseSQLMode,)with timings.measure("team", emit_span=True):@@ -1371,6 +1372,7 @@ class Database(BaseModel):from posthog.hogql.direct_sql.capability import is_direct_capable # noqa: PLC0415direct_connection_metadata: dict[str, Any] | None = None+ is_managed_warehouse_connection = False# Dual-mode: a synced source queried live builds virtual tables from schema metadata.virtual_source: ExternalDataSource | None = Noneif connection_id is not None:@@ -1389,6 +1391,13 @@ class Database(BaseModel):direct_source.access_method == ExternalDataSource.AccessMethod.DIRECTor is_direct_capable(direct_source)):+ if direct_source.has_managed_warehouse_prefix:+ managed_warehouse_sql_mode = direct_source.managed_warehouse_sql_mode+ if managed_warehouse_sql_mode == ManagedWarehouseSQLMode.UNAVAILABLE:+ raise QueryError(+ "This managed warehouse connection isn't available. Select another connection and try again."+ )+ is_managed_warehouse_connection = managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_INdirect_connection_metadata = direct_source.connection_metadata# A capable non-DIRECT (synced) source drives the dual-mode virtual-table path.if direct_source.access_method != ExternalDataSource.AccessMethod.DIRECT:@@ -1601,11 +1610,13 @@ class Database(BaseModel):is_managed_viewset_enabled=is_managed_viewset_enabled,is_hogql_warehouse_access_control_enabled=is_hogql_warehouse_access_control_enabled,is_data_catalog_enabled=data_catalog_enabled,+ # Managed warehouse is a built-in project datastore and has no warehouse-object ACL surface.# Principals that skip warehouse access control by design:# - synthetic users (project-wide service tokens, bypass object-level RBAC)# - shared-link users (publishing is the explicit access grant).# System tables stay gated for both.bypass_warehouse_access_control=bypass_warehouse_access_control+ or is_managed_warehouse_connectionor isinstance(user, SyntheticUser | SharedLinkUser),direct_connection_metadata=direct_connection_metadata,user_access_control=user_access_control,diff --git a/posthog/hogql/direct_connection.py b/posthog/hogql/direct_connection.pyindex 84549409aec8..3dd0977b233b 100644--- a/posthog/hogql/direct_connection.py+++ b/posthog/hogql/direct_connection.py@@ -14,7 +14,11 @@ from posthog.rbac.user_access_control import UserAccessControlfrom posthog.shared_link_user import SharedLinkUserfrom posthog.synthetic_user import SyntheticUser-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+from products.warehouse_sources.backend.facade.models import (+ DataWarehouseTable,+ ExternalDataSource,+ ManagedWarehouseSQLMode,+)if TYPE_CHECKING:from posthog.models import Team, User@@ -99,11 +103,18 @@ def get_direct_connection_source(id=source_uuid,).exclude(deleted=True)+ .defer("job_inputs").first())if source is None or not is_direct_capable(source):return None+ managed_warehouse_mode: ManagedWarehouseSQLMode | None = None+ if source.has_managed_warehouse_prefix:+ managed_warehouse_mode = source.managed_warehouse_sql_mode+ if managed_warehouse_mode == ManagedWarehouseSQLMode.UNAVAILABLE:+ return None+# Synced (warehouse) sources only expose their `should_sync` catalog — raw SQL bypasses that# boundary and reads any upstream table, so raw queries are pure-direct only. Pure-direct# sources have no restricted catalog to bypass; the whole external database is the intended@@ -111,8 +122,10 @@ def get_direct_connection_source(if require_pure_direct and source.access_method != ExternalDataSource.AccessMethod.DIRECT:return None- if user is not None and not UserAccessControl(user=user, team=team).check_access_level_for_object(- source, required_level="viewer"+ if (+ user is not None+ and managed_warehouse_mode != ManagedWarehouseSQLMode.BUILT_IN+ and not UserAccessControl(user=user, team=team).check_access_level_for_object(source, required_level="viewer")):return Nonediff --git a/posthog/hogql/direct_query_metrics.py b/posthog/hogql/direct_query_metrics.pyindex ca557e42d7b3..ed3ce40dad93 100644--- a/posthog/hogql/direct_query_metrics.py+++ b/posthog/hogql/direct_query_metrics.py@@ -19,7 +19,7 @@ from prometheus_client import (Histogram,)-DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift", "clickhouse", "motherduck"]+DirectQueryDialect = Literal["postgres", "mysql", "snowflake", "redshift", "clickhouse", "duckgres", "motherduck"]DirectQueryStatus = Literal["success", "error"]DIRECT_QUERY_TOTAL = PromCounter(diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.pyindex f7bfab44f960..48b7bf6a402e 100644--- a/posthog/hogql/direct_sql/__init__.py+++ b/posthog/hogql/direct_sql/__init__.py@@ -1,6 +1,7 @@from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, DirectSQLAdapterfrom posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capablefrom posthog.hogql.direct_sql.clickhouse_adapter import ClickHouseAdapter+from posthog.hogql.direct_sql.duckgres_adapter import DuckgresRawAdapterfrom posthog.hogql.direct_sql.motherduck_adapter import MotherDuckAdapterfrom posthog.hogql.direct_sql.mysql_adapter import MySQLAdapterfrom posthog.hogql.direct_sql.postgres_adapter import PostgresAdapter@@ -9,6 +10,8 @@ from posthog.hogql.direct_sql.redshift_adapter import RedshiftAdapterfrom posthog.hogql.direct_sql.registry import get_adapter, register_adapter, registered_enginesfrom posthog.hogql.direct_sql.snowflake_adapter import SnowflakeAdapter+from products.warehouse_sources.backend.facade.models import ExternalDataSource, ManagedWarehouseSQLMode+register_adapter(PostgresAdapter())register_adapter(MySQLAdapter())register_adapter(SnowflakeAdapter())@@ -16,11 +19,25 @@ register_adapter(RedshiftAdapter())register_adapter(ClickHouseAdapter())register_adapter(MotherDuckAdapter())++def get_raw_adapter_for_source(source: ExternalDataSource) -> 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:+ return DuckgresRawAdapter()+ if managed_warehouse_mode == ManagedWarehouseSQLMode.UNAVAILABLE:+ return None+ return get_adapter(source.direct_engine)++__all__ = ["DirectQueryRequest","DirectQueryResult","DirectSQLAdapter","ClickHouseAdapter",+ "DuckgresRawAdapter","MotherDuckAdapter","PostgresAdapter","MySQLAdapter",@@ -30,6 +47,7 @@ __all__ = ["is_direct_capable","ensure_single_direct_statement","get_adapter",+ "get_raw_adapter_for_source","register_adapter","registered_engines",]diff --git a/posthog/hogql/direct_sql/adapter.py b/posthog/hogql/direct_sql/adapter.pyindex 5cd8c4dc37d7..24fa96d66b4a 100644--- a/posthog/hogql/direct_sql/adapter.py+++ b/posthog/hogql/direct_sql/adapter.py@@ -10,7 +10,7 @@ if TYPE_CHECKING:from products.warehouse_sources.backend.facade.models import ExternalDataSource[email protected](frozen=False)class DirectQueryRequest:source: "ExternalDataSource"team: "Team"@@ -20,9 +20,10 @@ class DirectQueryRequest:timings: HogQLTimingsquery_type: strdebug: bool+ cancellation_token: str | None = None[email protected](frozen=False)class DirectQueryResult:results: listtypes: list[tuple[str, str]]@@ -46,9 +47,9 @@ class DirectSQLAdapter(Protocol):...def prepare_raw_sql(self, sql: str) -> str:- """Apply the engine's read-only / single-statement guard to user-supplied raw SQL."""+ """Apply the engine's raw-statement guards to user-supplied SQL."""...def execute(self, request: DirectQueryRequest) -> DirectQueryResult:- """Connect, enforce read-only + timeout, run the SQL, and map results/types back."""+ """Connect, apply engine execution controls, run the SQL, and map results/types back."""...diff --git a/posthog/hogql/direct_sql/duckgres_adapter.py b/posthog/hogql/direct_sql/duckgres_adapter.pynew file mode 100644index 000000000000..e3f7498b3a50--- /dev/null+++ b/posthog/hogql/direct_sql/duckgres_adapter.py@@ -0,0 +1,470 @@+from __future__ import annotations++import socket+import threading+from collections.abc import Callable, Generator, Iterator+from contextlib import closing, contextmanager+from dataclasses import field+from itertools import chain+from selectors import DefaultSelector+from time import monotonic+from typing import TYPE_CHECKING, cast++import psycopg+import structlog+from opentelemetry import trace+from psycopg import pq+from psycopg.abc import Params, PQGen, PQGenConn, Query+from psycopg.conninfo import make_conninfo+from psycopg.generators import fetch, send+from psycopg.waiting import Ready++from posthog.hogql.constants import HogQLDialect+from posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_query+from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult+from posthog.hogql.direct_sql.pgwire import (+ MANAGED_WAREHOUSE_CONNECTION_ERROR,+ LenientDirectPostgresDateLoader,+ postgres_error_to_message,+ postgres_oid_to_clickhouse_type,+)+from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statement+from posthog.hogql.errors import ExposedHogQLError++from posthog.dataclasses import frozen+from posthog.direct_query_cancellation import is_direct_query_cancellation_requested+from posthog.psycopg_helpers import resolve_psycopg_hostaddr_with_timeout++if TYPE_CHECKING:+ from psycopg.pq.abc import PGresult++ from posthog.models.team import Team++ from products.warehouse_sources.backend.facade.models import ExternalDataSource+++DIRECT_DUCKGRES_CONNECT_TIMEOUT_SECONDS = 15+DIRECT_DUCKGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600+DIRECT_DUCKGRES_CANCEL_MAX_ATTEMPTS = 3+DIRECT_DUCKGRES_CANCEL_RETRY_SECONDS = 0.25+DIRECT_DUCKGRES_CANCEL_TIMEOUT_SECONDS = 1+DIRECT_DUCKGRES_CANCELLATION_POLL_SECONDS = 1+DIRECT_DUCKGRES_CANCEL_JOIN_SECONDS = (+ DIRECT_DUCKGRES_CANCEL_MAX_ATTEMPTS * DIRECT_DUCKGRES_CANCEL_TIMEOUT_SECONDS+ + (DIRECT_DUCKGRES_CANCEL_MAX_ATTEMPTS - 1) * DIRECT_DUCKGRES_CANCEL_RETRY_SECONDS+ + 1+)+DIRECT_DUCKGRES_MAX_ROWS = 50_000+DIRECT_DUCKGRES_ROW_CAP_ERROR = (+ f"Managed warehouse query returned more than {DIRECT_DUCKGRES_MAX_ROWS:,} rows. Add a LIMIT clause."+)+MANAGED_WAREHOUSE_UNAVAILABLE_ERROR = "Managed warehouse is unavailable. Contact support if the problem persists."+MANAGED_WAREHOUSE_TIMEOUT_ERROR = "Managed warehouse query exceeded the execution time limit."+MANAGED_WAREHOUSE_CANCELED_ERROR = "Managed warehouse query was canceled."++logger = structlog.get_logger(__name__)+++@frozen+class _DuckgresProjectReaderConfig:+ host: str+ port: int+ database: str+ user: str+ password: str = field(repr=False)+++@frozen+class _DuckgresCancellationState:+ timed_out: threading.Event = field(default_factory=threading.Event)+ canceled: threading.Event = field(default_factory=threading.Event)+++class _DuckgresStreamingClientCursor(psycopg.ClientCursor[tuple[object, ...]]):+ # Psycopg 3.2.4's stream() drops empty-result metadata and rejects successful commands.+ # Preserve its single-row decoding while retaining the terminal libpq result.+ def _stream_send_gen(+ self,+ query: Query,+ params: Params | None = None,+ *,+ binary: bool | None = None,+ size: int,+ ) -> PQGen[None]:+ if size != 1:+ raise ValueError("Duckgres streaming only supports one row per result chunk")++ yield from self._start_query(query)+ postgres_query = self._convert_query(query, params)+ self._execute_send(postgres_query, binary=binary)+ self._pgconn.set_single_row_mode()+ self._last_query = query+ yield from send(self._pgconn)++ def _stream_fetchone_gen(self, first: bool) -> PQGen[PGresult | None]:+ result: PGresult | None = yield from fetch(self._pgconn)+ if result is None:+ return None++ if result.status in (pq.ExecStatus.SINGLE_TUPLE, pq.ExecStatus.TUPLES_CHUNK):+ self.pgresult = result+ self._tx.set_pgresult(result, set_loaders=first)+ if first:+ self._make_row = self._make_row_maker()+ return result++ if result.status in (pq.ExecStatus.EMPTY_QUERY, pq.ExecStatus.TUPLES_OK, pq.ExecStatus.COMMAND_OK):+ terminal_result = result+ while result is not None:+ result = yield from fetch(self._pgconn)+ self._set_results([terminal_result])+ return None++ return self._raise_for_result(result)+++@contextmanager+def _cancel_duckgres_query_on_signal(+ connection: psycopg.Connection,+ timeout_seconds: int,+ team_id: int,+ cancellation_token: str | None,+) -> Iterator[_DuckgresCancellationState]:+ state = _DuckgresCancellationState()+ stop_canceling = threading.Event()+ interrupt_started = threading.Event()+ interrupt_lock = threading.Lock()++ def interrupt_query(reason: str, signal: threading.Event) -> None:+ with interrupt_lock:+ if stop_canceling.is_set() or interrupt_started.is_set():+ return+ interrupt_started.set()+ signal.set()+ cancellation_failure_logged = False+ for attempt in range(DIRECT_DUCKGRES_CANCEL_MAX_ATTEMPTS):+ if stop_canceling.is_set():+ return+ try:+ connection.cancel_safe(timeout=DIRECT_DUCKGRES_CANCEL_TIMEOUT_SECONDS)+ except Exception:+ if not cancellation_failure_logged:+ logger.warning("Failed to cancel managed warehouse query", reason=reason)+ cancellation_failure_logged = True+ if attempt < DIRECT_DUCKGRES_CANCEL_MAX_ATTEMPTS - 1 and stop_canceling.wait(+ DIRECT_DUCKGRES_CANCEL_RETRY_SECONDS+ ):+ return+ if stop_canceling.is_set():+ return+ try:+ interrupt_socket = socket.socket(fileno=connection.pgconn.socket)+ try:+ interrupt_socket.shutdown(socket.SHUT_RDWR)+ finally:+ # The request thread owns libpq's descriptor and closes it after the interrupted operation unwinds.+ interrupt_socket.detach()+ except Exception:+ logger.warning("Failed to interrupt managed warehouse connection", reason=reason)++ def cancel_at_deadline() -> None:+ interrupt_query("execution deadline", state.timed_out)++ def watch_for_cancellation() -> None:+ cancellation_check_failure_logged = False+ while not stop_canceling.is_set():+ try:+ if cancellation_token is not None and is_direct_query_cancellation_requested(+ team_id, cancellation_token+ ):+ interrupt_query("user request", state.canceled)+ return+ except Exception:+ if not cancellation_check_failure_logged:+ logger.warning("Failed to check for managed warehouse query cancellation")+ cancellation_check_failure_logged = True+ if stop_canceling.wait(DIRECT_DUCKGRES_CANCELLATION_POLL_SECONDS):+ return++ timer = threading.Timer(timeout_seconds, cancel_at_deadline)+ timer.daemon = True+ timer.start()+ cancellation_watcher: threading.Thread | None = None+ if cancellation_token is not None:+ cancellation_watcher = threading.Thread(target=watch_for_cancellation, daemon=True)+ cancellation_watcher.start()+ try:+ yield state+ finally:+ stop_canceling.set()+ timer.cancel()+ timer.join(DIRECT_DUCKGRES_CANCEL_JOIN_SECONDS)+ if cancellation_watcher is not None:+ cancellation_watcher.join(DIRECT_DUCKGRES_CANCEL_JOIN_SECONDS)+++def _fetch_capped_duckgres_rows(row_stream: Iterator[tuple[object, ...]]) -> list[tuple[object, ...]]:+ rows: list[tuple[object, ...]] = []+ for row in row_stream:+ rows.append(row)+ if len(rows) > DIRECT_DUCKGRES_MAX_ROWS:+ DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL.labels(dialect="duckgres").inc()+ raise ExposedHogQLError(DIRECT_DUCKGRES_ROW_CAP_ERROR)+ return rows+++def _wait_for_duckgres_connection(+ generator: PQGenConn[psycopg.Connection[tuple[object, ...]]],+ deadline: float,+ abort_check: Callable[[], None],+) -> psycopg.Connection[tuple[object, ...]]:+ try:+ fileno, wait = next(generator)+ with DefaultSelector() as selector:+ selector.register(fileno, wait)+ while True:+ abort_check()+ remaining_seconds = deadline - monotonic()+ if remaining_seconds <= 0:+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")++ ready_events = selector.select(+ timeout=min(remaining_seconds, DIRECT_DUCKGRES_CANCELLATION_POLL_SECONDS)+ )+ if not ready_events:+ generator.send(Ready.NONE)+ continue++ selector.unregister(fileno)+ fileno, wait = generator.send(Ready(ready_events[0][1]))+ selector.register(fileno, wait)+ except StopIteration as stop:+ return stop.value+ finally:+ generator.close()+++def _connect_duckgres_address(+ source_config: _DuckgresProjectReaderConfig,+ hostaddr: str | None,+ deadline: float,+ abort_check: Callable[[], None],+) -> psycopg.Connection[tuple[object, ...]]:+ remaining_seconds = deadline - monotonic()+ if remaining_seconds <= 0:+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")++ conninfo = make_conninfo(+ "",+ host=source_config.host,+ hostaddr=hostaddr,+ port=source_config.port,+ dbname=source_config.database,+ user=source_config.user,+ password=source_config.password,+ sslmode="require",+ sslcert="/tmp/no.txt",+ sslkey="/tmp/no.txt",+ sslrootcert="/tmp/no.txt",+ )+ # The public connect API restarts connect_timeout for each address and offers no cancellation checkpoint.+ generator = cast(+ PQGenConn[psycopg.Connection[tuple[object, ...]]],+ psycopg.Connection._connect_gen(conninfo, timeout=remaining_seconds),+ )+ connection = _wait_for_duckgres_connection(generator, deadline, abort_check)+ connection.cursor_factory = _DuckgresStreamingClientCursor+ return connection+++def _connect_duckgres_project_reader(+ source_config: _DuckgresProjectReaderConfig,+ team_id: int,+ cancellation_token: str | None,+) -> psycopg.Connection[tuple[object, ...]]:+ deadline = monotonic() + DIRECT_DUCKGRES_CONNECT_TIMEOUT_SECONDS+ cancellation_check_failure_logged = False++ def abort_if_canceled() -> None:+ nonlocal cancellation_check_failure_logged+ if cancellation_token is None:+ return+ try:+ canceled = is_direct_query_cancellation_requested(team_id, cancellation_token)+ except Exception:+ if not cancellation_check_failure_logged:+ logger.warning("Failed to check for managed warehouse query cancellation while connecting")+ cancellation_check_failure_logged = True+ return+ if canceled:+ raise ExposedHogQLError(MANAGED_WAREHOUSE_CANCELED_ERROR)++ abort_if_canceled()+ remaining_seconds = deadline - monotonic()+ if remaining_seconds <= 0:+ raise psycopg.errors.ConnectionTimeout("connection timeout expired")+ addresses = resolve_psycopg_hostaddr_with_timeout(+ source_config.host,+ source_config.port,+ remaining_seconds,+ fail_on_resolution_error=True,+ abort_check=abort_if_canceled,+ )++ connection_addresses: list[str | None]+ if addresses is None:+ connection_addresses = [None]+ else:+ connection_addresses = list(addresses)+ last_error: psycopg.Error | None = None+ for hostaddr in connection_addresses:+ abort_if_canceled()+ if deadline - monotonic() <= 0:+ raise psycopg.errors.ConnectionTimeout("connection timeout expired") from last_error+ try:+ return _connect_duckgres_address(source_config, hostaddr, deadline, abort_if_canceled)+ except psycopg.Error as error:+ last_error = error++ if last_error is not None:+ raise last_error+ raise psycopg.OperationalError("Could not connect to managed warehouse")+++class DuckgresRawAdapter:+ engine = "duckgres"+ dialect: HogQLDialect | None = None++ def validate_source_config(+ self, source: ExternalDataSource, team: Team+ ) -> tuple[None, _DuckgresProjectReaderConfig]:+ if source.team_id != team.pk or not source.is_managed_warehouse_ready:+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)++ job_inputs = source.job_inputs+ if not isinstance(job_inputs, dict):+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)++ host = job_inputs.get("host")+ database = job_inputs.get("database")+ user = job_inputs.get("user")+ password = job_inputs.get("password")+ raw_port = job_inputs.get("port")+ if (+ not isinstance(host, str)+ or not host.strip()+ or not isinstance(database, str)+ or not database.strip()+ or not isinstance(user, str)+ or user != f"posthog_team_{team.pk}"+ or not isinstance(password, str)+ or not password+ or isinstance(raw_port, bool)+ ):+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)++ if isinstance(raw_port, int):+ port = raw_port+ elif isinstance(raw_port, str) and raw_port.isdigit():+ port = int(raw_port)+ else:+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)+ if not 1 <= port <= 65535:+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)++ return None, _DuckgresProjectReaderConfig(+ host=host,+ port=port,+ database=database,+ user=user,+ password=password,+ )++ def prepare_raw_sql(self, sql: str) -> str:+ return ensure_single_direct_statement(sql)++ def execute(self, request: DirectQueryRequest) -> DirectQueryResult:+ statement_timeout_seconds = max(+ request.settings.max_execution_time or DIRECT_DUCKGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1+ )+ span = trace.get_current_span()+ 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))+ cancellation: _DuckgresCancellationState | None = None++ try:+ with request.timings.measure("duckgres_execute"), observe_direct_query("duckgres"):+ with request.timings.measure("duckgres_source_validation"):+ _, source_config = self.validate_source_config(request.source, request.team)+ try:+ with request.timings.measure("duckgres_connect", emit_span=True):+ connection_context = _connect_duckgres_project_reader(+ source_config,+ request.team.pk,+ request.cancellation_token,+ )+ except (RuntimeError, ValueError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR) from error+ except psycopg.Error as error:+ span.set_attribute("error_type", error.__class__.__name__)+ raise ExposedHogQLError(MANAGED_WAREHOUSE_CONNECTION_ERROR) from error++ with connection_context as connection:+ with _cancel_duckgres_query_on_signal(+ connection,+ statement_timeout_seconds,+ request.team.pk,+ request.cancellation_token,+ ) as cancellation:+ with request.timings.measure("duckgres_session_setup"):+ connection.execute("USE ducklake")+ connection.adapters.register_loader("date", LenientDirectPostgresDateLoader)+ with connection.cursor() as cursor:+ row_stream = cast(+ Generator[tuple[object, ...]],+ cursor.stream( # nosemgrep: python.django.security.injection.sql.sql-injection-using-db-cursor-execute.sql-injection-db-cursor-execute+ request.sql, request.values or None+ ),+ )+ with closing(row_stream):+ with request.timings.measure("duckgres_query_execute", emit_span=True):+ try:+ first_row = next(row_stream)+ except StopIteration:+ first_row = None+ with request.timings.measure("duckgres_query_fetch"):+ results = (+ _fetch_capped_duckgres_rows(chain((first_row,), row_stream))+ if first_row is not None+ else []+ )+ if cancellation.canceled.is_set():+ raise ExposedHogQLError(MANAGED_WAREHOUSE_CANCELED_ERROR)+ if cancellation.timed_out.is_set():+ raise ExposedHogQLError(MANAGED_WAREHOUSE_TIMEOUT_ERROR)+ description = cursor.description or []+ with request.timings.measure("duckgres_commit", emit_span=True):+ connection.commit()+ if cancellation.canceled.is_set():+ raise ExposedHogQLError(MANAGED_WAREHOUSE_CANCELED_ERROR)+ if cancellation.timed_out.is_set():+ raise ExposedHogQLError(MANAGED_WAREHOUSE_TIMEOUT_ERROR)+ except (psycopg.Error, ExposedHogQLError) as error:+ span.set_attribute("error_type", error.__class__.__name__)+ if cancellation is not None and cancellation.canceled.is_set():+ error = ExposedHogQLError(MANAGED_WAREHOUSE_CANCELED_ERROR)+ elif cancellation is not None and cancellation.timed_out.is_set():+ error = ExposedHogQLError(MANAGED_WAREHOUSE_TIMEOUT_ERROR)+ elif isinstance(error, psycopg.OperationalError):+ error = ExposedHogQLError(MANAGED_WAREHOUSE_CONNECTION_ERROR)+ if request.debug:+ return DirectQueryResult(results=[], types=[], print_columns=[], error=postgres_error_to_message(error))+ raise ExposedHogQLError(postgres_error_to_message(error)) from error++ span.set_attribute("row_count", len(results))+ types = [+ (column.name, postgres_oid_to_clickhouse_type(getattr(column, "type_code", None))) for column in description+ ]+ return DirectQueryResult(results=results, types=types, print_columns=[column.name for column in description])diff --git a/posthog/hogql/direct_sql/pgwire.py b/posthog/hogql/direct_sql/pgwire.pynew file mode 100644index 000000000000..b5bd00d6028e--- /dev/null+++ b/posthog/hogql/direct_sql/pgwire.py@@ -0,0 +1,99 @@+from datetime import date, datetime++import psycopg+from psycopg.types.datetime import DateLoader++MANAGED_WAREHOUSE_CONNECTION_ERROR = (+ "Could not connect to the managed warehouse. Try again, and contact support if the problem persists."+)++POSTGRES_OID_TO_CLICKHOUSE_TYPE: dict[int, str] = {+ 16: "Bool",+ 20: "Int64",+ 21: "Int16",+ 23: "Int32",+ 26: "UInt32",+ 700: "Float32",+ 701: "Float64",+ 1082: "Date",+ 1114: "DateTime",+ 1184: "DateTime64(6, 'UTC')",+ 1700: "Decimal",+ 17: "String",+ 19: "String",+ 25: "String",+ 1042: "String",+ 1043: "String",+ 114: "String",+ 3802: "String",+ 2950: "UUID",+ 1083: "String",+ 1266: "String",+ 1186: "String",+ 1000: "Array(Bool)",+ 1005: "Array(Int16)",+ 1007: "Array(Int32)",+ 1016: "Array(Int64)",+ 1021: "Array(Float32)",+ 1022: "Array(Float64)",+ 1115: "Array(DateTime)",+ 1185: "Array(DateTime64(6, 'UTC'))",+ 1182: "Array(Date)",+ 1231: "Array(Decimal)",+ 1009: "Array(String)",+ 1015: "Array(String)",+ 2951: "Array(UUID)",+}+++def postgres_oid_to_clickhouse_type(oid: int | None) -> str:+ if oid is None:+ return "String"+ return POSTGRES_OID_TO_CLICKHOUSE_TYPE.get(oid, "String")+++def postgres_error_to_message(error: Exception) -> str:+ if isinstance(error, psycopg.Error):+ diag = getattr(error, "diag", None)+ message_primary = getattr(diag, "message_primary", None) if diag else None+ message_detail = getattr(diag, "message_detail", None) if diag else None+ if message_primary and message_detail:+ return f"{message_primary} {message_detail}"+ if message_primary:+ return message_primary++ message = str(error).strip()+ if not message:+ return "Postgres query failed."+ return message.splitlines()[0]+++def parse_lenient_direct_postgres_date(value: str) -> date:+ trimmed = value.strip()+ try:+ return date.fromisoformat(trimmed)+ except ValueError:+ pass++ normalized = trimmed[:-1] + "+00:00" if trimmed.endswith("Z") else trimmed+ try:+ return datetime.fromisoformat(normalized).date()+ except ValueError:+ pass++ if len(trimmed) >= 10:+ return date.fromisoformat(trimmed[:10])+ raise ValueError(f"Unable to parse date value: {value!r}")+++class LenientDirectPostgresDateLoader(DateLoader):+ """Handle non-standard DATE text values returned by DuckDB's Postgres wire."""++ def load(self, data) -> date:+ try:+ return super().load(data)+ except psycopg.DataError as exc:+ try:+ return parse_lenient_direct_postgres_date(bytes(data).decode("utf8", "replace"))+ except ValueError:+ raise exc from Nonediff --git a/posthog/hogql/direct_sql/postgres_adapter.py b/posthog/hogql/direct_sql/postgres_adapter.pyindex 6b5516dbce9f..f83d957e73a4 100644--- a/posthog/hogql/direct_sql/postgres_adapter.py+++ b/posthog/hogql/direct_sql/postgres_adapter.py@@ -1,15 +1,19 @@from contextlib import ExitStack-from datetime import date, datetimefrom typing import TYPE_CHECKING, TypedDict, castimport psycopgfrom opentelemetry import trace-from psycopg.types.datetime import DateLoaderfrom sshtunnel import BaseSSHTunnelForwarderErrorfrom posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResultfrom posthog.hogql.direct_sql.capability import is_direct_capable+from posthog.hogql.direct_sql.pgwire import (+ MANAGED_WAREHOUSE_CONNECTION_ERROR,+ LenientDirectPostgresDateLoader,+ postgres_error_to_message,+ postgres_oid_to_clickhouse_type,+)from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statementfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.escape_sql import escape_postgres_identifier@@ -27,44 +31,6 @@ if TYPE_CHECKING:DIRECT_POSTGRES_CONNECT_TIMEOUT_SECONDS = 15DIRECT_POSTGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS = 600-POSTGRES_OID_TO_CLICKHOUSE_TYPE: dict[int, str] = {- 16: "Bool",- 20: "Int64",- 21: "Int16",- 23: "Int32",- 26: "UInt32",- 700: "Float32",- 701: "Float64",- 1082: "Date",- 1114: "DateTime",- 1184: "DateTime64(6, 'UTC')",- 1700: "Decimal",- 17: "String",- 19: "String",- 25: "String",- 1042: "String",- 1043: "String",- 114: "String",- 3802: "String",- 2950: "UUID",- 1083: "String",- 1266: "String",- 1186: "String",- 1000: "Array(Bool)",- 1005: "Array(Int16)",- 1007: "Array(Int32)",- 1016: "Array(Int64)",- 1021: "Array(Float32)",- 1022: "Array(Float64)",- 1115: "Array(DateTime)",- 1185: "Array(DateTime64(6, 'UTC'))",- 1182: "Array(Date)",- 1231: "Array(Decimal)",- 1009: "Array(String)",- 1015: "Array(String)",- 2951: "Array(UUID)",-}-class PostgresConnectionKwargs(TypedDict, total=False):host: str@@ -80,29 +46,6 @@ class PostgresConnectionKwargs(TypedDict, total=False):sslrootcert: str-def postgres_oid_to_clickhouse_type(oid: int | None) -> str:- if oid is None:- return "String"-- return POSTGRES_OID_TO_CLICKHOUSE_TYPE.get(oid, "String")---def postgres_error_to_message(error: Exception) -> str:- if isinstance(error, psycopg.Error):- diag = getattr(error, "diag", None)- message_primary = getattr(diag, "message_primary", None) if diag else None- message_detail = getattr(diag, "message_detail", None) if diag else None- if message_primary and message_detail:- return f"{message_primary} {message_detail}"- if message_primary:- return message_primary-- message = str(error).strip()- if not message:- return "Postgres query failed."- return message.splitlines()[0]--def is_postwh_host(host: str | None) -> bool:# Hostnames are case-insensitive and may carry a trailing root-zone dot, so# normalize before matching to keep the sslmode enforcement bypass-proof.@@ -136,39 +79,6 @@ def direct_postgres_session_setup_sql(return f"SET search_path TO {quoted_schema}"-def parse_lenient_direct_postgres_date(value: str) -> date:- trimmed = value.strip()-- try:- return date.fromisoformat(trimmed)- except ValueError:- pass-- normalized = trimmed[:-1] + "+00:00" if trimmed.endswith("Z") else trimmed- try:- return datetime.fromisoformat(normalized).date()- except ValueError:- pass-- if len(trimmed) >= 10:- return date.fromisoformat(trimmed[:10])-- raise ValueError(f"Unable to parse date value: {value!r}")---class LenientDirectPostgresDateLoader(DateLoader):- """Handle non-standard DATE text values returned by DuckDB's Postgres wire."""-- def load(self, data) -> date:- try:- return super().load(data)- except psycopg.DataError as exc:- try:- return parse_lenient_direct_postgres_date(bytes(data).decode("utf8", "replace"))- except ValueError:- raise exc from None--def get_runtime_direct_postgres_connection_metadata(connection: psycopg.Connection,connection_metadata: dict[str, object] | None = None,@@ -292,7 +202,12 @@ class PostgresAdapter:connection_kwargs["sslmode"] = "require"with request.timings.measure("postgres_connect", emit_span=True):- connection_context = psycopg.connect(**connection_kwargs)+ try:+ connection_context = psycopg.connect(**connection_kwargs)+ except (psycopg.Error, RuntimeError, ValueError) as error:+ if source.is_managed_warehouse_ready:+ raise ExposedHogQLError(MANAGED_WAREHOUSE_CONNECTION_ERROR) from error+ raisewith connection_context as connection:runtime_connection_metadata = source.connection_metadataif should_hydrate_runtime_direct_postgres_connection_metadata(diff --git a/posthog/hogql/direct_sql/raw_sql.py b/posthog/hogql/direct_sql/raw_sql.pyindex 6bd6c2708f2f..fac1081ddde8 100644--- a/posthog/hogql/direct_sql/raw_sql.py+++ b/posthog/hogql/direct_sql/raw_sql.py@@ -7,9 +7,9 @@ def ensure_single_direct_statement(sql: str) -> str:"""Reject multi-statement raw SQL.Raw queries run without bound parameters, so psycopg uses the simple query- protocol, which runs every ``;``-separated statement in one round trip. A- caller could commit out of the read-only transaction and ``BEGIN READ WRITE``- to perform writes; restricting to one statement keeps it read-only. The same+ protocol, which runs every ``;``-separated statement in one round trip.+ Restricting each request to one operation keeps authorization, timeouts, and+ response accounting aligned to the statement the caller submitted. The sameguard protects direct MySQL queries (PyMySQL additionally disables theMULTI_STATEMENTS client flag by default)."""diff --git a/posthog/hogql/direct_sql/redshift_adapter.py b/posthog/hogql/direct_sql/redshift_adapter.pyindex e38e97003abb..a90cd3b65753 100644--- a/posthog/hogql/direct_sql/redshift_adapter.py+++ b/posthog/hogql/direct_sql/redshift_adapter.py@@ -10,7 +10,7 @@ from posthog.hogql.constants import HogQLDialectfrom posthog.hogql.direct_query_metrics import DIRECT_QUERY_ROW_CAP_EXCEEDED_TOTAL, observe_direct_queryfrom posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResultfrom posthog.hogql.direct_sql.capability import is_direct_capable-from posthog.hogql.direct_sql.postgres_adapter import postgres_error_to_message, postgres_oid_to_clickhouse_type+from posthog.hogql.direct_sql.pgwire import postgres_error_to_message, postgres_oid_to_clickhouse_typefrom posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statementfrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.escape_sql import escape_postgres_identifierdiff --git a/posthog/hogql/query.py b/posthog/hogql/query.pyindex c53826ca0f1b..06b45fd6ed85 100644--- a/posthog/hogql/query.py+++ b/posthog/hogql/query.py@@ -40,7 +40,13 @@ from posthog.hogql.direct_connection import (get_direct_connection_source_none_or_raise,raw_query_denied_by_table_access,)-from posthog.hogql.direct_sql import DirectQueryRequest, ensure_single_direct_statement, get_adapter+from posthog.hogql.direct_sql import (+ DirectQueryRequest,+ DirectSQLAdapter,+ ensure_single_direct_statement,+ get_adapter,+ get_raw_adapter_for_source,+)from posthog.hogql.errors import ExposedHogQLError, InternalHogQLError, QueryError, ResolutionErrorfrom posthog.hogql.feature_extractor import extract_hogql_featuresfrom posthog.hogql.filters import replace_filters@@ -60,13 +66,16 @@ from posthog.hogql.warehouse_warnings import record_warningsfrom posthog.clickhouse.client import sync_executefrom posthog.clickhouse.client.connection import ClickHouseUser, Workload-from posthog.clickhouse.query_tagging import tag_queries+from posthog.clickhouse.query_tagging import get_query_tags, tag_queries+from posthog.direct_query_cancellation import build_direct_query_cancellation_tokenfrom posthog.errors import CHQueryErrorS3Error, CHQueryErrorS3FileChangedDuringRead, ExposedCHQueryErrorfrom posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import UserAccessControlfrom posthog.settings import HOGQL_INCREASED_MAX_EXECUTION_TIME+from products.warehouse_sources.backend.facade.models import ManagedWarehouseSQLMode+tracer = trace.get_tracer(__name__)TRANSIENT_S3_ERROR_RETRY_DELAY_SECONDS = 1.0@@ -456,7 +465,7 @@ class HogQLQueryExecutor:return sources@tracer.start_as_current_span("HogQLQueryExecutor._execute_direct_sql_query")- def _execute_direct_sql_query(self) -> None:+ def _execute_direct_sql_query(self, adapter: DirectSQLAdapter | None = None) -> None:assert self.direct_sql is not Noneassert self.direct_source_id is not None@@ -464,10 +473,17 @@ class HogQLQueryExecutor:if source is None:raise ExposedHogQLError("Connection not found or has been deleted")- adapter = get_adapter(source.direct_engine)+ adapter = adapter or get_adapter(source.direct_engine)if adapter is None:raise InternalHogQLError(f"No direct SQL adapter registered for engine: {source.direct_engine}")+ query_tags = get_query_tags()+ cancellation_token = (+ build_direct_query_cancellation_token(query_tags.client_query_id, str(query_tags.celery_task_id))+ if query_tags.client_query_id is not None and query_tags.celery_task_id is not None+ else None+ )+result = adapter.execute(DirectQueryRequest(source=source,@@ -478,6 +494,7 @@ class HogQLQueryExecutor:timings=self.timings,query_type=self.query_type,debug=bool(self.debug),+ cancellation_token=cancellation_token,))@@ -594,7 +611,13 @@ class HogQLQueryExecutor:)if source is None:raise ExposedHogQLError("Sending a raw query requires a valid connection.")- if raw_query_denied_by_table_access(+ 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)+ if adapter is None:+ raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)+ if managed_warehouse_mode != ManagedWarehouseSQLMode.BUILT_IN and raw_query_denied_by_table_access(self.team,source,user=self.user,@@ -602,14 +625,9 @@ class HogQLQueryExecutor:bypass_warehouse_access_control=self.context.bypass_warehouse_access_control if self.context else False,):raise ExposedHogQLError(RAW_QUERY_TABLE_DENIED_ERROR)- self.connection_id = str(source.id)- self.direct_source_id = self.connection_id- adapter = get_adapter(source.direct_engine)- if adapter is None:- raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)self.direct_dialect = adapter.dialectself.direct_sql = adapter.prepare_raw_sql(str(self.query))- self._execute_direct_sql_query()+ self._execute_direct_sql_query(adapter)@tracer.start_as_current_span("HogQLQueryExecutor._execute_clickhouse_query")def _execute_clickhouse_query(self):diff --git a/posthog/hogql/test/test_direct_connection.py b/posthog/hogql/test/test_direct_connection.pyindex 899d1dcd69ae..138b54bf1bed 100644--- a/posthog/hogql/test/test_direct_connection.py+++ b/posthog/hogql/test/test_direct_connection.py@@ -1,18 +1,44 @@from posthog.test.base import APIBaseTest-from unittest.mock import patch+from unittest.mock import MagicMock, patch-from posthog.hogql.direct_connection import get_direct_connection_source, raw_query_denied_by_table_access+from parameterized import parameterized++from posthog.hogql.direct_connection import (+ RAW_QUERY_TABLE_DENIED_ERROR,+ get_direct_connection_source,+ raw_query_denied_by_table_access,+)+from posthog.hogql.errors import ExposedHogQLError+from posthog.hogql.query import HogQLQueryExecutorfrom posthog.constants import AvailableFeature-from posthog.models import OrganizationMembership+from posthog.models import OrganizationMembership, Team-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSource+from products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_SOURCE_PREFIX,+ DataWarehouseTable,+ ExternalDataSource,+)from products.warehouse_sources.backend.facade.types import ExternalDataSourceType+from products.warehouse_sources.backend.models.external_data_source import (+ get_direct_external_data_source_for_connection,+)from ee.models import AccessControlclass TestGetDirectConnectionSource(APIBaseTest):+ managed_warehouse_sql_editor_flag: MagicMock++ def setUp(self) -> None:+ super().setUp()+ flag_patcher = patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ return_value=True,+ )+ self.managed_warehouse_sql_editor_flag = flag_patcher.start()+ self.addCleanup(flag_patcher.stop)+def _create_source(self, *, access_method: str, direct_query_enabled: bool = True) -> ExternalDataSource:return ExternalDataSource.objects.create(team=self.team,@@ -22,6 +48,34 @@ class TestGetDirectConnectionSource(APIBaseTest):job_inputs={"host": "h", "port": "5432", "database": "d", "user": "u", "password": "p", "schema": "public"},)+ def _create_managed_source(self, **overrides: object) -> ExternalDataSource:+ source_team = overrides.get("team")+ if not isinstance(source_team, Team):+ source_team = self.team+ fields: dict[str, object] = {+ "team": source_team,+ "source_type": ExternalDataSourceType.POSTGRES,+ "access_method": ExternalDataSource.AccessMethod.DIRECT,+ "direct_query_enabled": True,+ "prefix": MANAGED_WAREHOUSE_SOURCE_PREFIX,+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": True,+ },+ "job_inputs": {+ "host": "h",+ "port": "5432",+ "database": "d",+ "user": f"posthog_team_{source_team.id}",+ "password": "p",+ "schema": "public",+ },+ }+ fields.update(overrides)+ return ExternalDataSource.objects.create(**fields)+def test_require_pure_direct_rejects_synced_warehouse_source(self):# A synced source only exposes its `should_sync` catalog through the HogQL-compiled path —# raw SQL has no such projection, so it must not resolve a connection for it.@@ -48,6 +102,168 @@ class TestGetDirectConnectionSource(APIBaseTest):assert resolved is not Noneself.assertEqual(resolved.id, source.id)+ @parameterized.expand(+ [+ ("reader_flag_off", "project_reader", False, True),+ ("reader_flag_on", "project_reader", True, True),+ ("legacy_flag_off", "org_root", False, False),+ ("legacy_flag_on", "org_root", True, False),+ ]+ )+ def test_managed_warehouse_access_control_follows_credential_kind(+ self, _name: str, credential_kind: str, flag_enabled: bool, expected_access: bool+ ) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()++ external_source = self._create_source(access_method=ExternalDataSource.AccessMethod.DIRECT)+ managed_source = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": credential_kind,+ "reader_configured": credential_kind == "project_reader",+ }+ )+ AccessControl.objects.create(+ team=self.team,+ resource="external_data_source",+ access_level="none",+ )+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled+ self.assertIsNone(get_direct_connection_source(self.team, str(external_source.id), user=self.user))+ resolved = get_direct_connection_source(self.team, str(managed_source.id), user=self.user)++ self.assertEqual(resolved is not None, expected_access)+ if resolved is not None:+ self.assertEqual(resolved.id, managed_source.id)++ @parameterized.expand([("flag_off", False), ("flag_on", True)])+ def test_ready_reader_resolution_does_not_depend_on_picker_flag(self, _name: str, flag_enabled: bool) -> None:+ source = self._create_managed_source()+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled++ self.assertEqual(get_direct_connection_source(self.team, str(source.id)), source)+ self.assertEqual(+ get_direct_connection_source(self.team, str(source.id), require_pure_direct=True),+ source,+ )+ self.assertEqual(+ get_direct_external_data_source_for_connection(self.team.id, str(source.id)),+ source,+ )++ @parameterized.expand([("org_root", "org_root"), ("stored_server_login", "stored_server_login")])+ def test_legacy_managed_credentials_remain_available_when_picker_flag_changes(+ self, _name: str, credential_kind: str+ ) -> None:+ source = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": credential_kind,+ }+ )++ for flag_enabled in (False, True):+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled+ self.assertEqual(get_direct_connection_source(self.team, str(source.id)), source)+ self.assertEqual(get_direct_external_data_source_for_connection(self.team.id, str(source.id)), source)++ @parameterized.expand([("flag_off", False), ("flag_on", True)])+ def test_malformed_reserved_source_fails_closed_in_both_modes(self, _name: str, flag_enabled: bool) -> None:+ source = self._create_managed_source(connection_metadata={"engine": "duckdb"})+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled++ self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))+ self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))++ @parameterized.expand(+ [+ ("direct_query_disabled", {"direct_query_enabled": False}),+ (+ "reader_pending",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ }+ },+ ),+ (+ "spoofed_root_username",+ {+ "job_inputs": {+ "host": "h",+ "port": 5432,+ "database": "d",+ "user": "root",+ "password": "p",+ }+ },+ ),+ (+ "malformed_credentials",+ {+ "job_inputs": {+ "host": "",+ "port": 70000,+ "database": "d",+ "user": "posthog_team_invalid",+ "password": "",+ }+ },+ ),+ ]+ )+ def test_managed_warehouse_fails_closed_until_project_reader_is_ready(+ self, _name: str, overrides: dict[str, object]+ ) -> None:+ source = self._create_managed_source(**overrides)++ for flag_enabled in (False, True):+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled+ self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))+ self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))++ @parameterized.expand(+ [+ ("empty_user", {"host": "h", "port": 5432, "database": "d", "user": "", "password": "p"}),+ ("empty_host", {"host": "", "port": 5432, "database": "d", "user": "u", "password": "p"}),+ ("invalid_port", {"host": "h", "port": 70000, "database": "d", "user": "u", "password": "p"}),+ ]+ )+ def test_malformed_legacy_managed_credentials_fail_closed(self, _name: str, job_inputs: dict[str, object]) -> None:+ source = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ },+ job_inputs=job_inputs,+ )++ for flag_enabled in (False, True):+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled+ self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))+ self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))++ def test_managed_warehouse_resolution_rejects_deleted_and_cross_team_sources(self) -> None:+ deleted_source = self._create_managed_source(deleted=True)+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ cross_team_source = self._create_managed_source(team=other_team)++ for source in (deleted_source, cross_team_source):+ self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))+ self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))+class TestRawQueryTableAccess(APIBaseTest):def _create_source(self) -> ExternalDataSource:@@ -94,6 +310,27 @@ class TestRawQueryTableAccess(APIBaseTest):with patch("posthog.hogql.direct_connection.feature_enabled_or_false", return_value=True):assert raw_query_denied_by_table_access(self.team, source, user=self.user) is True+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")+ def test_denies_external_raw_query_before_connecting(self, connect: MagicMock) -> None:+ self._enable_access_control()+ source = self._create_source()+ table = self._create_table(source)+ self._deny_table(table)++ with (+ patch("posthog.hogql.direct_connection.feature_enabled_or_false", return_value=True),+ self.assertRaisesMessage(ExposedHogQLError, RAW_QUERY_TABLE_DENIED_ERROR),+ ):+ HogQLQueryExecutor(+ query="SELECT * FROM orders",+ team=self.team,+ user=self.user,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ connect.assert_not_called()+def test_allows_raw_query_when_user_can_read_all_tables(self):self._enable_access_control()source = self._create_source()diff --git a/posthog/hogql/test/test_direct_duckgres_query.py b/posthog/hogql/test/test_direct_duckgres_query.pynew file mode 100644index 000000000000..1e1286cf92e7--- /dev/null+++ b/posthog/hogql/test/test_direct_duckgres_query.py@@ -0,0 +1,791 @@+import socket+import threading+from collections.abc import Generator++from posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch++from django.test import SimpleTestCase++import psycopg+from parameterized import parameterized+from psycopg import pq++from posthog.hogql.constants import HogQLGlobalSettings+from posthog.hogql.database.database import Database+from posthog.hogql.direct_sql import DuckgresRawAdapter, PostgresAdapter, get_adapter, get_raw_adapter_for_source+from posthog.hogql.direct_sql.duckgres_adapter import _DuckgresStreamingClientCursor+from posthog.hogql.errors import ExposedHogQLError, QueryError, TableAccessDeniedError+from posthog.hogql.query import HogQLQueryExecutor++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership++from products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_SOURCE_PREFIX,+ DataWarehouseTable,+ ExternalDataSource,+)+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType++from ee.models import AccessControl+++class TestDuckgresRawAdapterSelection(SimpleTestCase):+ def _source(self, **overrides: object) -> ExternalDataSource:+ source = ExternalDataSource(+ team_id=123,+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=True,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ job_inputs={+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": "posthog_team_123",+ "password": "reader-password",+ },+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": True,+ },+ )+ for field, value in overrides.items():+ setattr(source, field, value)+ return source++ def test_selects_native_adapter_only_for_complete_managed_markers(self) -> None:+ self.assertIsInstance(get_raw_adapter_for_source(self._source()), DuckgresRawAdapter)+ self.assertIsInstance(+ get_raw_adapter_for_source(+ self._source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ }+ )+ ),+ PostgresAdapter,+ )+ self.assertIsInstance(+ get_raw_adapter_for_source(self._source(prefix="customer_postgres", connection_metadata={})),+ PostgresAdapter,+ )++ def test_managed_source_keeps_postgres_adapter_for_non_raw_queries(self) -> None:+ source = self._source()+ self.assertIsInstance(get_adapter(source.direct_engine), PostgresAdapter)++ @parameterized.expand(+ [+ ("missing_system_managed", {"connection_metadata": {"engine": "duckdb"}}),+ ("wrong_prefix", {"prefix": "ducklake"}),+ (+ "wrong_engine",+ {+ "connection_metadata": {+ "engine": "postgres",+ "system_managed": True,+ }+ },+ ),+ ("wrong_source_type", {"source_type": ExternalDataSourceType.MYSQL}),+ (+ "disabled_direct_query",+ {"access_method": ExternalDataSource.AccessMethod.WAREHOUSE, "direct_query_enabled": False},+ ),+ (+ "synced_direct_query",+ {"access_method": ExternalDataSource.AccessMethod.WAREHOUSE, "direct_query_enabled": True},+ ),+ (+ "pending_reader",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ }+ },+ ),+ (+ "unknown_credential_kind",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "unknown",+ }+ },+ ),+ ]+ )+ def test_incomplete_managed_markers_do_not_select_native_adapter(+ self, _name: str, overrides: dict[str, object]+ ) -> None:+ adapter = get_raw_adapter_for_source(self._source(**overrides))+ if overrides.get("prefix") == "ducklake":+ self.assertIsInstance(adapter, PostgresAdapter)+ else:+ self.assertIsNone(adapter)+++class TestDuckgresStreamingClientCursor(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty_query", pq.ExecStatus.EMPTY_QUERY),+ ("empty_select", pq.ExecStatus.TUPLES_OK),+ ("command", pq.ExecStatus.COMMAND_OK),+ ]+ )+ def test_retains_terminal_result(self, _name: str, status: pq.ExecStatus) -> None:+ terminal_result = MagicMock(status=status)+ results = iter([terminal_result, None])++ def fake_fetch(_connection: object) -> Generator[None, None, object | None]:+ yield from ()+ return next(results)++ cursor = MagicMock()+ with patch("posthog.hogql.direct_sql.duckgres_adapter.fetch", side_effect=fake_fetch):+ self.assertEqual(list(_DuckgresStreamingClientCursor._stream_fetchone_gen(cursor, first=True)), [])++ cursor._set_results.assert_called_once_with([terminal_result])++ def test_streams_with_the_simple_query_protocol(self) -> None:+ postgres_query = object()++ def empty_generator(*_args: object, **_kwargs: object) -> Generator[None]:+ yield from ()++ cursor = MagicMock()+ cursor._start_query.side_effect = empty_generator+ cursor._convert_query.return_value = postgres_query+ with patch("posthog.hogql.direct_sql.duckgres_adapter.send", side_effect=empty_generator):+ self.assertEqual(+ list(+ _DuckgresStreamingClientCursor._stream_send_gen(+ cursor,+ "UPDATE example SET value = 1 RETURNING value",+ size=1,+ )+ ),+ [],+ )++ cursor._execute_send.assert_called_once_with(postgres_query, binary=None)+ cursor._pgconn.set_single_row_mode.assert_called_once()+++class TestDirectDuckgresQuery(APIBaseTest):+ managed_warehouse_sql_editor_flag: MagicMock++ def setUp(self) -> None:+ super().setUp()+ flag_patcher = patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ return_value=True,+ )+ self.managed_warehouse_sql_editor_flag = flag_patcher.start()+ self.addCleanup(flag_patcher.stop)+ resolver_patcher = patch(+ "posthog.hogql.direct_sql.duckgres_adapter.resolve_psycopg_hostaddr_with_timeout",+ return_value=["203.0.113.10"],+ )+ self.resolve_hostaddr = resolver_patcher.start()+ self.addCleanup(resolver_patcher.stop)++ def _managed_source(+ self,+ *,+ source_id: str = "managed-source",+ user: str | None = None,+ direct_query_enabled: bool = True,+ connection_metadata: dict[str, object] | None = None,+ ) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_id=source_id,+ connection_id=f"{source_id}-connection",+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=direct_query_enabled,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ job_inputs={+ "host": f"{source_id}.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": user if user is not None else f"posthog_team_{self.team.pk}",+ "password": f"{source_id}-password",+ },+ connection_metadata=(+ connection_metadata+ if connection_metadata is not None+ else {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": True,+ }+ ),+ )++ @staticmethod+ def _connection_with_result(rows: list[tuple[object, ...]], type_code: int = 23) -> tuple[MagicMock, MagicMock]:+ cursor = MagicMock()+ cursor.stream_closed = False++ def stream_rows() -> Generator[tuple[object, ...]]:+ try:+ yield from rows+ finally:+ cursor.stream_closed = True++ cursor.stream.return_value = stream_rows()+ column = MagicMock(type_code=type_code)+ column.name = "value"+ cursor.description = [column]+ connection = MagicMock()+ connection.cursor.return_value.__enter__.return_value = cursor+ return connection, cursor++ def _managed_source_with_denied_table(+ self,+ *,+ user: str | None = None,+ connection_metadata: dict[str, object] | None = None,+ ) -> ExternalDataSource:+ source = self._managed_source(user=user, connection_metadata=connection_metadata)+ table = DataWarehouseTable.objects.create(+ name="managed_table",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern="",+ columns={"value": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}},+ )+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},+ ]+ self.organization.save()+ membership = OrganizationMembership.objects.get(user=self.user, organization=self.organization)+ membership.level = OrganizationMembership.Level.MEMBER+ membership.save()+ AccessControl.objects.create(+ team=self.team,+ resource="warehouse_table",+ resource_id=str(table.id),+ access_level="none",+ )+ return source++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_executes_with_the_selected_sources_project_reader(self, connect) -> None:+ self._managed_source(source_id="decoy-source")+ source = self._managed_source(source_id="selected-source")+ connection, cursor = self._connection_with_result([(1,)])+ connect.return_value.__enter__.return_value = connection++ with (+ patch("posthog.hogql.direct_connection.Database.create_for", side_effect=AssertionError),+ patch.object(HogQLQueryExecutor, "_prepare_execution", side_effect=AssertionError),+ patch(+ "products.warehouse_sources.backend.facade.source_management.SourceRegistry.get_source",+ side_effect=AssertionError,+ ),+ ):+ response = HogQLQueryExecutor(+ query="SELECT 1 AS value", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(response.results, [(1,)])+ self.assertEqual(response.columns, ["value"])+ self.assertEqual(response.types, [("value", "Int32")])+ connect.assert_called_once()+ source_config, hostaddr, deadline, abort_check = connect.call_args.args+ self.assertEqual(source_config.host, "selected-source.example.com")+ self.assertEqual(source_config.port, 5432)+ self.assertEqual(source_config.database, "ducklake")+ self.assertEqual(source_config.user, f"posthog_team_{self.team.pk}")+ self.assertEqual(source_config.password, "selected-source-password")+ self.assertEqual(hostaddr, "203.0.113.10")+ self.assertGreater(deadline, 0)+ self.assertTrue(callable(abort_check))+ self.resolve_hostaddr.assert_called_once()+ resolver_args = self.resolve_hostaddr.call_args.args+ resolver_kwargs = self.resolve_hostaddr.call_args.kwargs+ self.assertEqual(resolver_args[:2], ("selected-source.example.com", 5432))+ self.assertGreater(resolver_args[2], 0)+ self.assertLessEqual(resolver_args[2], 15)+ self.assertTrue(resolver_kwargs["fail_on_resolution_error"])+ self.assertTrue(callable(resolver_kwargs["abort_check"]))+ connection.execute.assert_called_once_with("USE ducklake")+ cursor.stream.assert_called_once_with("SELECT 1 AS value", None)++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_rejects_multiple_statements_before_connecting(self, connect) -> None:+ source = self._managed_source()++ with self.assertRaisesMessage(ExposedHogQLError, "Raw queries must contain a single statement"):+ HogQLQueryExecutor(+ query="SELECT 1; SELECT 2",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ connect.assert_not_called()++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ @patch("posthog.hogql.direct_sql.duckgres_adapter.threading.Timer")+ def test_schedules_cancellation_and_preserves_empty_utility_results(self, timer, connect) -> None:+ source = self._managed_source()+ connection, cursor = self._connection_with_result([])+ cursor.description = None+ connect.return_value.__enter__.return_value = connection+ connection.commit.side_effect = lambda: self.assertFalse(timer.return_value.cancel.called)++ response = HogQLQueryExecutor(+ query="SET TIME ZONE 'UTC'",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ settings=HogQLGlobalSettings(max_execution_time=12),+ ).execute()++ self.assertIsNone(response.error)+ self.assertEqual(response.results, [])+ self.assertEqual(response.columns, [])+ cursor.stream.assert_called_once_with("SET TIME ZONE 'UTC'", None)+ self.assertEqual(timer.call_args.args[0], 12)+ connection.commit.assert_called_once_with()++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_preserves_columns_for_an_empty_select(self, connect) -> None:+ source = self._managed_source()+ connection, _cursor = self._connection_with_result([])+ connect.return_value.__enter__.return_value = connection++ response = HogQLQueryExecutor(+ query="SELECT 1 AS value WHERE false",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ self.assertEqual(response.results, [])+ self.assertEqual(response.columns, ["value"])+ self.assertEqual(response.types, [("value", "Int32")])++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ @patch("posthog.hogql.direct_sql.duckgres_adapter.threading.Timer")+ @patch("posthog.hogql.direct_sql.duckgres_adapter.socket.socket")+ def test_cancels_queries_at_the_execution_deadline(self, socket_factory, timer, connect) -> None:+ source = self._managed_source()+ connection, _cursor = self._connection_with_result([(1,)])+ connection.pgconn.socket = 42+ connect.return_value.__enter__.return_value = connection+ timer.return_value.start.side_effect = lambda: timer.call_args.args[1]()++ with self.assertRaisesMessage(ExposedHogQLError, "exceeded the execution time limit"):+ HogQLQueryExecutor(+ query="SELECT slow_value",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ settings=HogQLGlobalSettings(max_execution_time=12),+ ).execute()++ self.assertEqual(connection.cancel_safe.call_count, 3)+ connection.cancel_safe.assert_called_with(timeout=1)+ socket_factory.assert_called_once_with(fileno=42)+ socket_factory.return_value.shutdown.assert_called_once_with(socket.SHUT_RDWR)+ socket_factory.return_value.detach.assert_called_once_with()+ connection.close.assert_not_called()+ connection.commit.assert_not_called()++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_cancels_a_running_query_when_the_async_request_is_canceled(self, connect) -> None:+ source = self._managed_source()+ connection, cursor = self._connection_with_result([])+ cancellation_observed = threading.Event()++ def blocked_rows() -> Generator[tuple[object, ...]]:+ if not cancellation_observed.wait(2):+ raise AssertionError("The managed warehouse query was not canceled")+ yield from ()+ raise psycopg.OperationalError("query canceled")++ cursor.stream.return_value = blocked_rows()+ connection.cancel_safe.side_effect = lambda **_kwargs: cancellation_observed.set()+ connect.return_value.__enter__.return_value = connection+ query_tags = MagicMock(client_query_id="query-id", celery_task_id="2f3350d0-e641-4c33-bc9c-66898bf22317")++ with (+ patch("posthog.hogql.query.get_query_tags", return_value=query_tags),+ patch(+ "posthog.hogql.direct_sql.duckgres_adapter.is_direct_query_cancellation_requested",+ side_effect=[False, False, True],+ ),+ self.assertRaises(ExposedHogQLError) as error,+ ):+ HogQLQueryExecutor(+ query="SELECT slow_value",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ self.assertEqual(str(error.exception), "Managed warehouse query was canceled.")+ connection.cancel_safe.assert_called()+ connection.commit.assert_not_called()++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_cancels_before_opening_a_connection(self, connect) -> None:+ source = self._managed_source()+ query_tags = MagicMock(client_query_id="query-id", celery_task_id="2f3350d0-e641-4c33-bc9c-66898bf22317")++ with (+ patch("posthog.hogql.query.get_query_tags", return_value=query_tags),+ patch(+ "posthog.hogql.direct_sql.duckgres_adapter.is_direct_query_cancellation_requested",+ return_value=True,+ ),+ self.assertRaises(ExposedHogQLError) as error,+ ):+ HogQLQueryExecutor(+ query="SELECT slow_value",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ self.assertEqual(str(error.exception), "Managed warehouse query was canceled.")+ connect.assert_not_called()++ def test_non_raw_managed_query_ignores_warehouse_object_access_control(self) -> None:+ source = self._managed_source_with_denied_table()+ self.managed_warehouse_sql_editor_flag.return_value = False++ with patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda flag, *_args, **_kwargs: flag == "hogql-warehouse-access-control",+ ):+ sql, _context = HogQLQueryExecutor(+ query="SELECT value FROM managed_table",+ team=self.team,+ user=self.user,+ connection_id=str(source.id),+ ).generate_clickhouse_sql()++ self.assertIn("managed_table", sql)++ def test_non_raw_legacy_managed_source_enforces_warehouse_object_access_control(self) -> None:+ source = self._managed_source_with_denied_table(+ user="org-root",+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ },+ )+ self.managed_warehouse_sql_editor_flag.return_value = True++ with (+ patch(+ "posthog.hogql.database.database.feature_enabled_or_false",+ side_effect=lambda flag, *_args, **_kwargs: flag == "hogql-warehouse-access-control",+ ),+ self.assertRaises(TableAccessDeniedError),+ ):+ HogQLQueryExecutor(+ query="SELECT value FROM managed_table",+ team=self.team,+ user=self.user,+ connection_id=str(source.id),+ ).generate_clickhouse_sql()++ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")+ def test_non_raw_managed_connection_errors_hide_connection_details(self, connect) -> None:+ source = self._managed_source()+ DataWarehouseTable.objects.create(+ name="managed_table",+ format="Parquet",+ team=self.team,+ external_data_source=source,+ url_pattern="",+ columns={"value": {"hogql": "IntegerDatabaseField", "clickhouse": "Int64", "valid": True}},+ )+ connect.side_effect = psycopg.OperationalError(+ "could not connect to host=private.internal\nprivate driver detail"+ )++ with self.assertRaises(ExposedHogQLError) as context:+ HogQLQueryExecutor(+ query="SELECT value FROM managed_table",+ team=self.team,+ connection_id=str(source.id),+ ).execute()++ self.assertEqual(+ str(context.exception),+ "Could not connect to the managed warehouse. Try again, and contact support if the problem persists.",+ )+ self.assertNotIn("private.internal", str(context.exception))+ self.assertNotIn("private driver detail", str(context.exception))++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ @patch("posthog.hogql.query.raw_query_denied_by_table_access", side_effect=AssertionError)+ def test_managed_warehouse_raw_queries_skip_unconfigured_table_access(self, _denied, connect) -> None:+ source = self._managed_source()+ self.managed_warehouse_sql_editor_flag.return_value = False+ connection, _cursor = self._connection_with_result([(1,)])+ connect.return_value.__enter__.return_value = connection++ response = HogQLQueryExecutor(+ query="SELECT 1", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(response.results, [(1,)])++ @parameterized.expand(+ [+ ("empty_password", {"password": ""}),+ ("root_username", {"user": "root"}),+ ]+ )+ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_rejects_malformed_reader_credentials(+ self, _name: str, credential_overrides: dict[str, object], connect+ ) -> None:+ source = self._managed_source()+ self.managed_warehouse_sql_editor_flag.return_value = False+ source.job_inputs = {**source.job_inputs, **credential_overrides}+ source.save(update_fields=["job_inputs"])++ with self.assertRaisesMessage(ExposedHogQLError, "Invalid connectionId"):+ HogQLQueryExecutor(+ query="SELECT 1", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ connect.assert_not_called()++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ @patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect")+ @patch("posthog.hogql.query.raw_query_denied_by_table_access", return_value=True)+ def test_legacy_managed_raw_query_preserves_external_table_access_control(+ self, denied: MagicMock, postgres_connect: MagicMock, duckgres_connect: MagicMock+ ) -> None:+ source = self._managed_source(+ user="org-root",+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ },+ )+ self.managed_warehouse_sql_editor_flag.return_value = True++ with self.assertRaisesMessage(ExposedHogQLError, "raw SQL is not allowed"):+ HogQLQueryExecutor(+ query="SELECT 1",+ team=self.team,+ user=self.user,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ denied.assert_called_once()+ postgres_connect.assert_not_called()+ duckgres_connect.assert_not_called()++ @parameterized.expand(+ [+ (+ "pending_reader",+ {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ },+ True,+ ),+ (+ "unknown_credential_kind",+ {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "unknown",+ "reader_configured": True,+ },+ True,+ ),+ (+ "direct_query_disabled",+ {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": True,+ },+ False,+ ),+ ]+ )+ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_rejects_unready_project_readers_before_connecting(+ self,+ _name: str,+ connection_metadata: dict[str, object],+ direct_query_enabled: bool,+ connect,+ ) -> None:+ source = self._managed_source(+ connection_metadata=connection_metadata,+ direct_query_enabled=direct_query_enabled,+ )+ self.managed_warehouse_sql_editor_flag.return_value = False++ with self.assertRaises(ExposedHogQLError):+ HogQLQueryExecutor(+ query="SELECT 1",+ team=self.team,+ connection_id=str(source.id),+ send_raw_query=True,+ ).execute()++ connect.assert_not_called()++ def test_database_fails_closed_for_an_unavailable_reserved_source(self) -> None:+ source = self._managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ }+ )++ with self.assertRaisesMessage(QueryError, "This managed warehouse connection isn't available"):+ Database.create_for(team=self.team, connection_id=str(source.id))++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_hides_connection_details(self, connect) -> None:+ source = self._managed_source()+ connect.side_effect = psycopg.OperationalError(+ "could not connect to host=private.internal\nprivate driver detail"+ )++ with self.assertRaises(ExposedHogQLError) as context:+ HogQLQueryExecutor(+ query="SELECT 1", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(+ str(context.exception),+ "Could not connect to the managed warehouse. Try again, and contact support if the problem persists.",+ )+ self.assertNotIn("private.internal", str(context.exception))+ self.assertNotIn("private driver detail", str(context.exception))++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ @patch("posthog.hogql.direct_sql.duckgres_adapter.monotonic")+ def test_connect_deadline_is_shared_across_resolved_addresses(self, monotonic, connect) -> None:+ source = self._managed_source()+ clock = [100.0]+ monotonic.side_effect = lambda: clock[0]+ self.resolve_hostaddr.return_value = ["203.0.113.10", "203.0.113.11"]++ def fail_after_deadline(*_args: object) -> None:+ clock[0] = 116.0+ raise psycopg.OperationalError("first address failed")++ connect.side_effect = fail_after_deadline+ with self.assertRaises(ExposedHogQLError) as context:+ HogQLQueryExecutor(+ query="SELECT 1", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(+ str(context.exception),+ "Could not connect to the managed warehouse. Try again, and contact support if the problem persists.",+ )+ connect.assert_called_once()+ self.assertEqual(connect.call_args.args[1], "203.0.113.10")++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_maps_query_errors_to_a_single_message(self, connect) -> None:+ source = self._managed_source()+ connection, cursor = self._connection_with_result([])+ cursor.stream.side_effect = psycopg.ProgrammingError("query failed\nprivate driver detail")+ connect.return_value.__enter__.return_value = connection++ with self.assertRaises(ExposedHogQLError) as context:+ HogQLQueryExecutor(+ query="SELECT 1", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(str(context.exception), "query failed")+ self.assertNotIn("private driver detail", str(context.exception))++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_hides_post_connect_operational_error_details(self, connect) -> None:+ source = self._managed_source()+ connection, cursor = self._connection_with_result([])+ cursor.stream.side_effect = psycopg.OperationalError(+ "server closed the connection to host=private.internal\nprivate driver detail"+ )+ connect.return_value.__enter__.return_value = connection++ with self.assertRaises(ExposedHogQLError) as context:+ HogQLQueryExecutor(+ query="SELECT 1", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(+ str(context.exception),+ "Could not connect to the managed warehouse. Try again, and contact support if the problem persists.",+ )+ self.assertNotIn("private.internal", str(context.exception))+ self.assertNotIn("private driver detail", str(context.exception))++ @patch("posthog.hogql.direct_sql.duckgres_adapter.DIRECT_DUCKGRES_MAX_ROWS", 3)+ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_accepts_raw_results_at_the_row_cap(self, connect) -> None:+ source = self._managed_source()+ connection, cursor = self._connection_with_result([(1,), (2,), (3,)])+ connect.return_value.__enter__.return_value = connection++ response = HogQLQueryExecutor(+ query="SELECT value FROM bounded_table", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(response.results, [(1,), (2,), (3,)])+ self.assertTrue(cursor.stream_closed)+ connection.commit.assert_called_once_with()++ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")+ def test_rejects_raw_results_over_the_row_cap(self, connect) -> None:+ source = self._managed_source()+ connection, cursor = self._connection_with_result([(1,)] * 50_001)+ connect.return_value.__enter__.return_value = connection++ with self.assertRaises(ExposedHogQLError) as context:+ HogQLQueryExecutor(+ query="SELECT value FROM large_table", team=self.team, connection_id=str(source.id), send_raw_query=True+ ).execute()++ self.assertEqual(+ str(context.exception),+ "Managed warehouse query returned more than 50,000 rows. Add a LIMIT clause.",+ )+ cursor.stream.assert_called_once_with("SELECT value FROM large_table", None)+ self.assertTrue(cursor.stream_closed)+ connection.commit.assert_not_called()diff --git a/posthog/hogql/test/test_direct_postgres_query.py b/posthog/hogql/test/test_direct_postgres_query.pyindex 2ccc83f18565..06ac1aa6ae8c 100644--- a/posthog/hogql/test/test_direct_postgres_query.py+++ b/posthog/hogql/test/test_direct_postgres_query.py@@ -15,14 +15,16 @@ from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettingsfrom posthog.hogql.context import HogQLContextfrom posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_function-from posthog.hogql.direct_sql.postgres_adapter import (+from posthog.hogql.direct_sql.pgwire import (LenientDirectPostgresDateLoader,- direct_postgres_session_setup_sql,- get_runtime_direct_postgres_connection_metadata,parse_lenient_direct_postgres_date,postgres_error_to_message,postgres_oid_to_clickhouse_type,)+from posthog.hogql.direct_sql.postgres_adapter import (+ direct_postgres_session_setup_sql,+ get_runtime_direct_postgres_connection_metadata,+)from posthog.hogql.direct_sql.raw_sql import ensure_single_direct_statementfrom posthog.hogql.errors import ExposedHogQLError, QueryErrorfrom posthog.hogql.escape_sql import escape_postgres_identifierdiff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.pyindex c05789f472b0..ed1b0c51763c 100644--- a/posthog/hogql_queries/hogql_query_runner.py+++ b/posthog/hogql_queries/hogql_query_runner.py@@ -4,16 +4,18 @@ from typing import Any, Optional, castfrom posthog.schema import (CachedHogQLQueryResponse,+ CacheMissResponse,DashboardFilter,DateRange,HogQLFilters,HogQLQuery,HogQLQueryResponse,+ QueryStatusResponse,)from posthog.hogql import astfrom posthog.hogql.constants import HogQLGlobalSettings-from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR+from posthog.hogql.direct_connection import INVALID_CONNECTION_ID_ERROR, get_direct_connection_sourcefrom posthog.hogql.errors import ExposedHogQLErrorfrom posthog.hogql.filters import replace_filtersfrom posthog.hogql.metadata import get_table_names@@ -26,10 +28,13 @@ from posthog.hogql.variables import replace_variablesfrom posthog import settings as app_settingsfrom posthog.caching.utils import ThresholdMode, staleness_threshold_mapfrom posthog.clickhouse.query_tagging import tag_contains_user_hogql+from posthog.event_usage import AnalyticsPropsfrom posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator-from posthog.hogql_queries.query_runner import AnalyticsQueryRunner+from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode+from posthog.models import User-from products.warehouse_sources.backend.facade.models import get_direct_external_data_source_for_connection+from products.managed_warehouse.backend.facade import feature_flags as managed_warehouse_feature_flags+from products.warehouse_sources.backend.facade.models import ManagedWarehouseSQLMode_INFORMATION_SCHEMA_PREFIX = "system.information_schema."@@ -46,6 +51,8 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):**kwargs,):self.settings = settings or HogQLGlobalSettings()+ self._direct_connection_validated = False+ self._managed_warehouse_sql_mode: ManagedWarehouseSQLMode | None = Nonesuper().__init__(*args, **kwargs)# Treat SQL query caching like day insight@@ -54,6 +61,61 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):return Nonereturn 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:+ return+ managed_warehouse_sql_mode: ManagedWarehouseSQLMode | None = None+ if self.query.connectionId:+ source = get_direct_connection_source(+ self.team,+ self.query.connectionId,+ user=user if user is not None else self.user,+ )+ if source is None:+ raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)+ if source.has_managed_warehouse_prefix:+ managed_warehouse_sql_mode = source.managed_warehouse_sql_mode+ if managed_warehouse_sql_mode == ManagedWarehouseSQLMode.UNAVAILABLE:+ raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)+ self._managed_warehouse_sql_mode = managed_warehouse_sql_mode+ self._direct_connection_validated = True++ def get_cache_payload(self) -> dict:+ self._validate_direct_connection()+ 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+ return payload++ def query_status_labels(self) -> list[str] | None:+ self._validate_direct_connection()+ if self._managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN:+ return [+ f"{managed_warehouse_feature_flags.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX}{self.query.connectionId}"+ ]+ return None++ def run(+ self,+ execution_mode: ExecutionMode = ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,+ user: Optional[User] = None,+ query_id: Optional[str] = None,+ insight_id: Optional[int] = None,+ dashboard_id: Optional[int] = None,+ cache_age_seconds: Optional[int] = None,+ analytics_props: Optional[AnalyticsProps] = None,+ ) -> HogQLQueryResponse | CachedHogQLQueryResponse | CacheMissResponse | QueryStatusResponse:+ self._validate_direct_connection(user=user, force=True)+ return super().run(+ execution_mode=execution_mode,+ user=user,+ query_id=query_id,+ insight_id=insight_id,+ dashboard_id=dashboard_id,+ cache_age_seconds=cache_age_seconds,+ analytics_props=analytics_props,+ )+def requires_fresh_calculation(self) -> bool:# system.information_schema.* mirrors mutable data-catalog state (metric approval, relationship# acceptance, source certification). A cached row keeps reporting the pre-change status after a@@ -113,12 +175,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):# p95 duration of HogQL query is 2.78secself.settings.max_execution_time = 10- if self.query.connectionId:- source = get_direct_external_data_source_for_connection(- team_id=self.team.pk, connection_id=self.query.connectionId- )- if source is None:- raise ExposedHogQLError(INVALID_CONNECTION_ID_ERROR)+ self._validate_direct_connection()if self.query.sendRawQuery and self.query.connectionId:return execute_hogql_query(diff --git a/posthog/hogql_queries/query_runner.py b/posthog/hogql_queries/query_runner.pyindex 32fb6e1cce78..d9b5961c4e40 100644--- a/posthog/hogql_queries/query_runner.py+++ b/posthog/hogql_queries/query_runner.py@@ -1660,6 +1660,9 @@ class QueryRunner(ABC, Generic[Q, R, CR]):def _calculate(self) -> R:raise NotImplementedError()+ def query_status_labels(self) -> list[str] | None:+ return None+def enqueue_async_calculation(self,*,@@ -1698,6 +1701,7 @@ class QueryRunner(ABC, Generic[Q, R, CR]):query_json=self.query.model_dump(),query_id=self.query_id or cache_manager.cache_key, # Use cache key as query ID to avoid duplicatescache_key=cache_manager.cache_key,+ labels=self.query_status_labels(),refresh_requested=refresh_requested,is_query_service=self.is_query_service,is_posthog_ai=self.limit_context == LimitContext.POSTHOG_AI,diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.pyindex 8a10e02694b7..e36156c3815b 100644--- a/posthog/hogql_queries/test/test_hogql_query_runner.py+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py@@ -2,7 +2,7 @@ from datetime import UTC, datetimefrom typing import castfrom posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, _create_person, flush_persons_and_events-from unittest.mock import patch+from unittest.mock import MagicMock, patchfrom parameterized import parameterized@@ -13,6 +13,7 @@ from posthog.schema import (HogQLQuery,HogQLQueryResponse,HogQLVariable,+ QueryStatus,)from posthog.hogql import ast@@ -22,10 +23,12 @@ from posthog.hogql.visitor import clear_locationsfrom posthog.caching.utils import ThresholdMode, staleness_threshold_mapfrom posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner+from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models.utils import UUIDT+from products.managed_warehouse.backend.facade.feature_flags import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIXfrom products.product_analytics.backend.models.insight_variable import InsightVariable-from products.warehouse_sources.backend.facade.models import ExternalDataSource+from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX, ExternalDataSourcefrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -226,6 +229,123 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):with self.assertRaises(ExposedHogQLError):runner.calculate()+ @patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ return_value=True,+ )+ @patch("posthog.hogql_queries.hogql_query_runner.execute_hogql_query")+ def test_managed_warehouse_cache_and_status_are_not_revoked_by_picker_flag(+ self, mock_execute_hogql_query: MagicMock, managed_warehouse_sql_editor_flag: MagicMock+ ) -> None:+ source = ExternalDataSource.objects.create(+ source_id="managed-source",+ connection_id="managed-connection",+ destination_id="managed-destination",+ team=self.team,+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.POSTGRES,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=True,+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": True,+ },+ job_inputs={+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": f"posthog_team_{self.team.id}",+ "password": "reader-password",+ },+ )+ 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=[])++ runner = self._create_runner(query)+ expected_query_status_labels = [f"{MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX}{source.id}"]+ self.assertEqual(runner.query_status_labels(), expected_query_status_labels)+ built_in_cache_key = runner.get_cache_key()+ response = cast(+ HogQLQueryResponse,+ runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS),+ )+ self.assertEqual(response.results, [(1,)])++ with patch(+ "posthog.hogql_queries.query_runner.enqueue_process_query_task",+ return_value=QueryStatus(id="managed-query", team_id=self.team.id),+ ) as enqueue_process_query_task:+ self._create_runner(query).run(execution_mode=ExecutionMode.CALCULATE_ASYNC_ALWAYS)+ self.assertEqual(+ enqueue_process_query_task.call_args.kwargs["labels"],+ expected_query_status_labels,+ )++ managed_warehouse_sql_editor_flag.return_value = False+ flag_off_runner = self._create_runner(query)+ self.assertEqual(flag_off_runner.query_status_labels(), expected_query_status_labels)+ self.assertEqual(flag_off_runner.get_cache_key(), built_in_cache_key)+ flag_off_response = cast(+ HogQLQueryResponse,+ flag_off_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS),+ )+ self.assertEqual(flag_off_response.results, [(1,)])++ assert isinstance(source.connection_metadata, dict)+ source.connection_metadata["reader_configured"] = False+ source.save(update_fields=["connection_metadata"])+ with self.assertRaisesMessage(ExposedHogQLError, "Invalid connectionId"):+ self._create_runner(query).run()++ self.assertEqual(mock_execute_hogql_query.call_count, 2)+ managed_warehouse_sql_editor_flag.assert_not_called()++ @patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ return_value=True,+ )+ def test_legacy_managed_cache_and_status_are_not_changed_by_picker_flag(+ self, managed_warehouse_sql_editor_flag: MagicMock+ ) -> None:+ source = ExternalDataSource.objects.create(+ source_id="managed-source",+ connection_id="managed-connection",+ destination_id="managed-destination",+ team=self.team,+ status=ExternalDataSource.Status.COMPLETED,+ source_type=ExternalDataSourceType.POSTGRES,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=True,+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ },+ job_inputs={+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": "org-root",+ "password": "root-password",+ },+ )+ query = HogQLQuery(query="select 1::int as value", connectionId=str(source.id), sendRawQuery=True)++ flag_on_runner = self._create_runner(query)+ self.assertIsNone(flag_on_runner.query_status_labels())+ self.assertNotIn("managed_warehouse_sql_mode", flag_on_runner.get_cache_payload())+ flag_on_cache_key = flag_on_runner.get_cache_key()++ managed_warehouse_sql_editor_flag.return_value = False+ flag_off_runner = self._create_runner(query)+ self.assertIsNone(flag_off_runner.query_status_labels())+ self.assertEqual(flag_off_runner.get_cache_key(), flag_on_cache_key)+ managed_warehouse_sql_editor_flag.assert_not_called()+@patch("posthog.hogql_queries.hogql_query_runner.execute_hogql_query")def test_send_raw_query_uses_raw_query_string_for_direct_connections(self, mock_execute_hogql_query):source = ExternalDataSource.objects.create(diff --git a/posthog/psycopg_helpers.py b/posthog/psycopg_helpers.pynew file mode 100644index 000000000000..c144353b684e--- /dev/null+++ b/posthog/psycopg_helpers.py@@ -0,0 +1,69 @@+import socket+import ipaddress+import threading+from collections.abc import Callable+from time import monotonic+from typing import Any++import psycopg+++def resolve_psycopg_hostaddr_with_timeout(+ host: str,+ port: int,+ timeout: float,+ *,+ fail_on_resolution_error: bool = False,+ abort_check: Callable[[], None] | None = None,+) -> list[str] | None:+ """Resolve a hostname before psycopg's unbounded Python-side DNS lookup."""+ if not host or host.startswith("/"):+ return None++ try:+ ipaddress.ip_address(host.strip("[]"))+ return None+ except ValueError:+ pass++ addrinfo: list[Any] = []+ lookup_error: list[BaseException] = []++ def _lookup() -> None:+ try:+ addrinfo.extend(socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM))+ except BaseException as error: # noqa: BLE001 — re-raised on the calling thread below+ lookup_error.append(error)++ # A daemon lets the caller abandon a stalled OS resolver without pinning the query worker.+ thread = threading.Thread(target=_lookup, daemon=True)+ thread.start()+ deadline = monotonic() + timeout+ while thread.is_alive():+ if abort_check is not None:+ abort_check()+ remaining_seconds = deadline - monotonic()+ if remaining_seconds <= 0:+ raise psycopg.OperationalError(f"Timed out resolving database host name after {timeout}s")+ thread.join(min(remaining_seconds, 1.0 if abort_check is not None else remaining_seconds))+ if abort_check is not None:+ abort_check()+ if lookup_error:+ if isinstance(lookup_error[0], OSError):+ if fail_on_resolution_error:+ raise psycopg.OperationalError("Could not resolve database host name") from lookup_error[0]+ return None+ raise lookup_error[0]+ if not addrinfo:+ if fail_on_resolution_error:+ raise psycopg.OperationalError("Could not resolve database host name")+ return None++ seen: set[str] = set()+ addresses: list[str] = []+ for info in addrinfo:+ address = str(info[4][0])+ if address not in seen:+ seen.add(address)+ addresses.append(address)+ return addressesdiff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.pyindex 36cb109ad60b..65b1b123afc5 100644--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py@@ -1084,10 +1084,11 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):resp = managed_warehouse.status_for(self.team.organization_id)if resp.status_code == 200 and isinstance(resp.data, dict):resp.data.update(managed_warehouse.team_backfill_state(self.team_id))- resp.data.update(managed_warehouse.team_onboarding_state(self.team.organization_id, self.team_id))+ onboarding_state = managed_warehouse.team_onboarding_state(self.team.organization_id, self.team_id)+ resp.data.update(onboarding_state)# Once the warehouse is reachable, surface its tables as a queryable direct- # connection. Best-effort scheduling coalesces repeated scene loads.- if resp.data.get("state") == "ready":+ # connection for enrolled projects. Best-effort scheduling coalesces repeated scene loads.+ if resp.data.get("state") == "ready" and onboarding_state["team_onboarded"]:managed_warehouse.ensure_direct_connection_tables(self.team_id, self.team.organization_id)return respdiff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.pyindex fa49d20c0963..e60e7928fecf 100644--- a/products/data_warehouse/backend/tasks/tasks.py+++ b/products/data_warehouse/backend/tasks/tasks.py@@ -47,10 +47,10 @@ EXTERNAL_DATA_FAILURE_DIGEST_DELAY_SECONDS = 15 * 60# Generous bound on one digest build + synchronous send; the lock auto-expires# after this if a worker dies mid-flight.EXTERNAL_DATA_FAILURE_DIGEST_LOCK_TIMEOUT_SECONDS = 120-# Live introspection of a large catalog can far exceed the digest bound; the-# select_for_update guards make an overlap harmless, but keep the lock long enough-# that it stays the normal exclusion mechanism.-MANAGED_WAREHOUSE_RECONCILE_LOCK_TIMEOUT_SECONDS = 600+# A team can have both a legacy and a project-reader catalog, and each metadata query+# has a 10-minute database timeout. Cover both serial queries so another task cannot+# overlap the catalog writes near the old lock boundary.+MANAGED_WAREHOUSE_RECONCILE_LOCK_TIMEOUT_SECONDS = 30 * 60MANAGED_WAREHOUSE_RECONCILE_INTERVAL_SECONDS = 60diff --git a/products/data_warehouse/backend/tests/api/test_data_warehouse.py b/products/data_warehouse/backend/tests/api/test_data_warehouse.pyindex b108a2f5220e..98c083f14b9a 100644--- a/products/data_warehouse/backend/tests/api/test_data_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_data_warehouse.py@@ -8,6 +8,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status+from rest_framework.response import Responsefrom products.dashboards.backend.models.dashboard import Dashboardfrom products.dashboards.backend.models.dashboard_tile import DashboardTile@@ -22,6 +23,40 @@ from products.warehouse_sources.backend.facade.models import (class TestDataWarehouseAPI(APIBaseTest):+ @parameterized.expand(+ [+ ("onboarded", True, True),+ ("not_onboarded", False, False),+ ]+ )+ def test_ready_warehouse_reconciles_only_onboarded_project(+ self, _name: str, team_onboarded: bool, expected_schedule: bool+ ) -> None:+ with (+ patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.status_for",+ return_value=Response({"state": "ready"}, status=200),+ ),+ patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.team_backfill_state",+ return_value={"has_backfill": team_onboarded, "table_suffix": "prod" if team_onboarded else None},+ ),+ patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.team_onboarding_state",+ return_value={"team_onboarded": team_onboarded, "schema_name": "prod" if team_onboarded else None},+ ),+ patch(+ "products.data_warehouse.backend.presentation.views.data_warehouse.managed_warehouse.ensure_direct_connection_tables"+ ) as ensure_tables,+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/data_warehouse/warehouse_status/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ if expected_schedule:+ ensure_tables.assert_called_once_with(self.team.id, self.organization.id)+ else:+ ensure_tables.assert_not_called()+@patch("products.data_warehouse.backend.presentation.views.data_warehouse.execute_hogql_query")def test_property_values_returns_results_with_cache_control(self, mock_execute_hogql_query):table = DataWarehouseTable.objects.create(diff --git a/products/managed_warehouse/backend/client.py b/products/managed_warehouse/backend/client.pyindex a4feed4d0ca3..8d8db7264f5f 100644--- a/products/managed_warehouse/backend/client.py+++ b/products/managed_warehouse/backend/client.py@@ -45,20 +45,20 @@ def make_duckgres_conninfo() -> str:"""Build a psycopg conninfo for a team's duckgres server.- Default (no ``service_credential``): the org-root username/password from- the stored ``DuckgresServer`` row — the transitional path used by the SQL- editor and materialization until they move to minted credentials.+ Default (no ``service_credential``): use the username/password from the+ stored ``DuckgresServer`` row. Materialization and internal warehouse+ helpers inherit the permissions of that login.With ``service_credential``: connect with a CP-issued, org-scopedper-credential grant (``svc_…`` credential_id + secret), short-lived anddisposable. This is what background jobs (dagster) should present; see``products/managed_warehouse/backend/service_credentials.py``.Host/port/database/sslmode come ENTIRELY from the credential's- CP-issued ``connect`` block — this branch never reads the stored- ``DuckgresServer`` row (the row is being deleted as a host store).+ CP-issued ``connect`` block, so this branch is independent of the stored+ ``DuckgresServer`` row.Service credentials are only mintable for a provisioned production- warehouse, so dev-mode is rejected loudly rather than silently- downgraded to root.+ warehouse, so dev-mode is rejected rather than silently using the+ environment-configured login.``application_name`` is forwarded to duckgres as a standard libpq startupparam and echoed into its analytics events, so callers should pass adiff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.pyindex a783517c4f3d..c229e4bd3c9a 100644--- a/products/managed_warehouse/backend/facade/contracts.py+++ b/products/managed_warehouse/backend/facade/contracts.py@@ -97,7 +97,7 @@ class ServiceCredential:class ServiceCredentialUnavailable(RuntimeError):"""The control plane couldn't issue a service credential (unreachable,org/team not provisioned, or a 5xx). Callers decide whether to fall back- to stored org-root credentials (transitional) or fail the run."""+ to the stored server login or fail the run."""@dataclass(frozen=True, kw_only=True)diff --git a/products/managed_warehouse/backend/facade/feature_flags.py b/products/managed_warehouse/backend/facade/feature_flags.pynew file mode 100644index 000000000000..5372db97ba17--- /dev/null+++ b/products/managed_warehouse/backend/facade/feature_flags.py@@ -0,0 +1,26 @@+from typing import TYPE_CHECKING++import structlog++from posthog.permissions import posthog_feature_flag_enabled++if TYPE_CHECKING:+ from posthog.models import Team++logger = structlog.get_logger(__name__)++MANAGED_WAREHOUSE_SQL_EDITOR_FLAG = "managed-warehouse-sql-editor"+MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX = f"{MANAGED_WAREHOUSE_SQL_EDITOR_FLAG}:"+++def is_managed_warehouse_sql_editor_enabled(team: "Team") -> bool:+ try:+ return posthog_feature_flag_enabled(+ MANAGED_WAREHOUSE_SQL_EDITOR_FLAG,+ str(team.uuid),+ organization_id=team.organization_id,+ team_id=team.id,+ )+ except Exception:+ logger.exception("managed_warehouse_sql_editor_feature_flag_check_failed", team_id=team.id)+ return Falsediff --git a/products/managed_warehouse/backend/logic/connection.py b/products/managed_warehouse/backend/logic/connection.pyindex 55463ebcbf0b..ec1068495d37 100644--- a/products/managed_warehouse/backend/logic/connection.py+++ b/products/managed_warehouse/backend/logic/connection.py@@ -1,23 +1,14 @@"""Expose a managed Duckgres warehouse in the SQL editor as a Postgres connection.-Each member team gets a Postgres ``ExternalDataSource`` pointed at the organization's-``DuckgresServer``, authenticated with the server's org root credential. Duckgres root-sees every schema in the warehouse, so the connection discovers and exposes the whole-org catalog without per-team namespace configuration — no control-plane handshake is-involved in setting it up. Setup happens in two steps:--1. ``ensure_managed_warehouse_direct_source`` creates the source row when a team- joins, so the connection appears immediately.-2. ``reconcile_managed_warehouse_tables`` runs once the warehouse is ready and records- every non-internal schema/table the root credential can see.+Each enrolled team keeps its auto-provisioned external source backed by the stored server+login. If a confirmed ``project_reader`` source also exists, it has an independent catalog.+This module does not create, replace, or rotate project readers.This bypasses the user-facing create endpoint because the managed host is internalinfrastructure and is not reachable for live schema validation during provisioning.-Lifecycle is org-level only: ``soft_delete_managed_warehouse_sources`` handles-deprovisioning of the whole warehouse. There is no per-team offboarding flow yet —-a single team leaving keeps its connection until the org deprovisions (revisit if-per-team removal becomes a product flow).+``soft_delete_managed_warehouse_sources`` handles deprovisioning of the whole warehouse.+Deleting a team removes its project-scoped source through the existing model cascade."""from __future__ import annotations@@ -35,10 +26,13 @@ from posthog.models.team.team import Teamfrom products.data_warehouse.backend.facade.api import reconcile_postgres_schemasfrom products.managed_warehouse.backend.models import DuckgresServerfrom products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS,+ MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,MANAGED_WAREHOUSE_SOURCE_PREFIX,DataWarehouseTable,ExternalDataSchema,ExternalDataSource,+ ManagedWarehouseSQLMode,)from products.warehouse_sources.backend.facade.source_management import SourceRegistryfrom products.warehouse_sources.backend.facade.types import ExternalDataSourceType@@ -48,8 +42,7 @@ logger = structlog.get_logger(__name__)MANAGED_WAREHOUSE_SOURCE_DESCRIPTION = "Managed warehouse (auto-provisioned)"# Database engine internals — never warehouse data. Sidebar hygiene, not permissioning:-# root bypasses Duckgres AllowedSchemas, so this denylist is the only filter on what the-# discover sweep registers. The later per-schema visibility control plugs in here.+# The discovery login may expose engine internals, so this denylist keeps them out of the sidebar.INTERNAL_SCHEMAS = frozenset({"pg_catalog", "information_schema", "pg_toast", "system"})@@ -68,7 +61,7 @@ def _managed_source_queryset(team_id: int) -> QuerySet[ExternalDataSource]:def _source_config(server: DuckgresServer) -> dict[str, object]:- """Snapshot the server's org root credential into the source's job_inputs."""+ """Snapshot the stored server login into the source's job_inputs."""source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)return source_impl.parse_config({@@ -81,18 +74,30 @@ def _source_config(server: DuckgresServer) -> dict[str, object]:).to_dict()-def _ensure_managed_source_locked(*, team_id: int, server: DuckgresServer) -> ExternalDataSource:- # Deliberately includes soft-deleted rows: a re-enabled membership revives its- # tombstoned source.- existing = _managed_source_queryset(team_id).select_for_update().order_by("-created_at").first()+def _is_project_reader_source(source: ExternalDataSource) -> bool:+ metadata = source.connection_metadata+ return (+ isinstance(metadata, dict)+ and metadata.get("credential_kind") == MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND+ )+++def _ensure_stored_login_source_locked(*, team_id: int, server: DuckgresServer) -> ExternalDataSource:+ existing = next(+ (+ source+ for source in _managed_source_queryset(team_id).select_for_update().order_by("deleted", "-created_at")+ if not _is_project_reader_source(source)+ ),+ None,+ )config = _source_config(server)if existing is not None:update_fields: list[str] = []connection_metadata = dict(existing.connection_metadata or {})- if connection_metadata.get("credential_kind") not in ("org_root", "project_reader"):- # Old managed sources predate the project-reader credential boundary, so- # discard any catalog entries discovered before Duckgres enforced it.+ if connection_metadata.get("credential_kind") not in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS:+ # Catalog rows discovered with an unknown credential scope cannot be reused safely.now = timezone.now()DataWarehouseTable.raw_objects.filter(team_id=team_id, external_data_source_id=existing.id, deleted=False@@ -151,62 +156,71 @@ def _ensure_managed_source_locked(*, team_id: int, server: DuckgresServer) -> Exdef ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> ExternalDataSource:- """Create or refresh the team's managed-warehouse query source on the org root credential."""+ """Create or refresh the external source backed by the stored server login."""with transaction.atomic():server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)- return _ensure_managed_source_locked(team_id=team_id, server=server)+ return _ensure_stored_login_source_locked(team_id=team_id, server=server)-def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:- """Discover and register the org-wide managed-warehouse catalog for this team's source."""+def _reconcile_managed_warehouse_source(+ *,+ team_id: int,+ organization_id: str | UUID,+ source_id: UUID,+ expected_mode: ManagedWarehouseSQLMode,+) -> None:with transaction.atomic():- # Check before ensure: a tombstoned source means the warehouse was deprovisioned- # (its DuckgresServer row is deleted synchronously), and nothing may revive it —- # otherwise this sweep would resurrect sources right after deprovision.- if _managed_source_queryset(team_id).filter(deleted=True).exists():- return-- try:- ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)- except (DuckgresServer.DoesNotExist, Team.DoesNotExist):- return-- with transaction.atomic():- server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()+ if expected_mode == ManagedWarehouseSQLMode.EXTERNAL:+ server_exists = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).exists()+ if not server_exists:+ returnteam = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()- if server is None or team is None:+ if team is None:return- source = _managed_source_queryset(team_id).select_for_update().filter(deleted=False).first()- if source is None:+ source = (+ _managed_source_queryset(team_id)+ .select_for_update()+ .filter(+ id=source_id,+ deleted=False,+ )+ .first()+ )+ if source is None or source.managed_warehouse_sql_mode != expected_mode:return- source_id = source.idsource_config = dict(source.job_inputs or {})source_api_version = source.api_versionexcluded_schemas = internal_schemas()source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)- config = source_impl.parse_config(source_config)try:+ 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))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)+ logger.warning(+ "Managed warehouse introspection failed; will retry",+ team_id=team_id,+ source_id=source_id,+ source_mode=expected_mode,+ exc_info=True,+ )returnsource_schemas = [schema for schema in discovered if (schema.source_schema or "") not in excluded_schemas]- if not source_schemas:- return-with transaction.atomic():# Revalidate after live introspection so deprovision wins the race.- server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()+ if expected_mode == ManagedWarehouseSQLMode.EXTERNAL:+ server_exists = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).exists()+ if not server_exists:+ returnteam = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()- if server is None or team is None:+ if team is None:returnsource = (_managed_source_queryset(team_id)@@ -215,11 +229,10 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | Uid=source_id,deleted=False,access_method=ExternalDataSource.AccessMethod.DIRECT,- direct_query_enabled=True,).first())- if source is None:+ if source is None or source.managed_warehouse_sql_mode != expected_mode:returnfor schema in source_schemas:@@ -238,6 +251,48 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | Ureconcile_postgres_schemas(source=source, source_schemas=source_schemas, team_id=team_id)+def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:+ """Discover each live managed-warehouse catalog using that source's own credentials."""+ legacy_source_id: UUID | None = None+ reader_source_id: UUID | None = None+ try:+ with transaction.atomic():+ server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()+ Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)+ sources = list(_managed_source_queryset(team_id).select_for_update().order_by("-created_at"))+ has_tombstone = any(source.deleted for source in sources)+ has_live_legacy_source = any(+ not source.deleted and not _is_project_reader_source(source) for source in sources+ )+ # Explicit reprovisioning revives one mode; tombstones left for the other mode remain authoritative.+ if server is not None and (not has_tombstone or has_live_legacy_source):+ legacy_source_id = _ensure_stored_login_source_locked(team_id=team_id, server=server).id++ reader_source = next(+ (source for source in sources if not source.deleted and source.is_managed_warehouse_ready),+ None,+ )+ if reader_source is not None:+ reader_source_id = reader_source.id+ except Team.DoesNotExist:+ return++ if legacy_source_id is not None:+ _reconcile_managed_warehouse_source(+ team_id=team_id,+ organization_id=organization_id,+ source_id=legacy_source_id,+ expected_mode=ManagedWarehouseSQLMode.EXTERNAL,+ )+ if reader_source_id is not None:+ _reconcile_managed_warehouse_source(+ team_id=team_id,+ organization_id=organization_id,+ source_id=reader_source_id,+ expected_mode=ManagedWarehouseSQLMode.BUILT_IN,+ )++def _managed_sources_for_org(organization_id: str | UUID) -> QuerySet[ExternalDataSource]:return ExternalDataSource._base_manager.filter(team__organization_id=organization_id,@@ -248,11 +303,10 @@ def _managed_sources_for_org(organization_id: str | UUID) -> QuerySet[ExternalDadef update_managed_warehouse_root_password(*, organization_id: str | UUID, password: str) -> None:- """Rotate the root password on the server row and every managed source of the org.+ """Rotate the stored root password without modifying project-reader sources.- Each source snapshots the root credential into its ``job_inputs``, so a rotation must- fan out to all of them in the same transaction — otherwise every source holds a stale- password and fails silently.+ Stored-login sources snapshot the root credential into ``job_inputs``. Project-reader+ passwords have a separate lifecycle and must remain unchanged."""with transaction.atomic():server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)@@ -261,17 +315,15 @@ def update_managed_warehouse_root_password(*, organization_id: str | UUID, passwconfig = _source_config(server)for source in _managed_sources_for_org(organization_id).select_for_update().order_by("team_id"):+ if _is_project_reader_source(source):+ continueif source.job_inputs != config:source.job_inputs = configsource.save(update_fields=["job_inputs", "updated_at"])def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID) -> None:- """Atomically tombstone the organization's managed query sources on deprovision.-- Per-team state needs no disabling here: deprovisioning removes the org's team rows- from the duckgres control plane, which is the read source for membership.- """+ """Atomically tombstone the organization's managed query sources on deprovision."""now = timezone.now()with transaction.atomic():DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()diff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.pyindex 675444ec19d8..ccc1c0f159f5 100644--- a/products/managed_warehouse/backend/presentation/views.py+++ b/products/managed_warehouse/backend/presentation/views.py@@ -355,8 +355,8 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int) -> Noduckgres creates the provisioning team's row from the provision request itself (and`_complete_provisioning_team_row` pins its legacy table names), so nothing is written- here — the team just gets its SQL-editor query connection and its earliest-event-date- sync kicked off, the same tail `onboard_team` runs for later teams.+ here. The team gets its auto-provisioned external SQL source and starts its+ earliest-event-date sync, matching the tail that `onboard_team` runs later.Best-effort, mirroring `_persist_duckgres_server`: a failure is logged, not raised, sothe one-time provision password is never lost to it.@@ -369,11 +369,10 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int) -> Nodef _ensure_direct_source(team_id: int, organization_id: UUID | str) -> None:- """Best-effort: register the org's managed warehouse as the team's query connection.+ """Best-effort: create or refresh the team's external managed-warehouse source.- A managed warehouse speaks the Postgres wire protocol, so each member team gets an- ExternalDataSource pointed at the org server and authenticated with its org root- credential. A failure here must never block onboarding.+ This snapshots the stored DuckgresServer login. Project-reader provisioning has a+ separate lifecycle, and this path never creates or modifies one."""try:from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415diff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.pyindex d843a52be588..ae01dd1d0c67 100644--- a/products/managed_warehouse/backend/service_credentials.py+++ b/products/managed_warehouse/backend/service_credentials.py@@ -4,8 +4,8 @@ This is the PostHog-side half of the duckgres "Service Credentials" contract(see duckgres/CLAUDE.md). A background job (dagster today) calls``mint_service_credential`` once per run to get a credential scoped to theorg's warehouse access — minted as its own server-side grant ROW (not a-rewrite of a shared team login's hash) — instead of reading the org-wide-root credential out of a ``DuckgresServer`` row.+rewrite of a shared team login's hash) instead of reading the stored login+out of a ``DuckgresServer`` row.Contract essentials mirrored here (read the CP side for the authoritativewording):@@ -236,8 +236,7 @@ def _parse_connect(data: dict[str, Any], *, action: str = "mint") -> ServiceCredconnect-bundle change. A 2xx without it means the CP is older than thecontract; the service-credential conninfo builder no longer reads the``DuckgresServer`` row, so there is nothing to fall back to here and we- raise ``ServiceCredentialUnavailable`` (the caller's broad fallback to- root engages — the established transitional degradation).+ raise ``ServiceCredentialUnavailable`` so the caller can apply its configured fallback."""raw = data.get("connect")if not isinstance(raw, dict):diff --git a/products/managed_warehouse/backend/tests/test_client_service_credentials.py b/products/managed_warehouse/backend/tests/test_client_service_credentials.pyindex 851f732aaba1..00aadbcbac94 100644--- a/products/managed_warehouse/backend/tests/test_client_service_credentials.py+++ b/products/managed_warehouse/backend/tests/test_client_service_credentials.py@@ -24,6 +24,27 @@ def _credential(secret: str, *, credential_id: str) -> ServiceCredential:)+class TestMakeDuckgresConninfoWithStoredLogin:+ @mock.patch("products.managed_warehouse.backend.client.is_dev_mode", return_value=False)+ @mock.patch("products.managed_warehouse.backend.client.get_duckgres_config_for_org")+ def test_uses_the_current_stored_server_login(self, config, _dev) -> None:+ config.return_value = {+ "DUCKGRES_HOST": "managed.example.com",+ "DUCKGRES_PORT": "5432",+ "DUCKGRES_DATABASE": "ducklake",+ "DUCKGRES_USERNAME": "stored-login",+ "DUCKGRES_PASSWORD": "stored-password",+ }++ conninfo = make_duckgres_conninfo(7, organization_id="org-1")++ config.assert_called_once_with("org-1")+ assert "host=managed.example.com" in conninfo+ assert "dbname=ducklake" in conninfo+ assert "user=stored-login" in conninfo+ assert "password=stored-password" in conninfo++class TestMakeDuckgresConninfoWithServiceCredential:"""client.make_duckgres_conninfo with a service_credential dials theserver-issued credential pair (svc_<id> + plaintext) and the CP-issueddiff --git a/products/managed_warehouse/backend/tests/test_connection.py b/products/managed_warehouse/backend/tests/test_connection.pyindex 632249e376b4..5c39ea12179d 100644--- a/products/managed_warehouse/backend/tests/test_connection.py+++ b/products/managed_warehouse/backend/tests/test_connection.py@@ -3,6 +3,8 @@ from typing import TypedDictimport pytestfrom unittest.mock import MagicMock, patch+from parameterized import parameterized+from posthog.hogql.direct_connection import get_direct_connection_sourcefrom posthog.hogql.query import HogQLQueryExecutor@@ -24,8 +26,16 @@ from products.managed_warehouse.backend.logic.connection import ()from products.managed_warehouse.backend.models import DuckgresServerfrom products.managed_warehouse.backend.presentation import views as managed_warehouse-from products.warehouse_sources.backend.facade.models import DataWarehouseTable, ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,+ DataWarehouseTable,+ ExternalDataSchema,+ ExternalDataSource,+)from products.warehouse_sources.backend.facade.source_management import SourceSchema+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (+ PostgresSourceConfig,+)class _Connection(TypedDict):@@ -44,10 +54,11 @@ _CONNECTION: _Connection = {"password": "pw",}+_PROJECT_READER_PASSWORD = "project-reader-password"-# Per-test control-plane membership rows, keyed by org id. The CP is the read source for-# the periodic sweep's team enumeration, so tests register rows here instead of creating-# Django rows — the per-team connection itself no longer consults the control plane.++# Per-test control-plane membership rows, keyed by org id. The periodic sweep uses+# these rows to schedule reconciliation for enrolled projects._MEMBERSHIPS: dict[str, list[ManagedWarehouseTeamMembership]] = {}@@ -108,144 +119,195 @@ def _create_server(org: Organization, **overrides: object) -> DuckgresServer:return DuckgresServer.objects.create(organization=org, **{**_CONNECTION, **overrides})-class TestEnsureManagedWarehouseDirectSource:- def test_creates_a_query_source_with_the_org_root_credential(self) -> None:- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- _create_server(org)+def _create_project_reader_source(+ team: Team,+ *,+ reader_configured: bool = True,+ direct_query_enabled: bool = True,+) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team,+ source_id=f"managed-source-{team.id}",+ connection_id=f"managed-connection-{team.id}",+ destination_id=f"managed-destination-{team.id}",+ status=ExternalDataSource.Status.RUNNING,+ source_type="Postgres",+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=direct_query_enabled,+ job_inputs={+ "host": _CONNECTION["host"],+ "port": _CONNECTION["port"],+ "database": _CONNECTION["database"],+ "user": f"posthog_team_{team.id}",+ "password": _PROJECT_READER_PASSWORD,+ },+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,+ "reader_configured": reader_configured,+ },+ )- source = _ensure(team)- assert source.source_type == "Postgres"- assert source.access_method == ExternalDataSource.AccessMethod.DIRECT- assert source.direct_query_enabled is True- assert isinstance(source.connection_metadata, dict)- assert source.connection_metadata["engine"] == "duckdb"- assert source.prefix == MANAGED_WAREHOUSE_SOURCE_PREFIX- # job_inputs carry the org root credential so live queries see every schema.- assert source.job_inputs["host"] == _CONNECTION["host"]- assert source.job_inputs["user"] == _CONNECTION["username"]- assert source.job_inputs["password"] == _CONNECTION["password"]- assert source.connection_metadata["credential_kind"] == "org_root"-- def test_is_idempotent(self) -> None:- # Without dedup, every status poll / re-enable would spawn a duplicate connection.- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- _create_server(org)-- first = _ensure(team)- second = _ensure(team)+def _create_stored_login_source(team: Team) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=team,+ source_id=f"stored-source-{team.id}",+ connection_id=f"stored-connection-{team.id}",+ destination_id=f"stored-destination-{team.id}",+ status=ExternalDataSource.Status.RUNNING,+ source_type="Postgres",+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ direct_query_enabled=True,+ job_inputs={+ "host": _CONNECTION["host"],+ "port": _CONNECTION["port"],+ "database": _CONNECTION["database"],+ "user": _CONNECTION["username"],+ "password": _CONNECTION["password"],+ },+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "stored_server_login",+ },+ )- assert first.pk == second.pk- assert ExternalDataSource.objects.filter(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX).count() == 1- def test_works_for_a_legacy_shared_tables_team(self) -> None:- # No per-team reader policy exists anymore, so nothing about the team's row- # layout (including the legacy shared tables) blocks its connection.+class TestEnsureManagedWarehouseDirectSource:+ def test_creates_a_stored_login_source_when_project_reader_is_missing(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)_create_server(org)- _add_membership(team, legacy_shared=True)source = _ensure(team)- assert source.direct_query_enabled is True- assert isinstance(source.connection_metadata, dict)- assert source.connection_metadata["credential_kind"] == "org_root"+ assert source.is_legacy_managed_warehouse+ assert ExternalDataSource.objects.filter(team_id=team.id).count() == 1- def test_needs_no_control_plane_membership(self) -> None:- # Root needs no handshake: a team the control plane doesn't know about still- # gets its connection.+ def test_creates_a_stored_login_source_without_overwriting_a_project_reader(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)_create_server(org)+ reader = _create_project_reader_source(team)+ reader.refresh_from_db()+ assert isinstance(reader.job_inputs, dict)+ original_reader_inputs = dict(reader.job_inputs)source = _ensure(team)+ source.refresh_from_db()+ reader.refresh_from_db()+ assert source.id != reader.id+ assert source.description == "Managed warehouse (auto-provisioned)"+ assert source.access_method == ExternalDataSource.AccessMethod.DIRECTassert source.direct_query_enabled is True- assert isinstance(source.connection_metadata, dict)- assert source.connection_metadata["credential_kind"] == "org_root"+ assert isinstance(source.job_inputs, dict)+ assert {key: source.job_inputs[key] for key in ("host", "port", "database", "user", "password")} == {+ "host": _CONNECTION["host"],+ "port": str(_CONNECTION["port"]),+ "database": _CONNECTION["database"],+ "user": _CONNECTION["username"],+ "password": _CONNECTION["password"],+ }+ assert source.connection_metadata == {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ }+ assert reader.job_inputs == original_reader_inputs+ assert reader.is_managed_warehouse_ready- def test_refreshes_a_project_reader_source_onto_the_root_credential(self) -> None:+ def test_refreshes_the_existing_stored_login_source(self) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)- _create_server(org)- source = ExternalDataSource.objects.create(- team=team,- source_id="managed-source",- connection_id="managed-connection",- destination_id="managed-destination",- status=ExternalDataSource.Status.RUNNING,- source_type="Postgres",- prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,- access_method=ExternalDataSource.AccessMethod.DIRECT,- direct_query_enabled=True,- job_inputs={- "host": _CONNECTION["host"],- "port": _CONNECTION["port"],- "database": _CONNECTION["database"],- "user": f"posthog_team_{team.id}",- "password": "reader-password",- },- connection_metadata={- "engine": "duckdb",- "system_managed": True,- "credential_kind": "project_reader",- "reader_configured": True,- },- )- team_schema = ExternalDataSchema.objects.create(+ _create_server(org, password="new-password")+ reader = _create_project_reader_source(team)+ source = _create_stored_login_source(team)+ source.job_inputs = {**(source.job_inputs or {}), "password": "stale-password"}+ source.access_method = ExternalDataSource.AccessMethod.WAREHOUSE+ source.direct_query_enabled = False+ source.deleted = True+ source.save(update_fields=["job_inputs", "access_method", "direct_query_enabled", "deleted"])++ refreshed = _ensure(team)++ refreshed.refresh_from_db()+ reader.refresh_from_db()+ assert refreshed.id == source.id+ assert isinstance(refreshed.job_inputs, dict)+ assert refreshed.job_inputs["password"] == "new-password"+ assert refreshed.access_method == ExternalDataSource.AccessMethod.DIRECT+ assert refreshed.direct_query_enabled is True+ assert refreshed.deleted is False+ assert isinstance(refreshed.connection_metadata, dict)+ assert refreshed.connection_metadata["credential_kind"] == "org_root"+ assert isinstance(reader.job_inputs, dict)+ assert reader.job_inputs["password"] == _PROJECT_READER_PASSWORD+ assert reader.is_managed_warehouse_ready++ def test_missing_server_does_not_modify_a_ready_project_reader(self) -> None:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ source = _create_project_reader_source(team)+ assert isinstance(source.connection_metadata, dict)+ source.connection_metadata = {**source.connection_metadata, "provisioner_marker": "keep"}+ source.save(update_fields=["connection_metadata"])+ source.refresh_from_db()+ schema = ExternalDataSchema.objects.create(team=team,source=source,name="posthog.events_prod",should_sync=True,)+ assert isinstance(source.job_inputs, dict)+ assert isinstance(source.connection_metadata, dict)+ original_job_inputs = dict(source.job_inputs)+ original_metadata = dict(source.connection_metadata)++ with pytest.raises(DuckgresServer.DoesNotExist):+ _ensure(team)- managed_source = _ensure(team)-- managed_source.refresh_from_db()- team_schema.refresh_from_db()- assert managed_source.id == source.id- assert managed_source.job_inputs["user"] == _CONNECTION["username"]- assert managed_source.job_inputs["password"] == _CONNECTION["password"]- assert managed_source.direct_query_enabled is True- assert isinstance(managed_source.connection_metadata, dict)- assert managed_source.connection_metadata["credential_kind"] == "org_root"- assert "reader_configured" not in managed_source.connection_metadata- # Reader-discovered catalogs are already bounded and stay in place; only the- # swappable credential changes.- assert team_schema.deleted is False-- def test_removes_existing_schemas_when_upgrading_a_root_managed_source(self) -> None:+ source.refresh_from_db()+ assert source.job_inputs == original_job_inputs+ assert source.connection_metadata == original_metadata+ assert ExternalDataSchema.objects.filter(id=schema.id, deleted=False).exists()++ @parameterized.expand(+ [+ (False, False),+ (False, True),+ (True, False),+ ]+ )+ def test_creates_legacy_without_promoting_or_replacing_an_unready_project_reader(+ self, reader_configured: bool, direct_query_enabled: bool+ ) -> None:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)_create_server(org)- source = ExternalDataSource.objects.create(- team=team,- source_id="managed-source",- connection_id="managed-connection",- destination_id="managed-destination",- status=ExternalDataSource.Status.RUNNING,- source_type="Postgres",- prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,- access_method=ExternalDataSource.AccessMethod.DIRECT,- job_inputs={"password": "old-password"},- connection_metadata={"engine": "duckdb", "system_managed": True},- )- schema = ExternalDataSchema.objects.create(- team=team,- source=source,- name="events_other_team",- should_sync=True,+ source = _create_project_reader_source(+ team,+ reader_configured=reader_configured,+ direct_query_enabled=direct_query_enabled,)+ source.refresh_from_db()+ assert isinstance(source.job_inputs, dict)+ original_job_inputs = dict(source.job_inputs)- managed_source = _ensure(team)+ legacy_source = _ensure(team)- assert managed_source.id == source.id- assert managed_source.access_method == ExternalDataSource.AccessMethod.DIRECT- assert not ExternalDataSchema.objects.filter(id=schema.id).exists()+ source.refresh_from_db()+ assert legacy_source.id != source.id+ assert legacy_source.is_legacy_managed_warehouse+ assert source.job_inputs == original_job_inputs+ assert isinstance(source.connection_metadata, dict)+ assert source.connection_metadata["reader_configured"] is reader_configured+ assert source.direct_query_enabled is direct_query_enableddef _source_schema(table_name: str, source_schema: str = "posthog") -> SourceSchema:@@ -268,41 +330,41 @@ class TestReconcileManagedWarehouseTables:_add_membership(team)return org, team- def test_discovers_the_whole_org_catalog_and_makes_it_queryable(self) -> None:+ def test_discovers_with_the_existing_project_reader_and_makes_its_catalog_queryable(self) -> None:org, team = self._setup()- other_team = Team.objects.create(organization=org)- # Discovery runs as root, so every team's schema shows up on this team's source;- # only engine-internal schemas are excluded.+ source = _create_project_reader_source(team)+ DuckgresServer.objects.filter(organization=org).delete()discovered = [_source_schema("events_prod"),_source_schema("persons_prod"),- _source_schema("events_other"),_source_schema("customers", "posthog_data_imports_prod"),_source_schema("revenue", f"shadow_{team.id}_models"),_source_schema("future_table", f"team_{team.id}"),- _source_schema("orders", f"team_{other_team.id}"),_source_schema("pg_stat_activity", "pg_catalog"),_source_schema("tables", "information_schema"),]+ def discover(config: PostgresSourceConfig, *_args: object, **_kwargs: object) -> list[SourceSchema]:+ assert config.user == f"posthog_team_{team.id}"+ assert config.password == _PROJECT_READER_PASSWORD+ return discovered+with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",- return_value=discovered,+ side_effect=discover,):reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)- source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)+ source.refresh_from_db()assert source.access_method == ExternalDataSource.AccessMethod.DIRECTassert set(ExternalDataSchema.objects.filter(source_id=source.id, should_sync=True).values_list("name", flat=True)) == {"posthog.events_prod","posthog.persons_prod",- "posthog.events_other","posthog_data_imports_prod.customers",f"shadow_{team.id}_models.revenue",f"team_{team.id}.future_table",- f"team_{other_team.id}.orders",}assert set(DataWarehouseTable.raw_objects.filter(external_data_source_id=source.id, deleted=False).values_list(@@ -311,11 +373,9 @@ class TestReconcileManagedWarehouseTables:) == {"posthog.events_prod","posthog.persons_prod",- "posthog.events_other","posthog_data_imports_prod.customers",f"shadow_{team.id}_models.revenue",f"team_{team.id}.future_table",- f"team_{other_team.id}.orders",}allowed_query = HogQLQueryExecutor(@@ -341,26 +401,157 @@ class TestReconcileManagedWarehouseTables:response = allowed_query.execute()assert response.results == [("row-uuid",)]+ connect.assert_called_once()+ assert {key: connect.call_args.kwargs[key] for key in ("host", "port", "dbname", "user", "password")} == {+ "host": _CONNECTION["host"],+ "port": _CONNECTION["port"],+ "dbname": _CONNECTION["database"],+ "user": f"posthog_team_{team.id}",+ "password": _PROJECT_READER_PASSWORD,+ }assert [call.args[0] for call in connection.execute.call_args_list] == ["SELECT current_database(), version()","USE ducklake",]query_cursor.execute.assert_called_once_with(sql, None)- # Tables from other teams in the org are queryable too — org-wide visibility- # is the point of the root credential.- cross_team_query = HogQLQueryExecutor(- query=f"SELECT uuid FROM team_{other_team.id}.orders",- team=team,- connection_id=str(source.id),+ assert get_direct_connection_source(team, str(source.id), require_pure_direct=True) == source++ def test_reconciles_legacy_and_ready_reader_sources_independently(self) -> None:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ _create_server(org)+ reader = _create_project_reader_source(team)+ stored_login = _create_stored_login_source(team)+ seen_users: list[str] = []++ def discover(config: PostgresSourceConfig, *_args: object, **_kwargs: object) -> list[SourceSchema]:+ seen_users.append(config.user)+ return [_source_schema("events")]++ with (+ patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ side_effect=AssertionError("lifecycle must not evaluate the SQL editor flag"),+ ) as feature_flag,+ patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",+ side_effect=discover,+ ),+ ):+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)++ feature_flag.assert_not_called()+ assert set(seen_users) == {_CONNECTION["username"], f"posthog_team_{team.id}"}+ assert ExternalDataSchema.objects.filter(source=stored_login, name="posthog.events").exists()+ assert ExternalDataSchema.objects.filter(source=reader, name="posthog.events").exists()++ def test_legacy_introspection_failure_does_not_block_ready_reader_reconciliation(self) -> None:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ _create_server(org)+ reader = _create_project_reader_source(team)+ stored_login = _create_stored_login_source(team)++ def discover(config: PostgresSourceConfig, *_args: object, **_kwargs: object) -> list[SourceSchema]:+ if config.user == _CONNECTION["username"]:+ raise ConnectionRefusedError("stored login unavailable")+ return [_source_schema("events")]++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",+ side_effect=discover,+ ) as get_schemas:+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)++ assert get_schemas.call_count == 2+ assert not ExternalDataSchema.objects.filter(source=stored_login).exists()+ assert ExternalDataSchema.objects.filter(source=reader, name="posthog.events").exists()++ @parameterized.expand([("external", False), ("built_in", True)])+ def test_reconciles_after_reprovision_with_another_mode_tombstoned(+ self, _name: str, revive_project_reader: bool+ ) -> None:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ _create_server(org)+ reader = _create_project_reader_source(team)+ stored_login = _create_stored_login_source(team)+ soft_delete_managed_warehouse_sources(organization_id=org.id)++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",+ return_value=[_source_schema("events")],+ ) as get_schemas:+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)+ get_schemas.assert_not_called()++ if revive_project_reader:+ reader.deleted = False+ reader.deleted_at = None+ reader.save(update_fields=["deleted", "deleted_at", "updated_at"])+ revived_source = reader+ tombstoned_source = stored_login+ else:+ revived_source = _ensure(team)+ tombstoned_source = reader+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)++ revived_source.refresh_from_db()+ tombstoned_source.refresh_from_db()+ assert revived_source.deleted is False+ assert tombstoned_source.deleted is True+ get_schemas.assert_called_once()+ assert ExternalDataSchema.objects.filter(source=revived_source, name="posthog.events").exists()+ assert not ExternalDataSchema.objects.filter(source=tombstoned_source).exists()++ @parameterized.expand(+ [+ (False, False),+ (False, True),+ (True, False),+ ]+ )+ def test_unready_reader_does_not_block_legacy_reconciliation(+ self, reader_configured: bool, direct_query_enabled: bool+ ) -> None:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ _create_server(org)+ reader = _create_project_reader_source(+ team,+ reader_configured=reader_configured,+ direct_query_enabled=direct_query_enabled,)- cross_sql, _context = cross_team_query.generate_clickhouse_sql()- assert "orders" in cross_sql- assert get_direct_connection_source(team, str(source.id), require_pure_direct=True) == source+ seen_users: list[str] = []++ def discover(config: PostgresSourceConfig, *_args: object, **_kwargs: object) -> list[SourceSchema]:+ seen_users.append(config.user)+ return [_source_schema("events")]- def test_discovers_only_internal_schemas_registers_nothing(self) -> None:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",+ side_effect=discover,+ ):+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)++ legacy_source = ExternalDataSource.objects.get(+ team_id=team.id,+ connection_metadata__credential_kind="org_root",+ )+ assert seen_users == [_CONNECTION["username"]]+ assert ExternalDataSchema.objects.filter(source=legacy_source, name="posthog.events").exists()+ assert not ExternalDataSchema.objects.filter(source=reader).exists()++ def test_successful_internal_only_discovery_clears_stale_catalog(self) -> None:org, team = self._setup()+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",+ return_value=[_source_schema("events_prod")],+ ):+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)+with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",return_value=[@@ -371,7 +562,14 @@ class TestReconcileManagedWarehouseTables:reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)- assert not ExternalDataSchema.objects.filter(source_id=source.id).exists()+ schema = ExternalDataSchema.objects.get(source_id=source.id, name="posthog.events_prod")+ assert schema.deleted is True+ assert schema.table is not None+ assert schema.table.deleted is True+ assert not ExternalDataSchema.objects.filter(+ source_id=source.id,+ name__in=["pg_catalog.pg_stat_activity", "information_schema.tables"],+ ).exists()def test_reintrospects_to_pick_up_new_tables(self) -> None:org, team = self._setup()@@ -423,23 +621,33 @@ class TestReconcileManagedWarehouseTables:assert schema.table is not Noneassert schema.table.deleted is False- def test_skips_quietly_when_the_warehouse_is_not_reachable(self) -> None:- # A provisioning warehouse fails introspection on every sweep; that must not raise.+ def test_failed_introspection_preserves_the_existing_catalog(self) -> None:org, team = self._setup()with patch("products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",- side_effect=ConnectionRefusedError("still provisioning"),+ return_value=[_source_schema("events_prod")],):reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)- assert not ExternalDataSchema.objects.filter(source_id=source.id).exists()+ schema = ExternalDataSchema.objects.get(source_id=source.id, name="posthog.events_prod")+ assert schema.table_id is not None++ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",+ side_effect=ConnectionRefusedError("still provisioning"),+ ):+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)++ schema.refresh_from_db()+ table = DataWarehouseTable.raw_objects.get(id=schema.table_id)+ assert schema.deleted is False+ assert table.deleted is Falsedef test_periodic_sweep_schedules_every_managed_project(self) -> None:org, team = self._setup()all_rows = _MEMBERSHIPS[str(org.id)] + [- # Legacy shared-table membership: root-backed sources support it, so the- # sweep schedules it like any other row.+ # Legacy shared-table membership remains an enrolled project, so the sweep schedules it._membership(team.id + 1, str(org.id), "team_x", legacy_shared=True),]@@ -471,17 +679,6 @@ class TestReconcileManagedWarehouseTables:schedule.assert_not_called()- def test_registers_a_connection_for_a_team_without_cp_membership(self) -> None:- # The connection no longer depends on control-plane membership: any team in an org- # with a provisioned warehouse gets one on reconcile.- org = Organization.objects.create(name="Org")- team = Team.objects.create(organization=org)- _create_server(org)-- reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)-- assert ExternalDataSource.objects.filter(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX).exists()-def test_reconciles_for_a_legacy_shared_tables_team(self) -> None:org, team = self._setup()_clear_memberships()@@ -520,13 +717,13 @@ class TestManagedWarehouseLifecycle:org = Organization.objects.create(name="Org")team = Team.objects.create(organization=org)server = _create_server(org)- source = ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=org.id)+ source = _create_project_reader_source(team)return org, team, source, server- def test_update_root_password_rotates_the_server_and_every_managed_source(self) -> None:+ def test_update_root_password_preserves_project_readers_and_refreshes_stored_login_sources(self) -> None:org, team, source, server = self._org_team_source()other_team = Team.objects.create(organization=org)- other_source = ensure_managed_warehouse_direct_source(team_id=other_team.id, organization_id=org.id)+ other_source = _create_stored_login_source(other_team)update_managed_warehouse_root_password(organization_id=org.id, password="rotated")@@ -535,7 +732,7 @@ class TestManagedWarehouseLifecycle:server.refresh_from_db()assert isinstance(source.job_inputs, dict)assert isinstance(other_source.job_inputs, dict)- assert source.job_inputs["password"] == "rotated"+ assert source.job_inputs["password"] == _PROJECT_READER_PASSWORDassert other_source.job_inputs["password"] == "rotated"assert server.password == "rotated"@@ -549,12 +746,7 @@ class TestManagedWarehouseLifecycle:server.refresh_from_db()assert server.password == "rotated"assert isinstance(source.job_inputs, dict)- assert source.job_inputs["password"] == _CONNECTION["password"]- # The next ensure revives the source and rewrites its credential from the server.- revived = ensure_managed_warehouse_direct_source(team_id=source.team_id, organization_id=org.id)- assert revived.deleted is False- assert isinstance(revived.job_inputs, dict)- assert revived.job_inputs["password"] == "rotated"+ assert source.job_inputs["password"] == _PROJECT_READER_PASSWORDdef test_soft_delete_removes_sources_and_their_tables(self) -> None:org, team, source, _server = self._org_team_source()@@ -593,8 +785,8 @@ class TestManagedWarehouseLifecycle:_create_server(org)team_a = Team.objects.create(organization=org)team_b = Team.objects.create(organization=org)- source_a = _ensure(team_a)- source_b = _ensure(team_b)+ source_a = _create_project_reader_source(team_a)+ source_b = _create_project_reader_source(team_b)original_save = ExternalDataSource.savedef fail_on_second_source(instance: ExternalDataSource, *args: object, **kwargs: object) -> None:diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.pyindex 4a8ca5b2a778..703fe604b4ed 100644--- a/products/warehouse_sources/backend/facade/models.py+++ b/products/warehouse_sources/backend/facade/models.py@@ -34,9 +34,13 @@ from products.warehouse_sources.backend.models.external_data_schema import (update_sync_type_config_keys,)from products.warehouse_sources.backend.models.external_data_source import (+ MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS,+ MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,MANAGED_WAREHOUSE_SOURCE_PREFIX,ExternalDataSource,+ ManagedWarehouseSQLMode,get_direct_external_data_source_for_connection,+ is_managed_warehouse_connection_ready,)from products.warehouse_sources.backend.models.pending_source_credential import PendingSourceCredentialfrom products.warehouse_sources.backend.models.ssh_tunnel import SSHTunnel@@ -71,7 +75,10 @@ __all__ = ["ExternalDataJob","ExternalDataSchema","ExternalDataSource",+ "MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS",+ "MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND","MANAGED_WAREHOUSE_SOURCE_PREFIX",+ "ManagedWarehouseSQLMode","PendingSourceCredential","SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING","SSHTunnel",@@ -83,6 +90,7 @@ __all__ = ["get_custom_oauth2_integration","get_all_schemas_for_source_id","get_direct_external_data_source_for_connection",+ "is_managed_warehouse_connection_ready","get_latest_run_if_exists","get_or_create_datawarehouse_credential","clickhouse_column_to_dwh_column",diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.pyindex 22792f5d087b..7c678a282231 100644--- a/products/warehouse_sources/backend/models/external_data_source.py+++ b/products/warehouse_sources/backend/models/external_data_source.py@@ -1,3 +1,4 @@+from enum import StrEnumfrom uuid import UUIDfrom django.db import models@@ -15,9 +16,17 @@ from products.warehouse_sources.backend.types import DIRECT_ENGINE_BY_SOURCE_TYPlogger = structlog.get_logger(__name__)MANAGED_WAREHOUSE_SOURCE_PREFIX = "managed_warehouse"+MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND = "project_reader"+MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS = frozenset({"org_root", "stored_server_login"})SYSTEM_MANAGED_SOURCE_PREFIXES = frozenset({MANAGED_WAREHOUSE_SOURCE_PREFIX})+class ManagedWarehouseSQLMode(StrEnum):+ EXTERNAL = "external"+ BUILT_IN = "built_in"+ UNAVAILABLE = "unavailable"++class ExternalDataSourceManager(models.Manager):def get_queryset(self):return super().get_queryset().select_related("revenue_analytics_config")@@ -120,6 +129,111 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaFieldmetadata = self.connection_metadatareturn isinstance(metadata, dict) and metadata.get("system_managed") is True+ @property+ def has_managed_warehouse_prefix(self) -> bool:+ return self.prefix == MANAGED_WAREHOUSE_SOURCE_PREFIX++ @property+ def is_managed_warehouse(self) -> bool:+ metadata = self.connection_metadata+ return (+ self.source_type == ExternalDataSourceType.POSTGRES+ and self.access_method == self.AccessMethod.DIRECT+ and self.has_managed_warehouse_prefix+ and self.is_system_managed+ and isinstance(metadata, dict)+ and metadata.get("engine") == "duckdb"+ )++ @classmethod+ def managed_warehouse_identity_q(cls) -> models.Q:+ return models.Q(+ source_type=ExternalDataSourceType.POSTGRES,+ access_method=cls.AccessMethod.DIRECT,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ connection_metadata__engine="duckdb",+ connection_metadata__system_managed=True,+ )++ @classmethod+ def legacy_managed_warehouse_q(cls) -> models.Q:+ return cls.managed_warehouse_identity_q() & models.Q(+ direct_query_enabled=True,+ connection_metadata__credential_kind__in=MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS,+ )++ @classmethod+ def ready_managed_warehouse_q(cls) -> models.Q:+ return cls.managed_warehouse_identity_q() & models.Q(+ direct_query_enabled=True,+ connection_metadata__credential_kind=MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,+ connection_metadata__reader_configured=True,+ )++ def _has_valid_managed_warehouse_connection_inputs(self, *, expected_user: str | None = None) -> bool:+ job_inputs = self.job_inputs+ if not isinstance(job_inputs, dict):+ return False++ port = job_inputs.get("port")+ if isinstance(port, bool):+ return False+ if isinstance(port, int):+ port_number = port+ elif isinstance(port, str) and port.isdigit():+ port_number = int(port)+ else:+ return False++ user = job_inputs.get("user")+ return (+ isinstance(user, str)+ and bool(user)+ and (expected_user is None or user == expected_user)+ and isinstance(job_inputs.get("host"), str)+ and bool(job_inputs["host"].strip())+ and isinstance(job_inputs.get("database"), str)+ and bool(job_inputs["database"].strip())+ and isinstance(job_inputs.get("password"), str)+ and bool(job_inputs["password"])+ and 1 <= port_number <= 65535+ )++ @property+ def is_legacy_managed_warehouse(self) -> bool:+ metadata = self.connection_metadata+ return (+ self.is_managed_warehouse+ and isinstance(metadata, dict)+ and metadata.get("credential_kind") in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS+ )++ @property+ def is_managed_warehouse_ready(self) -> bool:+ metadata = self.connection_metadata+ if (+ not self.is_managed_warehouse+ or not self.direct_query_enabled+ or not isinstance(metadata, dict)+ or metadata.get("credential_kind") != MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND+ or metadata.get("reader_configured") is not True+ ):+ return False++ return self._has_valid_managed_warehouse_connection_inputs(expected_user=f"posthog_team_{self.team_id}")++ @property+ def managed_warehouse_sql_mode(self) -> ManagedWarehouseSQLMode:+ if self.is_managed_warehouse_ready:+ return ManagedWarehouseSQLMode.BUILT_IN+ if (+ self.is_legacy_managed_warehouse+ and self.direct_query_enabled+ and self._has_valid_managed_warehouse_connection_inputs()+ ):+ return ManagedWarehouseSQLMode.EXTERNAL+ return ManagedWarehouseSQLMode.UNAVAILABLE+@classmethoddef is_system_managed_prefix(cls, prefix: str | None) -> bool:return isinstance(prefix, str) and prefix.strip() in SYSTEM_MANAGED_SOURCE_PREFIXES@@ -221,8 +335,33 @@ def get_direct_external_data_source_for_connection(id=source_uuid,).exclude(deleted=True)+ .defer("job_inputs").first())if source is None or not is_direct_capable(source):return None++ if source.has_managed_warehouse_prefix and source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.UNAVAILABLE:+ return Nonereturn source+++def is_managed_warehouse_connection_ready(team_id: int, connection_id: str | None) -> bool:+ if not connection_id:+ return False++ try:+ source_uuid = UUID(connection_id)+ except ValueError:+ return False++ source = (+ ExternalDataSource.objects.filter(+ team_id=team_id,+ id=source_uuid,+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,+ )+ .exclude(deleted=True)+ .first()+ )+ return source is not None and source.is_managed_warehouse_readydiff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.pyindex 6925b6e1a165..e20c85c23853 100644--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py@@ -11,7 +11,7 @@ from django.conf import settingsfrom django.core.cache import cachefrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.db import connection, transaction-from django.db.models import Prefetch, Q+from django.db.models import Prefetch, Q, QuerySetfrom django.utils import timezonefrom django.utils.cache import patch_cache_control@@ -100,13 +100,16 @@ from products.data_warehouse.backend.facade.api import (unpause_cdc_extraction_schedule,)from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfig+from products.managed_warehouse.backend.facade import feature_flags as managed_warehouse_feature_flagsfrom products.revenue_analytics.backend.facade.api import ensure_person_join, remove_person_joinfrom products.warehouse_sources.backend.facade.api import validate_source_prefixfrom products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_SOURCE_PREFIX,DataWarehouseTable,ExternalDataJob,ExternalDataSchema,ExternalDataSource,+ ManagedWarehouseSQLMode,PendingSourceCredential,auto_enable_new_schemas,sync_old_schemas_with_new_schemas,@@ -176,6 +179,41 @@ INVALID_CREDENTIALS_FALLBACK_MESSAGE = ("We couldn't validate those credentials. Check they're correct and have the required access, then try again.")++def _canonical_legacy_managed_warehouse_source(+ queryset: QuerySet[ExternalDataSource],+) -> ExternalDataSource | None:+ candidates = (+ queryset.select_related(None)+ .filter(ExternalDataSource.legacy_managed_warehouse_q())+ .only(+ "id",+ "team_id",+ "created_at",+ "prefix",+ "connection_metadata",+ "source_type",+ "access_method",+ "direct_query_enabled",+ "job_inputs",+ )+ .order_by("-created_at")+ )+ return next(+ (source for source in candidates if source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL),+ None,+ )+++def _hide_noncanonical_managed_warehouse_sources(+ queryset: QuerySet[ExternalDataSource], canonical_source: ExternalDataSource | None+) -> QuerySet[ExternalDataSource]:+ hidden_sources = Q(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)+ if canonical_source is not None:+ hidden_sources &= ~Q(pk=canonical_source.pk)+ return queryset.exclude(hidden_sources)++REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {"timeout": "Connection timed out while fetching schemas from the source.","timed out": "Connection timed out while fetching schemas from the source.",@@ -579,6 +617,9 @@ class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):supports_hogql = serializers.SerializerMethodField(help_text="Whether HogQL queries compile for this connection. When false, only raw SQL (sendRawQuery) works.",)+ is_builtin_managed_warehouse = serializers.SerializerMethodField(+ help_text="Whether this option is the built-in PostHog managed warehouse connection.",+ )description = serializers.CharField(read_only=True,allow_null=True,@@ -592,10 +633,23 @@ class ExternalDataSourceConnectionOptionSerializer(serializers.ModelSerializer):return direct_supports_hogql(source)+ @extend_schema_field(serializers.BooleanField())+ def get_is_builtin_managed_warehouse(self, source: ExternalDataSource) -> bool:+ return source.pk == self.context.get("builtin_managed_warehouse_source_id")+class Meta:model = ExternalDataSource- fields = ["id", "prefix", "engine", "source_type", "access_method", "supports_hogql", "description"]- read_only_fields = ["id", "prefix", "engine", "source_type", "access_method", "supports_hogql", "description"]+ fields = [+ "id",+ "prefix",+ "engine",+ "source_type",+ "access_method",+ "supports_hogql",+ "is_builtin_managed_warehouse",+ "description",+ ]+ read_only_fields = fieldsclass DirectConnectionSourceOptionSerializer(serializers.Serializer):@@ -1778,7 +1832,6 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi"connect_link","stored_credentials","webhook_info",- "connections","cdc_status",]queryset = ExternalDataSource.objects.all()@@ -1815,6 +1868,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixiraise PermissionDenied("You do not have editor access to every table in this source.")def dangerously_get_permissions(self):+ if self.action == "connections":+ return [+ IsAuthenticated(),+ APIScopePermission(),+ TeamMemberAccessPermission(),+ ]# The account picker enumerates every account/site the connected provider exposes, so require# manage access even though it's a GET — a read-only member shouldn't discover unrelated# accounts (info disclosure). Other actions fall back to the viewset defaults.@@ -1878,8 +1937,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixireturn contextdef safely_get_queryset(self, queryset):+ queryset = queryset.exclude(deleted=True)+ canonical_source = _canonical_legacy_managed_warehouse_source(queryset.filter(team_id=self.team_id))+ queryset = _hide_noncanonical_managed_warehouse_sources(queryset, canonical_source)+return (- queryset.exclude(deleted=True)+ queryset# created_by (FK) and revenue_analytics_config (reverse 1:1) are read per source during# serialization. select_related folds them into the main query instead of firing one# extra SELECT per source — the reverse 1:1 was an unprefetched N+1 that dominated the@@ -4599,9 +4662,15 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixireturn Response(status=status.HTTP_200_OK, data=SourceConnectLinkSerializer(data).data)@extend_schema(responses=ExternalDataSourceConnectionOptionSerializer(many=True))- @action(methods=["GET"], detail=False, pagination_class=None, filter_backends=[])+ @action(+ methods=["GET"],+ detail=False,+ pagination_class=None,+ filter_backends=[],+ required_scopes=["external_data_source:read"],+ )def connections(self, request: Request, *args: Any, **kwargs: Any) -> Response:- queryset = (+ connection_sources = (ExternalDataSource._base_manager.filter(team_id=self.team_id,source_type__in=direct_capable_source_types(),@@ -4609,12 +4678,53 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi# Pure-direct sources are always live; synced sources only when the toggle is on..filter(Q(access_method=ExternalDataSource.AccessMethod.DIRECT) | Q(direct_query_enabled=True)).exclude(deleted=True)- .only("id", "prefix", "connection_metadata", "source_type", "access_method")+ .only(+ "id",+ "prefix",+ "description",+ "connection_metadata",+ "source_type",+ "access_method",+ ).order_by(self.ordering))- queryset = self.user_access_control.filter_queryset_by_access_level(queryset)-- serializer = ExternalDataSourceConnectionOptionSerializer(queryset, many=True)+ managed_warehouse_enabled = managed_warehouse_feature_flags.is_managed_warehouse_sql_editor_enabled(self.team)+ managed_source = None+ if managed_warehouse_enabled:+ managed_candidates = connection_sources.filter(ExternalDataSource.ready_managed_warehouse_q()).only(+ "id",+ "team_id",+ "prefix",+ "description",+ "connection_metadata",+ "source_type",+ "access_method",+ "direct_query_enabled",+ "job_inputs",+ )+ managed_source = next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)+ external_sources = connection_sources.exclude(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)+ else:+ canonical_source = _canonical_legacy_managed_warehouse_source(connection_sources)+ external_sources = _hide_noncanonical_managed_warehouse_sources(connection_sources, canonical_source)+ if is_service_auth(request):+ accessible_external_sources = external_sources+ else:+ accessible_external_sources = self.user_access_control.filter_queryset_by_access_level(external_sources)+ if not self.user_access_control.has_resource_access(+ "external_data_source"+ ) and not self.user_access_control.has_any_specific_access_for_resource(+ "external_data_source", required_level="viewer"+ ):+ accessible_external_sources = accessible_external_sources.filter(created_by=cast(User, request.user))+ accessible_sources = list(accessible_external_sources)+ options = ([managed_source] if managed_source is not None else []) + accessible_sources++ serializer = ExternalDataSourceConnectionOptionSerializer(+ options,+ many=True,+ context={"builtin_managed_warehouse_source_id": managed_source.pk if managed_source is not None else None},+ )return Response(status=status.HTTP_200_OK, data=serializer.data)@extend_schema(responses=DirectConnectionSourceOptionSerializer(many=True))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.pyindex df8f29b480ba..b1a98a5ca06d 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py@@ -4,9 +4,6 @@ import reimport mathimport timeimport errno-import socket-import ipaddress-import threadingimport collectionsimport dataclassesfrom collections.abc import Callable, Iterator@@ -36,6 +33,7 @@ from structlog.types import FilteringBoundLoggerfrom posthog.hogql.database.schema.duckdb_table_functions import is_dangerous_table_functionfrom posthog.exceptions_capture import capture_exception+from posthog.psycopg_helpers import resolve_psycopg_hostaddr_with_timeoutfrom products.warehouse_sources.backend.temporal.data_imports.naming_convention import NamingConventionfrom products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (@@ -773,79 +771,7 @@ def _is_invalid_ssl_negotiation_response(error: BaseException) -> bool:return _INVALID_SSL_NEGOTIATION_RESPONSE_SUBSTRING in " ".join(str(arg) for arg in error.args).lower()-def _is_ip_literal(host: str) -> bool:- try:- ipaddress.ip_address(host.strip("[]"))- return True- except ValueError:- return False---def _resolve_hostaddr_with_timeout(host: str, port: int, timeout: float) -> list[str] | None:- """Resolve `host` to its addresses under a wall-clock `timeout`, to hand psycopg as `hostaddr`.-- psycopg3 resolves hostnames in Python before libpq ever connects — `conninfo_attempts` calls- `socket.getaddrinfo` (see psycopg/_conninfo_attempts.py) and only then passes the resolved- address(es) to libpq. `connect_timeout` bounds establishing the socket, never that name lookup, so- a stalled or unresponsive resolver blocks the (threaded, non-interruptible) sync activity for as- long as the OS resolver takes. It never trips `connect_timeout`; the activity instead runs until- Temporal's `start_to_close_timeout` cancels the worker thread mid-`getaddrinfo`, surfacing a- misleading `CancelledError` and burning the whole activity's retry budget. Resolving here turns a- stalled resolver into a fast, retryable error instead.-- Returns every resolved address, not just one: when a host resolves to more than one address (most- commonly a dual-stack host with both an AAAA and an A record), `Connection.connect` tries each- `hostaddr` attempt in turn and only fails once all of them do (see `conninfo_attempts` /- `Connection.connect`'s attempt loop) — a network that can't route one address family (e.g. no IPv6- egress) still connects via the other. Handing psycopg a single pre-resolved `hostaddr` would- collapse that to one attempt and turn an unreachable-address-family blip into a hard failure.-- Returns None when there is nothing to bound — an empty host, a Unix-socket path, or a host that is- already an IP literal — and also on a genuine resolution failure, so psycopg connects (and- re-raises that failure) exactly as before and the existing "Name or service not known"- classification still applies. Only a resolver that exceeds `timeout` becomes an `OperationalError`;- its message deliberately avoids the non-retryable "could not translate host name" /- "Name or service not known" fragments because a stalled resolver is usually transient.- """- if not host or host.startswith("/") or _is_ip_literal(host):- return None-- addrinfo: list[Any] = []- lookup_error: list[BaseException] = []-- def _lookup() -> None:- try:- addrinfo.extend(socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP, type=socket.SOCK_STREAM))- except BaseException as e: # noqa: BLE001 — surfaced to the caller below via lookup_error- lookup_error.append(e)-- # Daemon thread so a stalled getaddrinfo can be abandoned without blocking worker shutdown or- # piling up non-daemon threads — the OS resolver bounds the orphaned lookup on its own.- thread = threading.Thread(target=_lookup, daemon=True)- thread.start()- thread.join(timeout)- if thread.is_alive():- raise psycopg.OperationalError(f"Timed out resolving database host name after {timeout}s")- # A genuine resolution failure falls through to None so psycopg connects and re-raises it,- # preserving the existing "Name or service not known" classification.- if lookup_error:- if isinstance(lookup_error[0], OSError):- return None- raise lookup_error[0]- if not addrinfo:- return None- # sockaddr[0] is the address string (getaddrinfo types it as str | int across the IPv4/IPv6- # tuple variants, so coerce to satisfy the str return type). Dedupe while preserving order —- # getaddrinfo can repeat an address across otherwise-distinct tuples (e.g. differing canonical- # names), and a duplicate `hostaddr` attempt would just fail the same way twice.- seen: set[str] = set()- addresses: list[str] = []- for info in addrinfo:- address = str(info[4][0])- if address not in seen:- seen.add(address)- addresses.append(address)- return addresses+_resolve_hostaddr_with_timeout = resolve_psycopg_hostaddr_with_timeoutdef _connect_with_options_fallback(**connect_kwargs: Any) -> psycopg.Connection:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.pyindex a44db1ae3750..a3cf7bdfeed3 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py@@ -2204,9 +2204,7 @@ class TestResolveHostaddrWithTimeout:],)def test_hosts_that_need_no_lookup_short_circuit(self, host):- with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo"- ) as getaddrinfo_mock:+ with patch("posthog.psycopg_helpers.socket.getaddrinfo") as getaddrinfo_mock:assert _resolve_hostaddr_with_timeout(host, 5432, 15) is Nonegetaddrinfo_mock.assert_not_called()@@ -2220,7 +2218,7 @@ class TestResolveHostaddrWithTimeout:(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.5", 5432)),]with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ "posthog.psycopg_helpers.socket.getaddrinfo",return_value=addrinfo,):assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == ["2001:db8::5", "10.0.0.5"]@@ -2233,7 +2231,7 @@ class TestResolveHostaddrWithTimeout:(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", ("10.0.0.5", 5432)),]with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ "posthog.psycopg_helpers.socket.getaddrinfo",return_value=addrinfo,):assert _resolve_hostaddr_with_timeout("db.example.com", 5432, 15) == ["10.0.0.5"]@@ -2242,16 +2240,38 @@ class TestResolveHostaddrWithTimeout:# A host that doesn't resolve must return None (not raise) so psycopg connects as before and# its own "Name or service not known" error still reaches the non-retryable classifier.with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ "posthog.psycopg_helpers.socket.getaddrinfo",side_effect=socket.gaierror(-2, "Name or service not known"),):assert _resolve_hostaddr_with_timeout("does-not-exist.example.com", 5432, 15) is None+ @pytest.mark.parametrize(+ "resolver_result",+ [+ socket.gaierror(-2, "Name or service not known"),+ [],+ ],+ )+ def test_strict_resolution_failure_raises(self, resolver_result):+ patch_kwargs = (+ {"side_effect": resolver_result}+ if isinstance(resolver_result, BaseException)+ else {"return_value": resolver_result}+ )+ with patch("posthog.psycopg_helpers.socket.getaddrinfo", **patch_kwargs):+ with pytest.raises(psycopg.OperationalError, match="Could not resolve database host name"):+ _resolve_hostaddr_with_timeout(+ "does-not-exist.example.com",+ 5432,+ 15,+ fail_on_resolution_error=True,+ )+def test_stalled_resolver_raises_fast_retryable_error(self):release = threading.Event()try:with patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ "posthog.psycopg_helpers.socket.getaddrinfo",side_effect=lambda *a, **k: release.wait(),):with pytest.raises(psycopg.OperationalError) as exc_info:@@ -2265,6 +2285,23 @@ class TestResolveHostaddrWithTimeout:assert "could not translate host name" not in messageassert "Name or service not known" not in message+ def test_abort_check_interrupts_stalled_resolution(self):+ release = threading.Event()+ try:+ with patch(+ "posthog.psycopg_helpers.socket.getaddrinfo",+ side_effect=lambda *a, **k: release.wait(),+ ):+ with pytest.raises(RuntimeError, match="resolution canceled"):+ _resolve_hostaddr_with_timeout(+ "db.example.com",+ 5432,+ 15,+ abort_check=MagicMock(side_effect=RuntimeError("resolution canceled")),+ )+ finally:+ release.set()+# A dual-stack host (e.g. Neon) can resolve to both an IPv6 and an IPv4 address. Passing psycopg a# single pre-resolved `hostaddr` collapses its connection attempt to just that one address, so a@@ -2283,7 +2320,7 @@ class TestConnectToPostgresMultiAddressFailover:"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.settings") as mock_settings,patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ "posthog.psycopg_helpers.socket.getaddrinfo",return_value=addrinfo,),patch(@@ -2311,7 +2348,7 @@ class TestConnectToPostgresMultiAddressFailover:"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.settings") as mock_settings,patch(- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.postgres.socket.getaddrinfo",+ "posthog.psycopg_helpers.socket.getaddrinfo",return_value=addrinfo,),patch(diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source.py b/products/warehouse_sources/backend/tests/api/test_external_data_source.pyindex 2b39664ab815..90cefe6a8647 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source.py@@ -2303,6 +2303,7 @@ class TestExternalDataSource(APIBaseTest):"source_type": "Snowflake","access_method": "direct","supports_hogql": True,+ "is_builtin_managed_warehouse": False,"description": None,},{@@ -2312,6 +2313,7 @@ class TestExternalDataSource(APIBaseTest):"source_type": "Postgres","access_method": "direct","supports_hogql": True,+ "is_builtin_managed_warehouse": False,"description": "Prod Postgres replica",},{@@ -2321,6 +2323,7 @@ class TestExternalDataSource(APIBaseTest):"source_type": "MySQL","access_method": "direct","supports_hogql": True,+ "is_builtin_managed_warehouse": False,"description": None,},],diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py b/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.pyindex 9026b766ee91..bf8608ccd26c 100644--- a/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py@@ -2,15 +2,22 @@ import uuidimport pytestfrom posthog.test.base import APIBaseTest+from unittest.mock import MagicMock, patch+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeaturefrom posthog.models.organization import OrganizationMembership+from posthog.models.team import Teamfrom posthog.models.user import Userfrom posthog.rbac.user_access_control import UserAccessControl-from products.warehouse_sources.backend.facade.models import ExternalDataSchema, ExternalDataSource+from products.warehouse_sources.backend.facade.models import (+ MANAGED_WAREHOUSE_SOURCE_PREFIX,+ ExternalDataSchema,+ ExternalDataSource,+)try:from ee.models.rbac.access_control import AccessControl@@ -21,9 +28,18 @@ except ImportError:@pytest.mark.eeclass TestExternalDataSourceAccessControl(APIBaseTest):- def setUp(self):+ managed_warehouse_sql_editor_flag: MagicMock++ def setUp(self) -> None:super().setUp()+ flag_patcher = patch(+ "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",+ return_value=True,+ )+ self.managed_warehouse_sql_editor_flag = flag_patcher.start()+ self.addCleanup(flag_patcher.stop)+# Enable access control featuresself.organization.available_product_features = [{@@ -87,6 +103,54 @@ class TestExternalDataSourceAccessControl(APIBaseTest):role=None,)+ def _create_managed_source(self, **overrides: object) -> ExternalDataSource:+ source_team = overrides.get("team")+ if not isinstance(source_team, Team):+ source_team = self.team+ fields: dict[str, object] = {+ "team": source_team,+ "source_id": str(uuid.uuid4()),+ "connection_id": str(uuid.uuid4()),+ "source_type": "Postgres",+ "prefix": MANAGED_WAREHOUSE_SOURCE_PREFIX,+ "access_method": ExternalDataSource.AccessMethod.DIRECT,+ "direct_query_enabled": True,+ "created_by": self.user,+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": True,+ },+ "job_inputs": {+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": f"posthog_team_{source_team.id}",+ "password": "secret",+ },+ }+ fields.update(overrides)+ return ExternalDataSource.objects.create(**fields)++ def _create_legacy_managed_source(self, **overrides: object) -> ExternalDataSource:+ fields: dict[str, object] = {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ },+ "job_inputs": {+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": "organization_login",+ "password": "secret",+ },+ }+ fields.update(overrides)+ return self._create_managed_source(**fields)+# --- Viewer Access Level Tests ---def test_viewer_can_list_sources(self):@@ -280,6 +344,376 @@ class TestExternalDataSourceAccessControl(APIBaseTest):self.assertEqual(response.json()["count"], 1)self.assertEqual(response.json()["results"][0]["id"], str(self.source.id))+ def test_connections_includes_only_ready_managed_warehouse_regardless_of_source_access(self):+ external_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type="Postgres",+ prefix="Customer database",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ )+ pending_source = self._create_managed_source(+ direct_query_enabled=False,+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ },+ )+ self._create_access_control(self.viewer_user, access_level="none")+ self.client.force_login(self.viewer_user)++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])++ managed_source = self._create_managed_source()+ self._create_access_control(+ self.viewer_user,+ resource_id=str(managed_source.id),+ access_level="none",+ )+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ returned_ids = [item["id"] for item in response.json()]+ self.assertEqual(returned_ids, [str(managed_source.id)])+ self.assertTrue(response.json()[0]["is_builtin_managed_warehouse"])+ self.assertNotIn(str(external_source.id), returned_ids)+ self.assertNotIn(str(pending_source.id), returned_ids)++ @parameterized.expand(+ [+ ("missing_system_managed", {"connection_metadata": {"engine": "duckdb"}}),+ (+ "wrong_engine",+ {"connection_metadata": {"engine": "postgres", "system_managed": True}},+ ),+ ("wrong_source_type", {"source_type": "MySQL"}),+ (+ "synced_source",+ {+ "access_method": ExternalDataSource.AccessMethod.WAREHOUSE,+ "direct_query_enabled": True,+ },+ ),+ ("direct_query_disabled", {"direct_query_enabled": False}),+ (+ "reader_pending",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ }+ },+ ),+ (+ "missing_reader_marker",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ }+ },+ ),+ (+ "legacy_org_root",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "org_root",+ "reader_configured": True,+ }+ },+ ),+ (+ "stored_server_login",+ {+ "connection_metadata": {+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "stored_server_login",+ "reader_configured": True,+ }+ },+ ),+ (+ "spoofed_root_username",+ {+ "job_inputs": {+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": "root",+ "password": "secret",+ }+ },+ ),+ (+ "malformed_credentials",+ {+ "job_inputs": {+ "host": "managed.example.com",+ "port": "invalid",+ "database": "ducklake",+ "user": "posthog_team_invalid",+ "password": "",+ }+ },+ ),+ ]+ )+ def test_connections_omits_incomplete_reserved_sources(self, _name: str, overrides: dict[str, object]) -> None:+ source = self._create_managed_source(**overrides)++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertNotIn(str(source.id), [item["id"] for item in response.json()])++ @parameterized.expand(+ [+ ("disabled", False),+ ("evaluation_error", RuntimeError("feature flag unavailable")),+ ]+ )+ def test_connections_flag_off_preserves_legacy_managed_source_as_external(+ self, _name: str, flag_result: bool | Exception+ ) -> None:+ legacy_source = self._create_legacy_managed_source()+ ready_reader = self._create_managed_source()+ pending_reader = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ }+ )+ malformed_legacy = self._create_legacy_managed_source(job_inputs={})+ unknown_kind = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "unknown",+ }+ )+ external_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type="Postgres",+ prefix="Customer database",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ created_by=self.user,+ )+ if isinstance(flag_result, Exception):+ self.managed_warehouse_sql_editor_flag.side_effect = flag_result+ else:+ self.managed_warehouse_sql_editor_flag.return_value = flag_result++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ [item["id"] for item in response.json()],+ [str(external_source.id), str(legacy_source.id)],+ )+ self.assertFalse(+ next(item for item in response.json() if item["id"] == str(legacy_source.id))[+ "is_builtin_managed_warehouse"+ ]+ )+ self.assertNotIn(str(ready_reader.id), [item["id"] for item in response.json()])+ self.assertNotIn(str(pending_reader.id), [item["id"] for item in response.json()])+ self.assertNotIn(str(malformed_legacy.id), [item["id"] for item in response.json()])+ self.assertNotIn(str(unknown_kind.id), [item["id"] for item in response.json()])++ def test_connections_flag_on_hides_legacy_source_and_marks_ready_reader_as_built_in(self) -> None:+ ready_reader = self._create_managed_source()+ legacy_source = self._create_legacy_managed_source()+ external_source = ExternalDataSource.objects.create(+ team=self.team,+ source_id=str(uuid.uuid4()),+ connection_id=str(uuid.uuid4()),+ source_type="Postgres",+ prefix="Customer database",+ access_method=ExternalDataSource.AccessMethod.DIRECT,+ created_by=self.user,+ )++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ [(item["id"], item["is_builtin_managed_warehouse"]) for item in response.json()],+ [(str(ready_reader.id), True), (str(external_source.id), False)],+ )+ self.assertNotIn(str(legacy_source.id), [item["id"] for item in response.json()])++ def test_connections_flag_off_applies_external_source_access_control_to_legacy_source(self) -> None:+ legacy_source = self._create_legacy_managed_source()+ self.managed_warehouse_sql_editor_flag.return_value = False+ self._create_access_control(self.viewer_user, access_level="none")+ self.client.force_login(self.viewer_user)++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])++ self._create_access_control(+ self.viewer_user,+ resource_id=str(legacy_source.id),+ access_level="viewer",+ )+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(+ [(item["id"], item["is_builtin_managed_warehouse"]) for item in response.json()],+ [(str(legacy_source.id), False)],+ )++ def test_connections_flag_off_does_not_fall_back_to_an_older_accessible_legacy_source(self) -> None:+ older_source = self._create_legacy_managed_source()+ self._create_legacy_managed_source()+ self.managed_warehouse_sql_editor_flag.return_value = False+ self._create_access_control(self.viewer_user, access_level="none")+ self._create_access_control(+ self.viewer_user,+ resource_id=str(older_source.id),+ access_level="viewer",+ )+ self.client.force_login(self.viewer_user)++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json(), [])++ def test_connections_uses_a_ready_reader_when_a_newer_reserved_row_is_malformed(self) -> None:+ managed_source = self._create_managed_source()+ malformed_source = self._create_managed_source(+ job_inputs={+ "host": "managed.example.com",+ "port": 5432,+ "database": "ducklake",+ "user": "root",+ "password": "secret",+ }+ )++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ returned_ids = [item["id"] for item in response.json()]+ self.assertIn(str(managed_source.id), returned_ids)+ self.assertNotIn(str(malformed_source.id), returned_ids)++ def test_connections_omits_deleted_and_cross_team_managed_sources(self) -> None:+ deleted_source = self._create_managed_source(deleted=True)+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ cross_team_source = self._create_managed_source(team=other_team)++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ returned_ids = [item["id"] for item in response.json()]+ self.assertNotIn(str(deleted_source.id), returned_ids)+ self.assertNotIn(str(cross_team_source.id), returned_ids)++ @parameterized.expand(+ [+ ("external_data_source_read", "external_data_source:read", status.HTTP_200_OK),+ ("query_read", "query:read", status.HTTP_403_FORBIDDEN),+ ]+ )+ def test_connections_preserves_external_data_source_api_scope(+ self, _name: str, scope: str, expected_status: int+ ) -> None:+ api_key = self.create_personal_api_key_with_scopes([scope])+ self.client.force_authenticate(None)++ response = self.client.get(+ f"/api/environments/{self.team.pk}/external_data_sources/connections/",+ headers={"authorization": f"Bearer {api_key}"},+ )++ self.assertEqual(response.status_code, expected_status)++ def test_external_source_resources_expose_only_the_canonical_legacy_source(self) -> None:+ legacy_source = self._create_legacy_managed_source()+ managed_source = self._create_managed_source()+ incomplete_source = self._create_managed_source(connection_metadata={})++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ returned_ids = [item["id"] for item in response.json()["results"]]+ self.assertIn(str(legacy_source.id), returned_ids)+ self.assertNotIn(str(managed_source.id), returned_ids)+ self.assertNotIn(str(incomplete_source.id), returned_ids)+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{legacy_source.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ for source in (managed_source, incomplete_source):+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ def test_flag_off_preserves_legacy_managed_source_as_read_only_external_resource(self) -> None:+ legacy_source = self._create_legacy_managed_source()+ ready_reader = self._create_managed_source()+ pending_reader = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "project_reader",+ "reader_configured": False,+ }+ )+ malformed_legacy = self._create_legacy_managed_source(job_inputs={})+ unknown_kind = self._create_managed_source(+ connection_metadata={+ "engine": "duckdb",+ "system_managed": True,+ "credential_kind": "unknown",+ }+ )+ other_team = Team.objects.create(organization=self.organization, name="Other project")+ cross_team_legacy = self._create_legacy_managed_source(team=other_team)+ self.managed_warehouse_sql_editor_flag.return_value = False++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ returned_ids = [item["id"] for item in response.json()["results"]]+ self.assertIn(str(legacy_source.id), returned_ids)+ self.assertNotIn(str(ready_reader.id), returned_ids)+ self.assertNotIn(str(pending_reader.id), returned_ids)+ self.assertNotIn(str(malformed_legacy.id), returned_ids)+ self.assertNotIn(str(unknown_kind.id), returned_ids)+ self.assertNotIn(str(cross_team_legacy.id), returned_ids)++ for hidden_source in (ready_reader, pending_reader, malformed_legacy, unknown_kind):+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{hidden_source.id}/")+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)++ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{legacy_source.id}/")+ self.assertEqual(response.status_code, status.HTTP_200_OK)++ response = self.client.patch(+ f"/api/environments/{self.team.pk}/external_data_sources/{legacy_source.id}/",+ data={"description": "Updated description"},+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+# --- Organization Admin Tests ---def test_org_admin_has_full_access(self):diff --git a/products/warehouse_sources/frontend/generated/api.schemas.ts b/products/warehouse_sources/frontend/generated/api.schemas.tsindex 125b9022dd90..3247ec95c6fc 100644--- a/products/warehouse_sources/frontend/generated/api.schemas.ts+++ b/products/warehouse_sources/frontend/generated/api.schemas.ts@@ -6000,6 +6000,8 @@ export interface ExternalDataSourceConnectionOptionApi {readonly access_method: AccessMethodEnumApi/** Whether HogQL queries compile for this connection. When false, only raw SQL (sendRawQuery) works. */readonly supports_hogql: boolean+ /** Whether this option is the built-in PostHog managed warehouse connection. */+ readonly is_builtin_managed_warehouse: boolean/*** User-set description of the source, shown as its display name in the connection picker when set.* @nullablediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 2619ad1272f3..d6612f6f6cd9 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -34628,6 +34628,8 @@ export namespace Schemas {readonly access_method: AccessMethodEnum;/** Whether HogQL queries compile for this connection. When false, only raw SQL (sendRawQuery) works. */readonly supports_hogql: boolean;+ /** Whether this option is the built-in PostHog managed warehouse connection. */+ readonly is_builtin_managed_warehouse: boolean;/*** User-set description of the source, shown as its display name in the connection picker when set.* @nullable