Skip to content

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

feat(data-warehouse): expose managed warehouse in SQL editor (#72368)

Eric Duong43407cc8348c
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.md
new file mode 100644
index 000000000000..41b572ffb40a
--- /dev/null
+++ b/docs/internal/managed-warehouse-sql-editor.md
@@ -0,0 +1,7 @@
+# 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 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.
+
+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.
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.md
index 4bde093f2884..a13359a498a0 100644
--- a/posthog/dags/README_DUCKLINGS.md
+++ b/posthog/dags/README_DUCKLINGS.md
@@ -120,7 +120,13 @@ class DucklingBackfillConfig:
2. Enable the team's backfill by creating its `DuckgresServerTeam` row with
`backfill_enabled=True` (the provision / enable-backfill admin actions do this). The
- discovery sensor will then pick up the team on its next run.
+ discovery sensor will then 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.
3. To trigger immediate historical backfill, reset the full backfill sensor cursor
diff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.py
index 425b48b9d116..5a9aefd008b0 100644
--- a/posthog/ducklake/common.py
+++ b/posthog/ducklake/common.py
@@ -665,13 +665,37 @@ def enable_team_backfill(*, team_id: int, organization_id: str | UUID, table_nam
)
suffix = table_name
if already_enabled:
+ existing = DuckgresServerTeam.objects.get(team_id=team_id)
+ if not existing.backfill_enabled:
+ existing.backfill_enabled = True
+ existing.save(update_fields=["backfill_enabled", "updated_at"])
+ _ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)
return suffix
server = DuckgresServer.objects.get(organization_id=organization_id)
DuckgresServerTeam.objects.create(server=server, team_id=team_id, backfill_enabled=True, table_suffix=suffix)
+ _ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)
return suffix
+def _ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> None:
+ """Best-effort: register the org's managed warehouse as a restricted query connection.
+
+ A managed warehouse speaks the Postgres wire protocol, so each member team gets an
+ ExternalDataSource pointed at the org server. Duckgres scopes its credential to the project
+ and enforces read-only SQL. Isolated from backfill enablement: a failure here must never block
+ a team from joining the warehouse.
+ """
+ try:
+ # Lazy import: keep the data_warehouse/warehouse_sources stack off this module's import
+ # path (it's loaded by the API and by Dagster, which don't need it).
+ from products.data_warehouse.backend.facade.api import ensure_managed_warehouse_direct_source # noqa: PLC0415
+
+ ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)
+ except Exception:
+ logger.exception("Failed to register managed warehouse query source for team %s", team_id)
+
+
def get_team_backfill_state(team_id: int) -> dict[str, object]:
"""Return the team's duckling backfill state for the warehouse-status UI.
diff --git a/posthog/ducklake/test_common.py b/posthog/ducklake/test_common.py
index ee66098e3094..97aac3d8c9bf 100644
--- a/posthog/ducklake/test_common.py
+++ b/posthog/ducklake/test_common.py
@@ -19,6 +19,8 @@ from posthog.ducklake.common import (
from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam
from posthog.models import Organization, Team
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+
@pytest.mark.django_db
class TestUpsertDuckgresServerForOrg:
@@ -91,6 +93,17 @@ class TestEnableTeamBackfill:
assert suffix == "prod"
assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1
+ def test_same_name_reenables_a_deprovisioned_membership(self):
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = self._server(org)
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod", backfill_enabled=False)
+
+ suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")
+
+ assert suffix == "prod"
+ assert DuckgresServerTeam.objects.get(team=team).backfill_enabled is True
+
def test_refuses_to_change_a_set_suffix(self):
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
@@ -118,6 +131,41 @@ class TestEnableTeamBackfill:
with pytest.raises(DucklingBackfillEnableError):
enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="events")
+ def test_registers_a_restricted_postgres_query_connection_for_the_team(self):
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = self._server(org)
+
+ with patch(
+ "products.data_warehouse.backend.presentation.views.managed_warehouse.configure_project_reader",
+ side_effect=lambda **kwargs: {
+ "username": f"posthog_team_{kwargs['team_id']}",
+ "password": kwargs["password"],
+ },
+ ):
+ enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")
+
+ source = ExternalDataSource.objects.get(
+ team_id=team.id, access_method=ExternalDataSource.AccessMethod.DIRECT, direct_query_enabled=True
+ )
+ assert source.source_type == "Postgres"
+ assert source.job_inputs["host"] == server.host
+
+ def test_direct_connection_failure_does_not_block_enablement(self):
+ # The connection is a best-effort convenience; a failure must never stop a team joining.
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ self._server(org)
+
+ with patch(
+ "products.data_warehouse.backend.managed_warehouse_connection.ensure_managed_warehouse_direct_source",
+ side_effect=Exception("boom"),
+ ):
+ suffix = enable_team_backfill(team_id=team.id, organization_id=org.id, table_name="prod")
+
+ assert suffix == "prod"
+ assert DuckgresServerTeam.objects.filter(team_id=team.id).count() == 1
+
@pytest.mark.django_db
class TestGetTeamBackfillState:
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 3ec9bbc57473..dc0204f4c8cd 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -78,7 +78,10 @@ from products.conversations.backend.tasks import (
wake_snoozed_tickets,
)
from products.data_modeling.backend.facade.tasks import cleanup_expired_test_saved_queries
-from products.data_warehouse.backend.facade.tasks import send_external_data_failure_digest_catchup
+from products.data_warehouse.backend.facade.tasks import (
+ reconcile_all_managed_warehouse_tables_task,
+ send_external_data_failure_digest_catchup,
+)
from products.endpoints.backend.facade.tasks import deactivate_stale_materializations
from products.feature_flags.backend.tasks import (
cleanup_stale_flag_definitions_expiry_tracking_task,
@@ -504,6 +507,16 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="send external data failure digest catch-up",
)
+ # Background net for tables created while nobody visits the warehouse status page. Each
+ # reconcile opens a real warehouse session (one worker pod, billed compute), so the sweep is
+ # deliberately infrequent — the 60s-coalesced status-read path is the interactive fast path.
+ sender.add_periodic_task(
+ crontab(minute="17,47"),
+ reconcile_all_managed_warehouse_tables_task.s(),
+ name="reconcile managed warehouse SQL editor tables",
+ expires=1800,
+ )
+
# Every 30 minutes, send decide request counts to the main posthog instance
sender.add_periodic_task(
crontab(minute="*/30"),
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 73fadcc3ccbb..3ea24604e4e7 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -71,6 +71,12 @@ _LAZY = {
"get_redshift_source_location": "redshift_helpers",
"reconcile_redshift_schemas": "redshift_helpers",
"reproject_direct_redshift_table": "redshift_helpers",
+ "ensure_managed_warehouse_direct_source": "managed_warehouse_connection",
+ "reconcile_managed_warehouse_tables": "managed_warehouse_connection",
+ "soft_delete_managed_warehouse_sources": "managed_warehouse_connection",
+ "update_managed_warehouse_root_password": "managed_warehouse_connection",
+ "schedule_managed_warehouse_tables_reconcile": "tasks.tasks",
+ "schedule_soft_delete_managed_warehouse_sources": "tasks.tasks",
"HogQLQueryFixerTool": "max_tools",
"hide_direct_mysql_table": "direct_mysql",
"upsert_direct_mysql_table": "direct_mysql",
diff --git a/products/data_warehouse/backend/facade/tasks.py b/products/data_warehouse/backend/facade/tasks.py
index 903908088d80..722a84e5510d 100644
--- a/products/data_warehouse/backend/facade/tasks.py
+++ b/products/data_warehouse/backend/facade/tasks.py
@@ -4,7 +4,14 @@ Celery task wiring for data_warehouse.
Re-export of the beat-scheduled task that core registers (posthog/tasks/scheduled.py).
"""
-from products.data_warehouse.backend.tasks import send_external_data_failure_digest_catchup
+from products.data_warehouse.backend.tasks import (
+ reconcile_all_managed_warehouse_tables_task,
+ send_external_data_failure_digest_catchup,
+)
from products.data_warehouse.backend.tasks.tasks import schedule_external_data_failure_digest
-__all__ = ["schedule_external_data_failure_digest", "send_external_data_failure_digest_catchup"]
+__all__ = [
+ "reconcile_all_managed_warehouse_tables_task",
+ "schedule_external_data_failure_digest",
+ "send_external_data_failure_digest_catchup",
+]
diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_tasks.py b/products/data_warehouse/backend/logic/external_data_source/test/test_tasks.py
index 4e6ec917d599..f6d0ee732106 100644
--- a/products/data_warehouse/backend/logic/external_data_source/test/test_tasks.py
+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_tasks.py
@@ -3,6 +3,8 @@ from unittest.mock import patch
from posthog.redis import get_client
from products.data_warehouse.backend.tasks import (
+ reconcile_managed_warehouse_tables_task,
+ schedule_managed_warehouse_tables_reconcile,
send_external_data_failure_digest_catchup,
send_external_data_failure_digest_task,
)
@@ -37,3 +39,38 @@ class TestExternalDataFailureDigestTasks:
send_external_data_failure_digest_catchup()
assert [c.args for c in mock_task.delay.call_args_list] == [(1,), (2,)]
+
+
+class TestManagedWarehouseTasks:
+ def test_reconcile_task_discovers_tables(self) -> None:
+ with patch("products.data_warehouse.backend.tasks.tasks.reconcile_managed_warehouse_tables") as mock_reconcile:
+ reconcile_managed_warehouse_tables_task(123, "organization-id")
+
+ mock_reconcile.assert_called_once_with(team_id=123, organization_id="organization-id")
+
+ def test_reconcile_task_skips_when_another_reconcile_is_in_flight(self) -> None:
+ lock = get_client().lock("managed_warehouse_reconcile:123", timeout=10)
+ assert lock.acquire(blocking=False)
+ try:
+ with patch(
+ "products.data_warehouse.backend.tasks.tasks.reconcile_managed_warehouse_tables"
+ ) as mock_reconcile:
+ reconcile_managed_warehouse_tables_task(123, "organization-id")
+ finally:
+ lock.release()
+
+ mock_reconcile.assert_not_called()
+
+ def test_reconcile_scheduler_coalesces_repeated_scene_loads(self) -> None:
+ schedule_key = "managed_warehouse_reconcile_scheduled:456"
+ get_client().delete(schedule_key)
+ try:
+ with patch(
+ "products.data_warehouse.backend.tasks.tasks.reconcile_managed_warehouse_tables_task.delay"
+ ) as mock_delay:
+ schedule_managed_warehouse_tables_reconcile(team_id=456, organization_id="organization-id")
+ schedule_managed_warehouse_tables_reconcile(team_id=456, organization_id="organization-id")
+ finally:
+ get_client().delete(schedule_key)
+
+ mock_delay.assert_called_once_with(team_id=456, organization_id="organization-id")
diff --git a/products/data_warehouse/backend/managed_warehouse_connection.py b/products/data_warehouse/backend/managed_warehouse_connection.py
new file mode 100644
index 000000000000..802164c91f63
--- /dev/null
+++ b/products/data_warehouse/backend/managed_warehouse_connection.py
@@ -0,0 +1,394 @@
+"""Expose a managed Duckgres warehouse in the SQL editor as a read-only Postgres connection.
+
+Each member team gets a Postgres ``ExternalDataSource`` pointed at the organization's
+``DuckgresServer``. Duckgres issues a distinct database login for each project and enforces
+read-only access to the project's schemas, so both HogQL and raw SQL stay inside that boundary.
+Setup happens in two steps:
+
+1. ``ensure_managed_warehouse_direct_source`` creates the initially empty 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
+ table in the project's event/person, data-import, team, and modeled-data namespaces.
+
+This bypasses the user-facing create endpoint because the managed host is internal infrastructure
+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).
+"""
+
+from __future__ import annotations
+
+import secrets
+from typing import TYPE_CHECKING
+from uuid import UUID, uuid4
+
+from django.db import transaction
+from django.db.models import QuerySet
+from django.utils import timezone
+
+import structlog
+
+from posthog.models.team.team import Team
+
+from products.data_warehouse.backend.postgres_helpers import reconcile_postgres_schemas
+from products.data_warehouse.backend.presentation.views import managed_warehouse
+from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import (
+ MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ ExternalDataSource,
+)
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+
+if TYPE_CHECKING:
+ from posthog.ducklake.models import DuckgresServer
+
+logger = structlog.get_logger(__name__)
+
+MANAGED_WAREHOUSE_SOURCE_DESCRIPTION = "Managed warehouse (auto-provisioned)"
+
+
+def _managed_source_queryset(team_id: int) -> QuerySet[ExternalDataSource]:
+ return ExternalDataSource._base_manager.filter(
+ team_id=team_id,
+ source_type=ExternalDataSourceType.POSTGRES,
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ connection_metadata__system_managed=True,
+ )
+
+
+def _source_config(server: DuckgresServer, *, username: str, password: str) -> dict[str, object]:
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
+ return source_impl.parse_config(
+ {
+ "host": server.host,
+ "port": server.port,
+ "database": server.database,
+ "user": username,
+ "password": password,
+ }
+ ).to_dict()
+
+
+def _ensure_managed_source_locked(
+ *,
+ team_id: int,
+ server: DuckgresServer,
+ username: str,
+ password: str,
+ reader_configured: bool,
+) -> ExternalDataSource | None:
+ # Deliberately includes soft-deleted rows: a re-enabled membership revives its tombstoned
+ # source (the caller's credential pre-read filters deleted=False, so a revived row always
+ # gets fresh credentials and stays disabled until the handshake completes).
+ existing = _managed_source_queryset(team_id).select_for_update().order_by("-created_at").first()
+
+ config = _source_config(server, username=username, password=password)
+ if existing is not None:
+ update_fields: list[str] = []
+ connection_metadata = dict(existing.connection_metadata or {})
+ if connection_metadata.get("credential_kind") != "project_reader":
+ # Old managed sources used the org root credential, so discard any catalog
+ # entries discovered before Duckgres enforced the project boundary.
+ now = timezone.now()
+ DataWarehouseTable.raw_objects.filter(
+ team_id=team_id, external_data_source_id=existing.id, deleted=False
+ ).update(deleted=True, deleted_at=now, updated_at=now)
+ ExternalDataSchema.objects.filter(team_id=team_id, source_id=existing.id).delete()
+ if existing.job_inputs != config:
+ existing.job_inputs = config
+ update_fields.append("job_inputs")
+ if existing.access_method != ExternalDataSource.AccessMethod.DIRECT:
+ existing.access_method = ExternalDataSource.AccessMethod.DIRECT
+ update_fields.append("access_method")
+ if existing.direct_query_enabled != reader_configured:
+ existing.direct_query_enabled = reader_configured
+ update_fields.append("direct_query_enabled")
+ if (
+ connection_metadata.get("engine") != "duckdb"
+ or connection_metadata.get("system_managed") is not True
+ or connection_metadata.get("credential_kind") != "project_reader"
+ ):
+ existing.connection_metadata = {
+ **connection_metadata,
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "project_reader",
+ "reader_configured": reader_configured,
+ }
+ update_fields.append("connection_metadata")
+ elif connection_metadata.get("reader_configured") is not reader_configured:
+ existing.connection_metadata = {**connection_metadata, "reader_configured": reader_configured}
+ update_fields.append("connection_metadata")
+ if existing.deleted:
+ existing.deleted = False
+ existing.deleted_at = None
+ update_fields.extend(["deleted", "deleted_at"])
+ if update_fields:
+ existing.save(update_fields=[*update_fields, "updated_at"])
+ return existing
+
+ return ExternalDataSource.objects.create(
+ source_id=str(uuid4()),
+ connection_id=str(uuid4()),
+ destination_id=str(uuid4()),
+ team_id=team_id,
+ status=ExternalDataSource.Status.RUNNING,
+ source_type=ExternalDataSourceType.POSTGRES,
+ job_inputs=config,
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ description=MANAGED_WAREHOUSE_SOURCE_DESCRIPTION,
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ created_via=ExternalDataSource.CreatedVia.WEB,
+ direct_query_enabled=reader_configured,
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "project_reader",
+ "reader_configured": reader_configured,
+ },
+ )
+
+
+def ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> ExternalDataSource:
+ """Create or refresh the team's restricted live-query source from its membership."""
+ from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415
+
+ 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)
+ membership = (
+ DuckgresServerTeam.objects.select_for_update()
+ .filter(server=server, team_id=team_id, backfill_enabled=True)
+ .values("table_suffix")
+ .first()
+ )
+ if membership is None:
+ raise ValueError("The team has not joined this managed warehouse")
+ table_suffix = membership["table_suffix"]
+ if not table_suffix:
+ raise ValueError("Legacy shared managed warehouse tables cannot be exposed as a query connection")
+
+ existing = _managed_source_queryset(team_id).select_for_update().filter(deleted=False).first()
+ existing_metadata = existing.connection_metadata if existing is not None else None
+ has_reader_credentials = (
+ existing is not None
+ and isinstance(existing_metadata, dict)
+ and existing_metadata.get("credential_kind") == "project_reader"
+ and isinstance(existing.job_inputs, dict)
+ and existing.job_inputs.get("user")
+ and existing.job_inputs.get("password")
+ )
+ if has_reader_credentials:
+ assert existing is not None
+ assert isinstance(existing_metadata, dict)
+ assert isinstance(existing.job_inputs, dict)
+ reader_configured = existing_metadata.get("reader_configured") is True
+ username = str(existing.job_inputs["user"])
+ password = str(existing.job_inputs["password"])
+ else:
+ reader_configured = False
+ username = f"posthog_team_{team_id}"
+ password = secrets.token_urlsafe(32)
+
+ source = _ensure_managed_source_locked(
+ team_id=team_id,
+ server=server,
+ username=username,
+ password=password,
+ reader_configured=reader_configured,
+ )
+ if source is None:
+ raise RuntimeError("Failed to create the managed warehouse query source")
+ if reader_configured:
+ return source
+ source_id = source.id
+
+ credentials = managed_warehouse.configure_project_reader(
+ organization_id=organization_id,
+ team_id=team_id,
+ table_suffix=table_suffix,
+ password=password,
+ )
+ if credentials != {"username": username, "password": password}:
+ raise RuntimeError("Managed warehouse reader credentials did not match the requested credentials")
+
+ 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)
+ membership_exists = DuckgresServerTeam.objects.select_for_update().filter(
+ server=server,
+ team_id=team_id,
+ backfill_enabled=True,
+ table_suffix=table_suffix,
+ )
+ if not membership_exists.exists():
+ raise ValueError("The team has not joined this managed warehouse")
+ source = _managed_source_queryset(team_id).select_for_update().filter(id=source_id, deleted=False).first()
+ if source is None or not isinstance(source.job_inputs, dict):
+ raise RuntimeError("Managed warehouse query source changed while its reader was configured")
+ if source.job_inputs.get("user") != username or source.job_inputs.get("password") != password:
+ raise RuntimeError("Managed warehouse query source changed while its reader was configured")
+ connection_metadata = dict(source.connection_metadata or {})
+ source.connection_metadata = {**connection_metadata, "reader_configured": True}
+ source.direct_query_enabled = True
+ source.save(update_fields=["connection_metadata", "direct_query_enabled", "updated_at"])
+ return source
+
+
+def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:
+ """Discover and register only this team's managed-warehouse tables."""
+ from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415
+
+ try:
+ ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)
+ except (DuckgresServer.DoesNotExist, Team.DoesNotExist, ValueError):
+ return
+ except RuntimeError:
+ # The credential handshake needs the warehouse control plane; while an org is still
+ # provisioning this fails on every sweep, so skip quietly and let the next run retry.
+ logger.info("Managed warehouse reader handshake not possible yet", team_id=team_id)
+ return
+
+ with transaction.atomic():
+ server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()
+ team = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()
+ if server is None or team is None:
+ return
+
+ membership_data = (
+ DuckgresServerTeam.objects.select_for_update()
+ .filter(
+ server=server,
+ team_id=team_id,
+ team__organization_id=organization_id,
+ backfill_enabled=True,
+ )
+ .values("table_suffix")
+ .first()
+ )
+ if membership_data is None:
+ return
+
+ table_suffix = membership_data["table_suffix"]
+ if not table_suffix:
+ # Legacy tables are shared across teams and require a team_id predicate that direct HogQL cannot enforce.
+ return
+ source = _managed_source_queryset(team_id).select_for_update().filter(deleted=False).first()
+ if source is None:
+ return
+ source_id = source.id
+ source_config = dict(source.job_inputs or {})
+
+ # The allowlist mirrors the live Duckgres org-team row (the same row its reader policy is
+ # derived from), so hand-set layouts — legacy overrides like team 2's posthog.events, custom
+ # schema names like devex — stay in sync instead of assuming the suffix-derived scheme.
+ # Introspection also runs AS the reader, so this filter is defense in depth, not the boundary.
+ namespaces = managed_warehouse.project_reader_namespaces(organization_id=organization_id, team_id=team_id)
+ if namespaces is None:
+ return
+ allowed_schemas, allowed_relations = namespaces
+
+ source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
+ config = source_impl.parse_config(source_config)
+ try:
+ discovered = source_impl.get_schemas(config, team_id)
+ except Exception:
+ # A provisioning or briefly unreachable warehouse fails here on every periodic sweep;
+ # skip and let the next run retry rather than surfacing a task error each time.
+ logger.warning("Managed warehouse introspection failed; will retry", team_id=team_id, exc_info=True)
+ return
+ source_schemas = [
+ schema
+ for schema in discovered
+ if (schema.source_schema or "", schema.source_table_name or schema.name.rsplit(".", 1)[-1]) in allowed_relations
+ or (schema.source_schema or "") in allowed_schemas
+ ]
+ if not source_schemas:
+ return
+
+ with transaction.atomic():
+ # Revalidate after live introspection so deprovision or membership removal wins the race.
+ server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()
+ team = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()
+ if server is None or team is None:
+ return
+ membership = (
+ DuckgresServerTeam.objects.select_for_update()
+ .filter(
+ server=server,
+ team_id=team_id,
+ team__organization_id=organization_id,
+ table_suffix=table_suffix,
+ backfill_enabled=True,
+ )
+ .first()
+ )
+ source = (
+ _managed_source_queryset(team_id)
+ .select_for_update()
+ .filter(
+ id=source_id,
+ deleted=False,
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ direct_query_enabled=True,
+ )
+ .first()
+ )
+ if membership is None or source is None:
+ return
+
+ for schema in source_schemas:
+ schema_model, _created = ExternalDataSchema.objects.get_or_create(
+ team_id=team_id,
+ source=source,
+ name=schema.name,
+ defaults={"should_sync": True, "sync_type": None, "sync_type_config": {}},
+ )
+ if schema_model.deleted:
+ schema_model.deleted = False
+ schema_model.deleted_at = None
+ schema_model.should_sync = True
+ schema_model.save(update_fields=["deleted", "deleted_at", "should_sync", "updated_at"])
+
+ reconcile_postgres_schemas(source=source, source_schemas=source_schemas, team_id=team_id)
+
+
+def _managed_sources_for_org(organization_id: str | UUID) -> QuerySet[ExternalDataSource]:
+ return ExternalDataSource._base_manager.filter(
+ team__organization_id=organization_id,
+ source_type=ExternalDataSourceType.POSTGRES,
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ connection_metadata__system_managed=True,
+ ).exclude(deleted=True)
+
+
+def update_managed_warehouse_root_password(*, organization_id: str | UUID, password: str) -> None:
+ """Refresh the internal root writer without changing project reader credentials."""
+ from posthog.ducklake.models import DuckgresServer # noqa: PLC0415
+
+ with transaction.atomic():
+ server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)
+ server.password = password
+ server.save(update_fields=["password", "updated_at"])
+
+
+def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID) -> None:
+ """Atomically tombstone the organization's managed query sources on deprovision."""
+ from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam # noqa: PLC0415
+
+ now = timezone.now()
+ with transaction.atomic():
+ DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()
+ sources = list(_managed_sources_for_org(organization_id).select_for_update().order_by("team_id"))
+ DuckgresServerTeam.objects.filter(server__organization_id=organization_id).update(backfill_enabled=False)
+ DataWarehouseTable.raw_objects.filter(
+ external_data_source_id__in=[source.id for source in sources], deleted=False
+ ).update(deleted=True, deleted_at=now, updated_at=now)
+ for source in sources:
+ source.deleted = True
+ source.deleted_at = now
+ source.save(update_fields=["deleted", "deleted_at", "updated_at"])
diff --git a/products/data_warehouse/backend/presentation/views/data_warehouse.py b/products/data_warehouse/backend/presentation/views/data_warehouse.py
index 56595d22650d..2700000991bb 100644
--- a/products/data_warehouse/backend/presentation/views/data_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/data_warehouse.py
@@ -1013,6 +1013,10 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):
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))
+ # 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":
+ managed_warehouse.ensure_direct_connection_tables(self.team_id, self.team.organization_id)
return resp
@extend_schema(responses={200: ManagedWarehouseDataStatusResponseSerializer})
diff --git a/products/data_warehouse/backend/presentation/views/external_data_schema.py b/products/data_warehouse/backend/presentation/views/external_data_schema.py
index 5ed035a6f0c7..30e3549927aa 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_schema.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_schema.py
@@ -9,7 +9,7 @@ import temporalio
from asgiref.sync import async_to_sync
from drf_spectacular.utils import OpenApiResponse, extend_schema, extend_schema_field
from rest_framework import filters, serializers, status, viewsets
-from rest_framework.exceptions import MethodNotAllowed, ValidationError
+from rest_framework.exceptions import MethodNotAllowed, PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
@@ -1304,6 +1304,12 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
search_fields = ["name"]
ordering = "-created_at"
+ def check_object_permissions(self, request: Request, obj: Any) -> None:
+ super().check_object_permissions(request, obj)
+ if request.method not in ("GET", "HEAD", "OPTIONS") and isinstance(obj, ExternalDataSchema):
+ if obj.source.is_system_managed:
+ raise PermissionDenied("This schema is managed by PostHog and cannot be changed through this API.")
+
@extend_schema(exclude=True)
def create(self, request: Request, *args: Any, **kwargs: Any) -> Response:
# Schemas are created by source schema discovery, never via the API. ModelViewSet would
diff --git a/products/data_warehouse/backend/presentation/views/external_data_source.py b/products/data_warehouse/backend/presentation/views/external_data_source.py
index 0f79eeea09b8..b858c405e6bd 100644
--- a/products/data_warehouse/backend/presentation/views/external_data_source.py
+++ b/products/data_warehouse/backend/presentation/views/external_data_source.py
@@ -21,7 +21,7 @@ from drf_spectacular.utils import OpenApiParameter, OpenApiResponse, extend_sche
from openai import APIConnectionError
from psycopg import OperationalError
from rest_framework import filters, serializers, status, viewsets
-from rest_framework.exceptions import APIException, ValidationError
+from rest_framework.exceptions import APIException, PermissionDenied, ValidationError
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -166,6 +166,7 @@ from products.warehouse_sources.backend.facade.types import DataWarehouseManaged
logger = structlog.get_logger(__name__)
REFRESH_SCHEMAS_FALLBACK_ERROR_MESSAGE = "Could not fetch schemas from source."
+RESERVED_SOURCE_NAME_MESSAGE = "This source name is reserved by PostHog."
REFRESH_SCHEMAS_EXPECTED_ERROR_MESSAGES = {
"timeout": "Connection timed out while fetching schemas from the source.",
@@ -1000,6 +1001,8 @@ class ExternalDataSourceSerializers(UserAccessControlSerializerMixin, serializer
normalized_prefix = incoming_prefix.strip() if isinstance(incoming_prefix, str) else ""
if not normalized_prefix:
raise ValidationError("Name is required for direct query sources")
+ if ExternalDataSource.is_system_managed_prefix(normalized_prefix):
+ raise ValidationError(RESERVED_SOURCE_NAME_MESSAGE)
validated_data["prefix"] = normalized_prefix
else:
validated_data["prefix"] = instance.prefix
@@ -1712,6 +1715,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
search_fields = ["source_type", "prefix"]
ordering = "-created_at"
+ def check_object_permissions(self, request: Request, obj: Any) -> None:
+ super().check_object_permissions(request, obj)
+ if request.method not in ("GET", "HEAD", "OPTIONS") and isinstance(obj, ExternalDataSource):
+ if obj.is_system_managed:
+ raise PermissionDenied("This source is managed by PostHog and cannot be changed through this API.")
+
def dangerously_get_permissions(self):
# 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
@@ -2014,6 +2023,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
created_via = ExternalDataSource.CreatedVia.SELF_DRIVING
is_direct_query = access_method == ExternalDataSource.AccessMethod.DIRECT
+ if ExternalDataSource.is_system_managed_prefix(prefix):
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": RESERVED_SOURCE_NAME_MESSAGE},
+ )
+
if is_direct_query and source_type not in direct_capable_source_types():
return Response(
status=status.HTTP_400_BAD_REQUEST,
@@ -4154,6 +4169,12 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
source_type = request.data["source_type"]
access_method = request.data.get("access_method", ExternalDataSource.AccessMethod.WAREHOUSE)
+ if ExternalDataSource.is_system_managed_prefix(prefix):
+ return Response(
+ status=status.HTTP_400_BAD_REQUEST,
+ data={"message": RESERVED_SOURCE_NAME_MESSAGE},
+ )
+
if access_method == ExternalDataSource.AccessMethod.DIRECT:
if source_type not in direct_capable_source_types():
return Response(
diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.py
index f8b1c9ebd7c3..11723d3f530c 100644
--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py
@@ -190,6 +190,91 @@ def _request(
return Response(body, status=resp.status_code)
+def _get_project_team_row(*, organization_id: UUID | str, team_id: int) -> dict | None:
+ """Fetch the org-team row Duckgres currently holds for this project, if any."""
+ resp = _request("GET", organization_id, "/teams", require_enabled=False)
+ if not status.is_success(resp.status_code) or not isinstance(resp.data, dict):
+ raise RuntimeError("Failed to read the organization's managed warehouse team rows")
+ for row in resp.data.get("teams") or []:
+ if isinstance(row, dict) and row.get("team_id") == team_id:
+ return row
+ return None
+
+
+def configure_project_reader(
+ *, organization_id: UUID | str, team_id: int, table_suffix: str, password: str
+) -> dict[str, str]:
+ """Apply the project's read-only credential, creating its team row only when absent.
+
+ The org-team row is Duckgres-owned state that also drives external-writer discovery
+ (viaduck/millpond write targets) and may be hand-set (break-glass edits, legacy layouts).
+ An existing row is therefore never rewritten from this path; the derived naming below is
+ used only to create a row that does not exist yet.
+ """
+ row = _get_project_team_row(organization_id=organization_id, team_id=team_id)
+ if row is None:
+ team_response = _request(
+ "POST",
+ organization_id,
+ "/teams",
+ json_body={
+ "team_id": team_id,
+ "schema_name": f"team_{team_id}",
+ "enabled": True,
+ "events_table_name": f"events_{table_suffix}",
+ "persons_table_name": f"persons_{table_suffix}",
+ "schema_data_imports_name": f"posthog_data_imports_{table_suffix}",
+ },
+ require_enabled=False,
+ )
+ if not status.is_success(team_response.status_code):
+ raise RuntimeError("Failed to register the project's managed warehouse namespaces")
+ elif row.get("enabled") is not True:
+ # `enabled` is an operator-facing serving hold; do not silently lift it here.
+ raise RuntimeError("The project's managed warehouse team row is disabled")
+
+ credential_response = _request(
+ "PUT",
+ organization_id,
+ f"/teams/{team_id}/project-reader",
+ json_body={"password": password},
+ require_enabled=False,
+ )
+ if not status.is_success(credential_response.status_code) or not isinstance(credential_response.data, dict):
+ raise RuntimeError("Failed to create the project's managed warehouse reader")
+ username = credential_response.data.get("username")
+ response_password = credential_response.data.get("password")
+ if not isinstance(username, str) or not username or not isinstance(response_password, str) or not response_password:
+ raise RuntimeError("Managed warehouse reader response did not include credentials")
+ return {"username": username, "password": response_password}
+
+
+def project_reader_namespaces(
+ *, organization_id: UUID | str, team_id: int
+) -> tuple[set[str], set[tuple[str, str]]] | None:
+ """Return the (whole schemas, legacy posthog-schema tables) the project's reader may see.
+
+ Mirrors the Duckgres policy derivation from the org-team row: the reader is granted the row's
+ schema_name, its data-imports schema (override or `<schema>_data_imports`), the modeled-data
+ schema, and `posthog.<override>` for each non-NULL legacy events/persons override — including
+ overrides that spell the derived default name. None means no enabled row exists (fail closed).
+ """
+ row = _get_project_team_row(organization_id=organization_id, team_id=team_id)
+ if row is None or row.get("enabled") is not True:
+ return None
+ schema_name = str(row.get("schema_name") or "")
+ if not schema_name:
+ return None
+ imports_schema = str(row.get("schema_data_imports_name") or "") or f"{schema_name}_data_imports"
+ schemas = {schema_name, imports_schema, f"shadow_{team_id}_models"}
+ relations: set[tuple[str, str]] = set()
+ for override_field in ("events_table_name", "persons_table_name"):
+ override = row.get(override_field)
+ if isinstance(override, str) and override:
+ relations.add(("posthog", override))
+ return schemas, relations
+
+
def provision(
organization_id: UUID | str,
database_name: str | None,
@@ -640,7 +725,66 @@ def block_team_deletion(team_id: int, organization_id: UUID | str) -> str | None
def deprovision(organization_id: UUID | str, require_enabled: bool = True) -> Response:
- return _request("POST", organization_id, "/deprovision", require_enabled=require_enabled)
+ resp = _request("POST", organization_id, "/deprovision", require_enabled=require_enabled)
+ if status.is_success(resp.status_code):
+ # Deprovision is not re-POSTable (Duckgres 409s once the org leaves a deprovisionable
+ # state), so a failed local cleanup must converge via the retrying task, not the operator.
+ try:
+ _remove_direct_connection_sources(organization_id)
+ except Exception:
+ logger.exception("Failed to remove managed warehouse query sources", organization_id=str(organization_id))
+ try:
+ _schedule_remove_direct_connection_sources(organization_id)
+ except Exception:
+ logger.exception(
+ "Failed to schedule managed warehouse query source removal",
+ organization_id=str(organization_id),
+ )
+ return Response(
+ {
+ "error": "The warehouse was deprovisioned but its SQL connections could not be removed or scheduled for removal. They must be cleaned up manually."
+ },
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+ return resp
+
+
+def _remove_direct_connection_sources(organization_id: UUID | str) -> None:
+ """Soft-delete the org's auto-created Postgres query connections after deprovisioning."""
+ # Keep the data_warehouse/warehouse_sources stack off this adapter's import path.
+ from products.data_warehouse.backend.facade.api import soft_delete_managed_warehouse_sources # noqa: PLC0415
+
+ soft_delete_managed_warehouse_sources(organization_id=organization_id)
+
+
+def _schedule_remove_direct_connection_sources(organization_id: UUID | str) -> None:
+ """Queue the retrying cleanup task when the inline soft-delete failed."""
+ # Keep the Celery task stack off this adapter's import path.
+ from products.data_warehouse.backend.facade.api import ( # noqa: PLC0415
+ schedule_soft_delete_managed_warehouse_sources,
+ )
+
+ schedule_soft_delete_managed_warehouse_sources(organization_id=organization_id)
+
+
+def ensure_direct_connection_tables(team_id: int, organization_id: UUID | str) -> None:
+ """Queue discovery of the team's managed-warehouse tables for the SQL editor.
+
+ Called from the warehouse-status read once the warehouse is `ready`. Repeated requests are
+ coalesced for a short interval, while later runs re-introspect the live catalog so newly created
+ project tables appear automatically.
+ """
+ # Keep the Celery and data-warehouse task stack off this adapter's import path.
+ from products.data_warehouse.backend.facade.api import schedule_managed_warehouse_tables_reconcile # noqa: PLC0415
+
+ try:
+ schedule_managed_warehouse_tables_reconcile(team_id=team_id, organization_id=organization_id)
+ except Exception:
+ logger.exception(
+ "Failed to schedule managed warehouse direct connection table reconciliation",
+ organization_id=str(organization_id),
+ team_id=team_id,
+ )
def delete_org(organization_id: UUID | str, require_enabled: bool = True) -> Response:
@@ -756,7 +900,25 @@ def _reconcile_bucket_from_status(organization_id: UUID | str, body: dict) -> No
def reset_password(organization_id: UUID | str) -> Response:
- return _request("POST", organization_id, "/reset-password")
+ resp = _request("POST", organization_id, "/reset-password")
+ if status.is_success(resp.status_code) and isinstance(resp.data, dict) and resp.data.get("password"):
+ try:
+ _update_direct_connection_password(organization_id, resp.data["password"])
+ except Exception:
+ logger.exception("Failed to update managed warehouse stored password", organization_id=str(organization_id))
+ return Response(
+ {"error": "The password was rotated but could not be saved. Retry the password reset."},
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+ return resp
+
+
+def _update_direct_connection_password(organization_id: UUID | str, password: str) -> None:
+ """Sync the rotated root password into the server row and query connections."""
+ # Keep the data_warehouse/warehouse_sources stack off this adapter's import path.
+ from products.data_warehouse.backend.facade.api import update_managed_warehouse_root_password # noqa: PLC0415
+
+ update_managed_warehouse_root_password(organization_id=organization_id, password=password)
def check_name(organization_id: UUID | str, name: str | None) -> Response:
diff --git a/products/data_warehouse/backend/tasks/__init__.py b/products/data_warehouse/backend/tasks/__init__.py
index b47c37124d5f..9982e473bb54 100644
--- a/products/data_warehouse/backend/tasks/__init__.py
+++ b/products/data_warehouse/backend/tasks/__init__.py
@@ -1,5 +1,8 @@
from products.data_warehouse.backend.tasks.tasks import * # noqa: F401,F403
from products.data_warehouse.backend.tasks.tasks import ( # noqa: F401
+ reconcile_all_managed_warehouse_tables_task,
+ reconcile_managed_warehouse_tables_task,
+ schedule_managed_warehouse_tables_reconcile,
send_external_data_failure_digest_catchup,
send_external_data_failure_digest_task,
)
diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.py
index fc3d83b8e57c..9e4ca2c48cf7 100644
--- a/products/data_warehouse/backend/tasks/tasks.py
+++ b/products/data_warehouse/backend/tasks/tasks.py
@@ -1,7 +1,10 @@
+from uuid import UUID
+
import structlog
from celery import shared_task
from prometheus_client import Counter
+from posthog.ducklake.models import DuckgresServerTeam
from posthog.redis import get_client, redis
from posthog.scoping_audit import skip_team_scope_audit
@@ -9,6 +12,7 @@ from products.data_warehouse.backend.logic.external_data_source.notifications im
get_team_ids_with_recent_sync_failures,
notify_external_data_sync_failures,
)
+from products.data_warehouse.backend.managed_warehouse_connection import reconcile_managed_warehouse_tables
logger = structlog.get_logger(__name__)
@@ -40,6 +44,71 @@ 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 plus the credential handshake 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
+MANAGED_WAREHOUSE_RECONCILE_INTERVAL_SECONDS = 60
+
+
+@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.reconcile_managed_warehouse_tables")
+@skip_team_scope_audit
+def reconcile_managed_warehouse_tables_task(team_id: int, organization_id: str) -> None:
+ try:
+ with get_client().lock(
+ f"managed_warehouse_reconcile:{team_id}",
+ timeout=MANAGED_WAREHOUSE_RECONCILE_LOCK_TIMEOUT_SECONDS,
+ blocking=False,
+ ):
+ reconcile_managed_warehouse_tables(team_id=team_id, organization_id=organization_id)
+ except redis.exceptions.LockError:
+ logger.info("Managed warehouse table reconciliation already in flight", team_id=team_id)
+
+
+def schedule_managed_warehouse_tables_reconcile(*, team_id: int, organization_id: str | UUID) -> None:
+ client = get_client()
+ schedule_key = f"managed_warehouse_reconcile_scheduled:{team_id}"
+ if not client.set(schedule_key, "1", ex=MANAGED_WAREHOUSE_RECONCILE_INTERVAL_SECONDS, nx=True):
+ return
+ try:
+ reconcile_managed_warehouse_tables_task.delay(team_id=team_id, organization_id=str(organization_id))
+ except Exception:
+ client.delete(schedule_key)
+ raise
+
+
+@shared_task(
+ ignore_result=True,
+ name="products.data_warehouse.backend.tasks.soft_delete_managed_warehouse_sources",
+ autoretry_for=(Exception,),
+ retry_backoff=60,
+ retry_backoff_max=3600,
+ max_retries=10,
+)
+@skip_team_scope_audit
+def soft_delete_managed_warehouse_sources_task(organization_id: str) -> None:
+ from products.data_warehouse.backend.managed_warehouse_connection import ( # noqa: PLC0415
+ soft_delete_managed_warehouse_sources,
+ )
+
+ soft_delete_managed_warehouse_sources(organization_id=organization_id)
+
+
+def schedule_soft_delete_managed_warehouse_sources(*, organization_id: str | UUID) -> None:
+ soft_delete_managed_warehouse_sources_task.delay(organization_id=str(organization_id))
+
+
+@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.reconcile_all_managed_warehouse_tables")
+@skip_team_scope_audit
+def reconcile_all_managed_warehouse_tables_task() -> None:
+ memberships = (
+ DuckgresServerTeam.objects.filter(backfill_enabled=True, table_suffix__isnull=False)
+ .exclude(table_suffix="")
+ .values_list("team_id", "server__organization_id")
+ .iterator()
+ )
+ for team_id, organization_id in memberships:
+ schedule_managed_warehouse_tables_reconcile(team_id=team_id, organization_id=organization_id)
def schedule_external_data_failure_digest(team_id: int, *, trigger: str = "inline") -> None:
diff --git a/products/data_warehouse/backend/tests/api/test_external_data_source.py b/products/data_warehouse/backend/tests/api/test_external_data_source.py
index b3305c67ba65..a8592680e05d 100644
--- a/products/data_warehouse/backend/tests/api/test_external_data_source.py
+++ b/products/data_warehouse/backend/tests/api/test_external_data_source.py
@@ -2746,6 +2746,39 @@ class TestExternalDataSource(APIBaseTest):
)
self.assertCountEqual(names, ["table_a", "table_b"])
+ @patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")
+ def test_system_managed_source_rejects_schema_refresh(self, mock_get_source):
+ source = self._create_external_data_source()
+ source.connection_metadata = {"system_managed": True}
+ source.save(update_fields=["connection_metadata"])
+
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/{source.pk}/refresh_schemas/"
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ mock_get_source.assert_not_called()
+
+ def test_system_managed_source_schema_rejects_update(self):
+ source = self._create_external_data_source()
+ source.connection_metadata = {"system_managed": True}
+ source.save(update_fields=["connection_metadata"])
+ schema = ExternalDataSchema.objects.create(
+ name="sibling_team_events",
+ team_id=self.team.pk,
+ source=source,
+ should_sync=False,
+ )
+
+ response = self.client.patch(
+ f"/api/environments/{self.team.pk}/external_data_schemas/{schema.pk}/",
+ data={"should_sync": True},
+ )
+
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ schema.refresh_from_db()
+ assert schema.should_sync is False
+
@patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow")
@patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")
def test_refresh_schemas_auto_enables_matching_new_schemas(self, mock_get_source, mock_schedule):
@@ -3514,6 +3547,22 @@ class TestExternalDataSource(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json(), {"message": "Name is required for direct query sources"})
+ def test_create_direct_postgres_rejects_the_managed_warehouse_name(self):
+ response = self.client.post(
+ f"/api/environments/{self.team.pk}/external_data_sources/",
+ data={
+ "source_type": "Postgres",
+ "created_via": "web",
+ "access_method": "direct",
+ "prefix": "managed_warehouse",
+ "payload": {},
+ },
+ )
+
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert response.json() == {"message": "This source name is reserved by PostHog."}
+ assert not ExternalDataSource.objects.filter(team=self.team, prefix="managed_warehouse").exists()
+
@patch("products.data_warehouse.backend.presentation.views.external_data_source.SourceRegistry.get_source")
def test_create_direct_postgres_does_not_require_prefix_namespace(self, mock_get_source):
_configure_source_mock_versioning(mock_get_source)
diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py
index 6067f4232c74..1a1084f3316f 100644
--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py
+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py
@@ -1,7 +1,7 @@
from uuid import uuid4
import pytest
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
from django.test import override_settings
@@ -14,6 +14,153 @@ from posthog.models import Organization, Team
from products.data_warehouse.backend.presentation.views import managed_warehouse
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_configure_project_reader_creates_a_missing_team_row_before_rotating_credentials(
+ mock_request: MagicMock,
+) -> None:
+ organization_id = uuid4()
+ mock_request.side_effect = [
+ Response({"teams": []}, status=200),
+ Response({"team_id": 42}, status=200),
+ Response({"username": "posthog_team_42", "password": "reader-password"}, status=200),
+ ]
+
+ credentials = managed_warehouse.configure_project_reader(
+ organization_id=organization_id,
+ team_id=42,
+ table_suffix="prod",
+ password="caller-managed-password-with-32-characters",
+ )
+
+ assert credentials == {"username": "posthog_team_42", "password": "reader-password"}
+ assert mock_request.call_args_list == [
+ call("GET", organization_id, "/teams", require_enabled=False),
+ call(
+ "POST",
+ organization_id,
+ "/teams",
+ json_body={
+ "team_id": 42,
+ "schema_name": "team_42",
+ "enabled": True,
+ "events_table_name": "events_prod",
+ "persons_table_name": "persons_prod",
+ "schema_data_imports_name": "posthog_data_imports_prod",
+ },
+ require_enabled=False,
+ ),
+ call(
+ "PUT",
+ organization_id,
+ "/teams/42/project-reader",
+ json_body={"password": "caller-managed-password-with-32-characters"},
+ require_enabled=False,
+ ),
+ ]
+
+
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_configure_project_reader_never_rewrites_an_existing_team_row(mock_request: MagicMock) -> None:
+ # The Duckgres org-team row also drives external-writer discovery (viaduck/millpond), and rows
+ # can be hand-set (break-glass edits, legacy layouts like the dogfood devex/team-2 rows).
+ # Credential setup must therefore never POST over an existing row.
+ organization_id = uuid4()
+ mock_request.side_effect = [
+ Response(
+ {"teams": [{"team_id": 42, "schema_name": "devex", "enabled": True, "events_table_name": "events"}]},
+ status=200,
+ ),
+ Response({"username": "posthog_team_42", "password": "reader-password"}, status=200),
+ ]
+
+ credentials = managed_warehouse.configure_project_reader(
+ organization_id=organization_id,
+ team_id=42,
+ table_suffix="prod",
+ password="caller-managed-password-with-32-characters",
+ )
+
+ assert credentials == {"username": "posthog_team_42", "password": "reader-password"}
+ assert mock_request.call_args_list == [
+ call("GET", organization_id, "/teams", require_enabled=False),
+ call(
+ "PUT",
+ organization_id,
+ "/teams/42/project-reader",
+ json_body={"password": "caller-managed-password-with-32-characters"},
+ require_enabled=False,
+ ),
+ ]
+
+
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_configure_project_reader_refuses_a_disabled_team_row(mock_request: MagicMock) -> None:
+ # `enabled` is an operator-facing serving hold; credential setup must not silently lift it.
+ mock_request.return_value = Response(
+ {"teams": [{"team_id": 42, "schema_name": "team_42", "enabled": False}]}, status=200
+ )
+
+ with pytest.raises(RuntimeError, match="disabled"):
+ managed_warehouse.configure_project_reader(
+ organization_id=uuid4(),
+ team_id=42,
+ table_suffix="prod",
+ password="caller-managed-password-with-32-characters",
+ )
+
+ assert len(mock_request.call_args_list) == 1
+
+
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_project_reader_namespaces_mirror_the_duckgres_team_row(mock_request: MagicMock) -> None:
+ # Must match the Duckgres policy derivation: a non-NULL legacy override always grants
+ # posthog.<name> — including overrides that spell the derived default (team 2's
+ # events_table_name="events" -> posthog.events); NULL overrides grant nothing extra.
+ mock_request.return_value = Response(
+ {
+ "teams": [
+ {
+ "team_id": 2,
+ "schema_name": "team_2",
+ "enabled": True,
+ "events_table_name": "events",
+ "persons_table_name": "persons",
+ "schema_data_imports_name": "posthog_data_imports_team_2",
+ }
+ ]
+ },
+ status=200,
+ )
+
+ namespaces = managed_warehouse.project_reader_namespaces(organization_id=uuid4(), team_id=2)
+
+ assert namespaces == (
+ {"team_2", "posthog_data_imports_team_2", "shadow_2_models"},
+ {("posthog", "events"), ("posthog", "persons")},
+ )
+
+
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_project_reader_namespaces_derive_imports_and_skip_absent_overrides(mock_request: MagicMock) -> None:
+ mock_request.return_value = Response(
+ {"teams": [{"team_id": 7, "schema_name": "team_7", "enabled": True}]}, status=200
+ )
+
+ namespaces = managed_warehouse.project_reader_namespaces(organization_id=uuid4(), team_id=7)
+
+ assert namespaces == ({"team_7", "team_7_data_imports", "shadow_7_models"}, set())
+
+
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_project_reader_namespaces_fail_closed_without_an_enabled_row(mock_request: MagicMock) -> None:
+ mock_request.return_value = Response(
+ {"teams": [{"team_id": 7, "schema_name": "team_7", "enabled": False}]}, status=200
+ )
+
+ assert managed_warehouse.project_reader_namespaces(organization_id=uuid4(), team_id=7) is None
+ assert managed_warehouse.project_reader_namespaces(organization_id=uuid4(), team_id=8) is None
+
+
@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.posthoganalytics.feature_enabled")
def test_is_enabled_uses_data_warehouse_scene_flag(mock_feature_enabled: MagicMock) -> None:
organization_id = uuid4()
@@ -31,6 +178,56 @@ def test_is_enabled_uses_data_warehouse_scene_flag(mock_feature_enabled: MagicMo
)
+@patch("products.data_warehouse.backend.facade.api.update_managed_warehouse_root_password")
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_reset_password_reports_local_persistence_failure(
+ mock_request: MagicMock, mock_update_password: MagicMock
+) -> None:
+ mock_request.return_value = Response({"password": "rotated"}, status=200)
+ mock_update_password.side_effect = RuntimeError("database unavailable")
+
+ response = managed_warehouse.reset_password(uuid4())
+
+ assert response.status_code == 500
+ assert response.data == {"error": "The password was rotated but could not be saved. Retry the password reset."}
+
+
+@patch("products.data_warehouse.backend.facade.api.schedule_soft_delete_managed_warehouse_sources")
+@patch("products.data_warehouse.backend.facade.api.soft_delete_managed_warehouse_sources")
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_deprovision_schedules_cleanup_retry_when_inline_cleanup_fails(
+ mock_request: MagicMock, mock_soft_delete: MagicMock, mock_schedule: MagicMock
+) -> None:
+ # Deprovision is not re-POSTable (Duckgres 409s once the org leaves a deprovisionable state),
+ # so a failed local cleanup must converge on its own instead of asking the operator to retry.
+ mock_request.return_value = Response({"status": "deprovisioning started"}, status=202)
+ mock_soft_delete.side_effect = RuntimeError("database unavailable")
+ organization_id = uuid4()
+
+ response = managed_warehouse.deprovision(organization_id)
+
+ assert response.status_code == 202
+ mock_schedule.assert_called_once_with(organization_id=organization_id)
+
+
+@patch("products.data_warehouse.backend.facade.api.schedule_soft_delete_managed_warehouse_sources")
+@patch("products.data_warehouse.backend.facade.api.soft_delete_managed_warehouse_sources")
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
+def test_deprovision_reports_when_cleanup_and_its_retry_cannot_be_scheduled(
+ mock_request: MagicMock, mock_soft_delete: MagicMock, mock_schedule: MagicMock
+) -> None:
+ mock_request.return_value = Response({"status": "deprovisioning started"}, status=202)
+ mock_soft_delete.side_effect = RuntimeError("database unavailable")
+ mock_schedule.side_effect = RuntimeError("broker unavailable")
+
+ response = managed_warehouse.deprovision(uuid4())
+
+ assert response.status_code == 500
+ assert response.data == {
+ "error": "The warehouse was deprovisioned but its SQL connections could not be removed or scheduled for removal. They must be cleaned up manually."
+ }
+
+
@pytest.mark.django_db
@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)
@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")
@@ -72,7 +269,7 @@ def test_provision_sends_team_id_and_schema_name_to_control_plane(mock_request:
managed_warehouse.provision(org.id, "my-warehouse", team.id, "prod_events")
- json_body = mock_request.call_args.kwargs["json_body"]
+ json_body = mock_request.call_args_list[0].kwargs["json_body"]
assert json_body["team_id"] == team.id
assert json_body["schema_name"] == "prod_events"
assert "default_team_id" not in json_body
@@ -406,9 +603,9 @@ def test_onboard_team_dual_writes_duckgres_and_django(mock_request: MagicMock, _
# duckgres team row created via the org-teams upsert, without legacy table names
# (NULL legacy fields mean the derived <schema>.events layout).
- method, org_id, path = mock_request.call_args.args
+ method, org_id, path = mock_request.call_args_list[0].args
assert (method, org_id, path) == ("POST", org.id, "/teams")
- json_body = mock_request.call_args.kwargs["json_body"]
+ json_body = mock_request.call_args_list[0].kwargs["json_body"]
assert json_body == {"team_id": team.id, "schema_name": "my_events"}
link = DuckgresServerTeam.objects.get(server=server, team_id=team.id)
diff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py b/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py
new file mode 100644
index 000000000000..b51e825f2e84
--- /dev/null
+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py
@@ -0,0 +1,632 @@
+from typing import TypedDict
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.hogql.direct_connection import get_direct_connection_source
+from posthog.hogql.errors import QueryError
+from posthog.hogql.query import HogQLQueryExecutor
+
+from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam
+from posthog.models import Organization, Team
+
+from products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_PATTERN
+from products.data_warehouse.backend.managed_warehouse_connection import (
+ MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ ensure_managed_warehouse_direct_source,
+ reconcile_managed_warehouse_tables,
+ soft_delete_managed_warehouse_sources,
+ update_managed_warehouse_root_password,
+)
+from products.data_warehouse.backend.presentation.views import managed_warehouse
+from products.data_warehouse.backend.tasks import reconcile_all_managed_warehouse_tables_task
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
+from products.warehouse_sources.backend.models.table import DataWarehouseTable
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+
+
+class _Connection(TypedDict):
+ host: str
+ port: int
+ database: str
+ username: str
+ password: str
+
+
+_CONNECTION: _Connection = {
+ "host": "wh.dw.us.postwh.com",
+ "port": 5432,
+ "database": "ducklake",
+ "username": "root",
+ "password": "pw",
+}
+
+_PROJECT_READER_PASSWORD = "reader-password-with-at-least-32-characters"
+
+
[email protected](autouse=True)
+def _mock_project_reader_credentials():
+ def configure_project_reader(*, team_id: int, password: str, **_kwargs: object) -> dict[str, str]:
+ return {"username": f"posthog_team_{team_id}", "password": password}
+
+ def project_reader_namespaces(*, team_id: int, **_kwargs: object) -> tuple[set[str], set[tuple[str, str]]]:
+ # Mirrors the Duckgres row these tests provision (suffix "prod" layout).
+ return (
+ {f"team_{team_id}", "posthog_data_imports_prod", f"shadow_{team_id}_models"},
+ {("posthog", "events_prod"), ("posthog", "persons_prod")},
+ )
+
+ with (
+ patch.object(managed_warehouse, "configure_project_reader", side_effect=configure_project_reader) as mocked,
+ patch.object(managed_warehouse, "project_reader_namespaces", side_effect=project_reader_namespaces),
+ patch(
+ "products.data_warehouse.backend.managed_warehouse_connection.secrets.token_urlsafe",
+ return_value=_PROJECT_READER_PASSWORD,
+ ),
+ ):
+ yield mocked
+
+
+def _ensure(team: Team) -> ExternalDataSource:
+ return ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=team.organization_id)
+
+
+class TestEnsureManagedWarehouseDirectSource:
+ def test_creates_a_restricted_postgres_query_source_from_the_server(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")
+
+ 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 warehouse connection so live queries reach it.
+ assert source.job_inputs["host"] == _CONNECTION["host"]
+ assert source.job_inputs["user"] == f"posthog_team_{team.id}"
+ assert source.job_inputs["password"] == _PROJECT_READER_PASSWORD
+ assert source.connection_metadata["credential_kind"] == "project_reader"
+
+ 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)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")
+
+ first = _ensure(team)
+ second = _ensure(team)
+
+ assert first.pk == second.pk
+ assert ExternalDataSource.objects.filter(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX).count() == 1
+
+ def test_concurrent_reader_setup_reuses_the_persisted_credential(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")
+ requested_passwords: list[str] = []
+
+ def configure_project_reader(*, team_id: int, password: str, **_kwargs: object) -> dict[str, str]:
+ requested_passwords.append(password)
+ if len(requested_passwords) == 1:
+ _ensure(team)
+ return {"username": f"posthog_team_{team_id}", "password": password}
+
+ with patch.object(managed_warehouse, "configure_project_reader", side_effect=configure_project_reader):
+ source = _ensure(team)
+
+ source.refresh_from_db()
+ assert requested_passwords == [_PROJECT_READER_PASSWORD, _PROJECT_READER_PASSWORD]
+ assert source.direct_query_enabled is True
+ assert isinstance(source.connection_metadata, dict)
+ assert source.connection_metadata["reader_configured"] is True
+ assert ExternalDataSource.objects.filter(team=team, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX).count() == 1
+
+ def test_does_not_expose_legacy_shared_tables(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=None)
+
+ with pytest.raises(ValueError, match="shared managed warehouse tables"):
+ _ensure(team)
+
+ assert not ExternalDataSource.objects.filter(team_id=team.id).exists()
+
+ def test_does_not_promote_a_user_source_with_the_reserved_prefix(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")
+ user_source = ExternalDataSource.objects.create(
+ team=team,
+ source_id="user-source",
+ connection_id="user-connection",
+ destination_id="user-destination",
+ status=ExternalDataSource.Status.RUNNING,
+ source_type="Postgres",
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ job_inputs={"password": "user-password"},
+ connection_metadata={"engine": "duckdb"},
+ )
+ user_schema = ExternalDataSchema.objects.create(
+ team=team,
+ source=user_source,
+ name="events_other_team",
+ should_sync=True,
+ )
+
+ managed_source = _ensure(team)
+
+ user_source.refresh_from_db()
+ user_schema.refresh_from_db()
+ assert managed_source.id != user_source.id
+ assert managed_source.is_system_managed is True
+ assert user_source.is_system_managed is False
+ assert user_source.job_inputs == {"password": "user-password"}
+ assert user_schema.source_id == user_source.id
+
+ def test_removes_existing_schemas_when_upgrading_a_root_managed_source(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")
+ 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,
+ )
+
+ managed_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()
+
+
+def _source_schema(table_name: str, source_schema: str = "posthog") -> SourceSchema:
+ return SourceSchema(
+ name=f"{source_schema}.{table_name}",
+ supports_incremental=False,
+ supports_append=False,
+ columns=[("uuid", "uuid", False), ("timestamp", "timestamp", True)],
+ source_schema=source_schema,
+ source_table_name=table_name,
+ )
+
+
+class TestReconcileManagedWarehouseTables:
+ def _setup(self) -> tuple[Organization, Team]:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, backfill_enabled=True, table_suffix="prod")
+ return org, team
+
+ def test_discovers_only_the_teams_tables_and_makes_them_queryable(self) -> None:
+ org, team = self._setup()
+ # The endpoint would also list other environments' tables; only this team's two are exposed.
+ 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}"),
+ ]
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ return_value=discovered,
+ ):
+ 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 source.access_method == ExternalDataSource.AccessMethod.DIRECT
+ assert set(
+ ExternalDataSchema.objects.filter(source_id=source.id, should_sync=True).values_list("name", flat=True)
+ ) == {
+ "posthog.events_prod",
+ "posthog.persons_prod",
+ "posthog_data_imports_prod.customers",
+ f"shadow_{team.id}_models.revenue",
+ f"team_{team.id}.future_table",
+ }
+ assert set(
+ DataWarehouseTable.raw_objects.filter(external_data_source_id=source.id, deleted=False).values_list(
+ "name", flat=True
+ )
+ ) == {
+ "posthog.events_prod",
+ "posthog.persons_prod",
+ "posthog_data_imports_prod.customers",
+ f"shadow_{team.id}_models.revenue",
+ f"team_{team.id}.future_table",
+ }
+
+ allowed_query = HogQLQueryExecutor(
+ query="SELECT uuid FROM posthog.events_prod",
+ team=team,
+ connection_id=str(source.id),
+ )
+ sql, _context = allowed_query.generate_clickhouse_sql()
+ assert "events_prod" in sql
+
+ metadata_cursor = MagicMock()
+ metadata_cursor.fetchone.return_value = ("ducklake", "Duckgres")
+ query_cursor = MagicMock()
+ query_cursor.fetchall.return_value = [("row-uuid",)]
+ column = MagicMock(type_code=25)
+ column.name = "uuid"
+ query_cursor.description = [column]
+ connection = MagicMock()
+ connection.execute.side_effect = [metadata_cursor, MagicMock()]
+ connection.cursor.return_value.__enter__.return_value = query_cursor
+ with patch("posthog.hogql.direct_sql.postgres_adapter.psycopg.connect") as connect:
+ connect.return_value.__enter__.return_value = connection
+ response = allowed_query.execute()
+
+ assert response.results == [("row-uuid",)]
+ 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)
+
+ forbidden_query = HogQLQueryExecutor(
+ query="SELECT uuid FROM posthog.events_other",
+ team=team,
+ connection_id=str(source.id),
+ )
+ with pytest.raises(QueryError):
+ forbidden_query.generate_clickhouse_sql()
+
+ assert get_direct_connection_source(team, str(source.id), require_pure_direct=True) == source
+
+ def test_reintrospects_to_pick_up_new_tables_in_project_schemas(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"), _source_schema("persons_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=[
+ _source_schema("events_prod"),
+ _source_schema("persons_prod"),
+ _source_schema("new_model", f"shadow_{team.id}_models"),
+ ],
+ ) as get_schemas:
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+ get_schemas.assert_called_once()
+ source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ assert ExternalDataSchema.objects.filter(source=source, name=f"shadow_{team.id}_models.new_model").exists()
+
+ def test_reintrospection_revives_a_dropped_and_recreated_table(self) -> None:
+ org, team = self._setup()
+ table = _source_schema("recreated", f"team_{team.id}")
+ events = _source_schema("events_prod")
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ return_value=[events, table],
+ ):
+ 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=[events],
+ ):
+ 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=[events, table],
+ ):
+ 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)
+ schema = ExternalDataSchema.objects.get(source=source, name=f"team_{team.id}.recreated")
+ assert schema.deleted is False
+ assert schema.table is not None
+ assert schema.table.deleted is False
+
+ def test_allowlist_follows_a_legacy_row_with_default_named_overrides(self) -> None:
+ # Team-2 shape: the Duckgres row grants posthog.events/persons via overrides that spell
+ # the derived default names. The local filter must mirror the row, not the suffix scheme.
+ org, team = self._setup()
+ with patch.object(
+ managed_warehouse,
+ "project_reader_namespaces",
+ return_value=(
+ {f"team_{team.id}", "posthog_data_imports_team_2", f"shadow_{team.id}_models"},
+ {("posthog", "events"), ("posthog", "persons")},
+ ),
+ ):
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ return_value=[_source_schema("events"), _source_schema("persons"), _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 set(ExternalDataSchema.objects.filter(source_id=source.id).values_list("name", flat=True)) == {
+ "posthog.events",
+ "posthog.persons",
+ }
+
+ def test_fails_closed_when_the_team_row_is_missing_or_disabled(self) -> None:
+ org, team = self._setup()
+ with patch.object(managed_warehouse, "project_reader_namespaces", return_value=None):
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"
+ ) as get_schemas:
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ get_schemas.assert_not_called()
+ source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ assert not ExternalDataSchema.objects.filter(source_id=source.id).exists()
+
+ def test_skips_quietly_when_the_warehouse_is_not_reachable(self) -> None:
+ # A provisioning warehouse fails introspection on every sweep; that must not raise.
+ org, team = self._setup()
+ 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)
+
+ source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ assert not ExternalDataSchema.objects.filter(source_id=source.id).exists()
+
+ def test_periodic_sweep_schedules_every_managed_project(self) -> None:
+ org, team = self._setup()
+
+ with patch(
+ "products.data_warehouse.backend.tasks.tasks.schedule_managed_warehouse_tables_reconcile"
+ ) as schedule:
+ reconcile_all_managed_warehouse_tables_task()
+
+ schedule.assert_called_once_with(team_id=team.id, organization_id=org.id)
+
+ def test_does_nothing_for_a_team_that_has_not_joined_the_warehouse(self) -> None:
+ # A non-member team polling status while the warehouse is ready must not get a connection.
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ DuckgresServer.objects.create(
+ organization=org, host=_CONNECTION["host"], port=5432, database="ducklake", username="root", password="pw"
+ )
+
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ assert not ExternalDataSource.objects.filter(team_id=team.id).exists()
+
+ def test_does_not_reconcile_legacy_shared_tables(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix=None)
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"
+ ) as get_schemas:
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ assert not ExternalDataSource.objects.filter(team_id=team.id).exists()
+ get_schemas.assert_not_called()
+
+ def test_rejects_a_team_membership_from_another_organization(self) -> None:
+ org_a = Organization.objects.create(name="Org A")
+ org_b = Organization.objects.create(name="Org B")
+ team_b = Team.objects.create(organization=org_b)
+ server_a = DuckgresServer.objects.create(
+ organization=org_a,
+ host="a.example.com",
+ port=5432,
+ database="ducklake",
+ username="root",
+ password="org-a-password",
+ )
+ server_b = DuckgresServer.objects.create(
+ organization=org_b,
+ host="b.example.com",
+ port=5432,
+ database="ducklake",
+ username="root",
+ password="org-b-password",
+ )
+ DuckgresServerTeam.objects.create(server=server_b, team=team_b, table_suffix="b")
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"
+ ) as get_schemas:
+ reconcile_managed_warehouse_tables(team_id=team_b.id, organization_id=org_a.id)
+
+ assert server_a.organization_id == org_a.id
+ assert not ExternalDataSource.objects.filter(team_id=team_b.id).exists()
+ get_schemas.assert_not_called()
+
+
+class TestManagedWarehouseLifecycle:
+ def _org_team_source(self) -> tuple[Organization, Team, ExternalDataSource, DuckgresServer]:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="prod")
+ source = ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=org.id)
+ return org, team, source, server
+
+ def test_update_root_password_only_rotates_the_internal_root_writer(self) -> None:
+ org, _team, source, server = self._org_team_source()
+
+ update_managed_warehouse_root_password(organization_id=org.id, password="rotated")
+
+ source.refresh_from_db()
+ server.refresh_from_db()
+ assert source.job_inputs["password"] == _PROJECT_READER_PASSWORD
+ assert server.password == "rotated"
+
+ def test_soft_delete_removes_sources_and_their_tables(self) -> None:
+ org, team, source, _server = self._org_team_source()
+ table = DataWarehouseTable.objects.create(
+ name="events_prod",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ team_id=team.id,
+ url_pattern=DIRECT_POSTGRES_URL_PATTERN,
+ external_data_source=source,
+ columns={},
+ options={},
+ )
+
+ soft_delete_managed_warehouse_sources(organization_id=org.id)
+
+ source.refresh_from_db()
+ table.refresh_from_db()
+ assert source.deleted is True
+ assert table.deleted is True
+ assert DuckgresServerTeam.objects.get(team=team).backfill_enabled is False
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"
+ ) as get_schemas:
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ source.refresh_from_db()
+ assert source.deleted is True
+ assert (
+ ExternalDataSource._base_manager.filter(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX).count()
+ == 1
+ )
+ get_schemas.assert_not_called()
+
+ def test_soft_delete_is_atomic_across_all_organization_sources(self) -> None:
+ org = Organization.objects.create(name="Org")
+ server = DuckgresServer.objects.create(
+ organization=org,
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username=_CONNECTION["username"],
+ password=_CONNECTION["password"],
+ )
+ team_a = Team.objects.create(organization=org)
+ team_b = Team.objects.create(organization=org)
+ DuckgresServerTeam.objects.create(server=server, team=team_a, table_suffix="a")
+ DuckgresServerTeam.objects.create(server=server, team=team_b, table_suffix="b")
+ source_a = _ensure(team_a)
+ source_b = _ensure(team_b)
+ original_save = ExternalDataSource.save
+
+ def fail_on_second_source(instance: ExternalDataSource, *args: object, **kwargs: object) -> None:
+ if instance.id == source_b.id:
+ raise RuntimeError("database write failed")
+ original_save(instance, *args, **kwargs)
+
+ with (
+ patch.object(ExternalDataSource, "save", new=fail_on_second_source),
+ pytest.raises(RuntimeError, match="database write failed"),
+ ):
+ soft_delete_managed_warehouse_sources(organization_id=org.id)
+
+ source_a.refresh_from_db()
+ source_b.refresh_from_db()
+ assert source_a.deleted is False
+ assert source_b.deleted is False
+
+
+@patch("products.data_warehouse.backend.facade.api.schedule_managed_warehouse_tables_reconcile")
+def test_ready_status_queues_table_discovery(mock_schedule: MagicMock) -> None:
+ organization_id = "a8fd15f0-1ed3-480b-a859-b10bba374acf"
+
+ managed_warehouse.ensure_direct_connection_tables(team_id=42, organization_id=organization_id)
+
+ mock_schedule.assert_called_once_with(team_id=42, organization_id=organization_id)
diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.py
index 4a1a09964d2c..22792f5d087b 100644
--- a/products/warehouse_sources/backend/models/external_data_source.py
+++ b/products/warehouse_sources/backend/models/external_data_source.py
@@ -14,6 +14,9 @@ from products.warehouse_sources.backend.types import DIRECT_ENGINE_BY_SOURCE_TYP
logger = structlog.get_logger(__name__)
+MANAGED_WAREHOUSE_SOURCE_PREFIX = "managed_warehouse"
+SYSTEM_MANAGED_SOURCE_PREFIXES = frozenset({MANAGED_WAREHOUSE_SOURCE_PREFIX})
+
class ExternalDataSourceManager(models.Manager):
def get_queryset(self):
@@ -112,6 +115,15 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
def is_direct_redshift(self) -> bool:
return self.is_direct_query and self.source_type == ExternalDataSourceType.REDSHIFT
+ @property
+ def is_system_managed(self) -> bool:
+ metadata = self.connection_metadata
+ return isinstance(metadata, dict) and metadata.get("system_managed") is True
+
+ @classmethod
+ def is_system_managed_prefix(cls, prefix: str | None) -> bool:
+ return isinstance(prefix, str) and prefix.strip() in SYSTEM_MANAGED_SOURCE_PREFIXES
+
@property
def direct_engine(self) -> str | None:
"""The direct-SQL engine for this source's type, or None if no engine maps to it.