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): authenticate managed warehouse sources with the org root credential (#74535)

Eric Duong96875f87a9b9
diff --git a/products/data_warehouse/backend/managed_warehouse_connection.py b/products/data_warehouse/backend/managed_warehouse_connection.py
index 97848792073c..d42aef9f6715 100644
--- a/products/data_warehouse/backend/managed_warehouse_connection.py
+++ b/products/data_warehouse/backend/managed_warehouse_connection.py
@@ -1,26 +1,27 @@
-"""Expose a managed Duckgres warehouse in the SQL editor as a read-only Postgres connection.
+"""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``. 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:
+``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 initially empty source row when a team
+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
- table in the project's event/person, data-import, team, and modeled-data namespaces.
+2. ``reconcile_managed_warehouse_tables`` runs once the warehouse is ready and records
+ every non-internal schema/table the root credential can see.
-This bypasses the user-facing create endpoint because the managed host is internal infrastructure
-and is not reachable for live schema validation during provisioning.
+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).
+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
@@ -33,7 +34,6 @@ 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 (
@@ -50,6 +50,16 @@ 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.
+INTERNAL_SCHEMAS = frozenset({"pg_catalog", "information_schema", "pg_toast", "system"})
+
+
+def internal_schemas() -> set[str]:
+ """The schemas the discover sweep must never register as warehouse tables."""
+ return set(INTERNAL_SCHEMAS)
+
def _managed_source_queryset(team_id: int) -> QuerySet[ExternalDataSource]:
return ExternalDataSource._base_manager.filter(
@@ -60,39 +70,32 @@ def _managed_source_queryset(team_id: int) -> QuerySet[ExternalDataSource]:
)
-def _source_config(server: DuckgresServer, *, username: str, password: str) -> dict[str, object]:
+def _source_config(server: DuckgresServer) -> dict[str, object]:
+ """Snapshot the server's org root credential into the source's job_inputs."""
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,
+ "user": server.username,
+ "password": server.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).
+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()
- config = _source_config(server, username=username, password=password)
+ 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") != "project_reader":
- # Old managed sources used the org root credential, so discard any catalog
- # entries discovered before Duckgres enforced the project boundary.
+ 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.
now = timezone.now()
DataWarehouseTable.raw_objects.filter(
team_id=team_id, external_data_source_id=existing.id, deleted=False
@@ -104,24 +107,22 @@ def _ensure_managed_source_locked(
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
+ if not existing.direct_query_enabled:
+ existing.direct_query_enabled = True
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"
+ or connection_metadata.get("credential_kind") != "org_root"
):
- existing.connection_metadata = {
+ migrated = {
**connection_metadata,
"engine": "duckdb",
"system_managed": True,
- "credential_kind": "project_reader",
- "reader_configured": reader_configured,
+ "credential_kind": "org_root",
}
- update_fields.append("connection_metadata")
- elif connection_metadata.get("reader_configured") is not reader_configured:
- existing.connection_metadata = {**connection_metadata, "reader_configured": reader_configured}
+ migrated.pop("reader_configured", None)
+ existing.connection_metadata = migrated
update_fields.append("connection_metadata")
if existing.deleted:
existing.deleted = False
@@ -143,119 +144,39 @@ def _ensure_managed_source_locked(
description=MANAGED_WAREHOUSE_SOURCE_DESCRIPTION,
access_method=ExternalDataSource.AccessMethod.DIRECT,
created_via=ExternalDataSource.CreatedVia.WEB,
- direct_query_enabled=reader_configured,
+ direct_query_enabled=True,
connection_metadata={
"engine": "duckdb",
"system_managed": True,
- "credential_kind": "project_reader",
- "reader_configured": reader_configured,
+ "credential_kind": "org_root",
},
)
-def _membership_table_suffix(*, team_id: int, organization_id: str | UUID) -> str:
- """The team's warehouse table suffix from its duckgres control-plane row.
-
- Raises RuntimeError when the control plane can't answer (callers treat that like the
- reader handshake being unavailable and retry on a later sweep) and ValueError when the
- team has no backfill-enabled row or sits on the legacy shared tables — neither can be
- exposed as a per-project query connection.
- """
- from posthog.ducklake import cp_teams, team_state # noqa: PLC0415 — keeps duckdb off this module's import path
-
- teams = cp_teams.list_org_teams(str(organization_id))
- if teams is None:
- raise RuntimeError("The managed warehouse control plane is unreachable")
- row = next((team for team in teams if team.team_id == team_id), None)
- if row is None or not row.backfill_enabled:
- raise ValueError("The team has not joined this managed warehouse")
- table_suffix = team_state.cp_table_suffix(row)
- if not table_suffix:
- raise ValueError("Legacy shared managed warehouse tables cannot be exposed as a query connection")
- return table_suffix
-
-
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."""
+ """Create or refresh the team's managed-warehouse query source on the org root credential."""
from posthog.ducklake.models import DuckgresServer # noqa: PLC0415
- table_suffix = _membership_table_suffix(team_id=team_id, organization_id=organization_id)
-
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)
-
- 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():
- 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)
- 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
+ return _ensure_managed_source_locked(team_id=team_id, server=server)
def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:
- """Discover and register only this team's managed-warehouse tables."""
+ """Discover and register the org-wide managed-warehouse catalog for this team's source."""
from posthog.ducklake.models import DuckgresServer # noqa: PLC0415
+ 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, 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)
+ except (DuckgresServer.DoesNotExist, Team.DoesNotExist):
return
with transaction.atomic():
@@ -271,14 +192,7 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | U
source_config = dict(source.job_inputs or {})
source_api_version = source.api_version
- # 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
+ excluded_schemas = internal_schemas()
source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
config = source_impl.parse_config(source_config)
@@ -291,12 +205,7 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | U
# 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
- ]
+ source_schemas = [schema for schema in discovered if (schema.source_schema or "") not in excluded_schemas]
if not source_schemas:
return
@@ -346,7 +255,12 @@ def _managed_sources_for_org(organization_id: str | UUID) -> QuerySet[ExternalDa
def update_managed_warehouse_root_password(*, organization_id: str | UUID, password: str) -> None:
- """Refresh the internal root writer without changing project reader credentials."""
+ """Rotate the root password on the server row and every managed source of the org.
+
+ 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.
+ """
from posthog.ducklake.models import DuckgresServer # noqa: PLC0415
with transaction.atomic():
@@ -354,6 +268,12 @@ def update_managed_warehouse_root_password(*, organization_id: str | UUID, passw
server.password = password
server.save(update_fields=["password", "updated_at"])
+ config = _source_config(server)
+ for source in _managed_sources_for_org(organization_id).select_for_update().order_by("team_id"):
+ if source.job_inputs != config:
+ source.job_inputs = config
+ source.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.
diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.py
index 639e9cb37494..4a11b5225df7 100644
--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py
+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py
@@ -210,80 +210,6 @@ def _row_team_id(row: dict) -> int | None:
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 _block_if_pending_deletion(organization_id: UUID | str) -> Response | None:
"""Refuse warehouse-creating calls for an organization whose deletion is underway.
@@ -347,7 +273,7 @@ def provision(
if status.is_success(resp.status_code) and isinstance(resp.data, dict):
_persist_duckgres_server(organization_id, database_name, resp.data)
# Complete the row BEFORE registering the team: registration kicks off the
- # SQL-editor reader handshake, whose namespace grants derive from this row.
+ # SQL-editor query-source setup and discovery against this row's warehouse.
_complete_provisioning_team_row(organization_id, team_id, schema_name, require_enabled=require_enabled)
_register_provisioning_team(organization_id, team_id)
# The bucket is internal infra detail, persisted above and consumed by the
@@ -362,8 +288,8 @@ def _complete_provisioning_team_row(
) -> None:
"""Pin the first team's legacy table names onto the row duckgres just created.
- The provision body cannot carry them, and without them the team's SQL-editor reader is
- granted only the derived schemas no data lands in yet (see onboard_team). Best-effort:
+ The provision body cannot carry them, so without this step the row describes the derived
+ layout no data lands in yet (see onboard_team). Best-effort:
the warehouse is already provisioned, so a transient failure must not fail the provision —
re-running onboarding completes the row later.
"""
@@ -427,11 +353,11 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int) -> No
def _ensure_direct_source(team_id: int, organization_id: UUID | str) -> None:
- """Best-effort: register the org's managed warehouse as the team's restricted query connection.
+ """Best-effort: register the org's managed warehouse as the team's 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. A failure here must never block onboarding.
+ ExternalDataSource pointed at the org server and authenticated with its org root
+ credential. A failure here must never block onboarding.
"""
try:
# Keep the data_warehouse/warehouse_sources stack off this adapter's import path.
@@ -657,9 +583,9 @@ def onboard_team(
else:
# Pin the legacy table names the duckling DAG writes today (posthog.events_<suffix>,
# posthog_data_imports_<suffix>): the suffix for a newly onboarded team IS its schema
- # name. A row without them describes the derived layout no data lands in yet, which
- # grants the project's SQL-editor reader nothing (the EU placeholder-row bug). Drop
- # this once the duckling DAG writes the derived <schema_name>.events layout for real.
+ # name. A row without them describes the derived layout no data lands in yet (the EU
+ # placeholder-row bug). Drop this once the duckling DAG writes the derived
+ # <schema_name>.events layout for real.
legacy = _legacy_table_fields(schema_name)
resp = create_team(
organization_id,
diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.py
index 35e28d042ef2..14cb954b626d 100644
--- a/products/data_warehouse/backend/tasks/tasks.py
+++ b/products/data_warehouse/backend/tasks/tasks.py
@@ -43,9 +43,9 @@ 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.
+# 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
MANAGED_WAREHOUSE_RECONCILE_INTERVAL_SECONDS = 60
@@ -102,7 +102,7 @@ def schedule_soft_delete_managed_warehouse_sources(*, organization_id: str | UUI
def reconcile_all_managed_warehouse_tables_task() -> None:
# Deferred: ducklake pulls duckdb in via common, and that must not load while Celery
# imports task modules — keep it off this module's import path.
- from posthog.ducklake import cp_teams, team_state # noqa: PLC0415
+ from posthog.ducklake import cp_teams # noqa: PLC0415
rows = cp_teams.list_enabled_backfills()
if rows is None:
@@ -111,9 +111,6 @@ def reconcile_all_managed_warehouse_tables_task() -> None:
logger.warning("Managed warehouse reconcile sweep skipped: control plane unreachable")
return
for row in rows:
- if team_state.cp_table_suffix(row) is None:
- # Legacy shared tables can't be exposed as a per-project query connection.
- continue
schedule_managed_warehouse_tables_reconcile(team_id=row.team_id, organization_id=row.organization_id)
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 d76db23e926f..74a5785e060f 100644
--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py
+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py
@@ -2,7 +2,7 @@ from types import SimpleNamespace
from uuid import uuid4
import pytest
-from unittest.mock import MagicMock, call, patch
+from unittest.mock import MagicMock, patch
from django.test import override_settings
@@ -32,153 +32,6 @@ def _onboarding_side_effects():
cp_teams.clear_cache()
-@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()
@@ -656,8 +509,8 @@ def test_onboard_team_creates_duckgres_row_with_legacy_names(
# duckgres team row created via the org-teams upsert WITH the legacy table names the
# duckling DAG actually writes today (posthog.events_<suffix> + posthog_data_imports_<suffix>).
- # A row without them grants the project reader only nonexistent derived schemas — the
- # empty-SQL-editor-sidebar bug the EU placeholder rows hit.
+ # A row without them describes the derived layout no data lands in yet — the EU
+ # placeholder-row bug.
assert mock_request.call_args_list[0].args == ("GET", org.id, "/teams")
method, org_id, path = mock_request.call_args_list[1].args
assert (method, org_id, path) == ("POST", org.id, "/teams")
diff --git a/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py b/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py
index 8f76af39a135..50610cdf1b2f 100644
--- a/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py
+++ b/products/data_warehouse/backend/tests/test_managed_warehouse_connection.py
@@ -4,7 +4,6 @@ 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 import cp_teams
@@ -15,6 +14,7 @@ from products.data_warehouse.backend.direct_postgres import DIRECT_POSTGRES_URL_
from products.data_warehouse.backend.managed_warehouse_connection import (
MANAGED_WAREHOUSE_SOURCE_PREFIX,
ensure_managed_warehouse_direct_source,
+ internal_schemas,
reconcile_managed_warehouse_tables,
soft_delete_managed_warehouse_sources,
update_managed_warehouse_root_password,
@@ -43,34 +43,10 @@ _CONNECTION: _Connection = {
"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
-
# Per-test control-plane membership rows, keyed by org id. The CP is the read source for
-# membership now, so tests register rows here instead of creating Django rows.
+# 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.
_MEMBERSHIPS: dict[str, list[dict]] = {}
@@ -113,20 +89,16 @@ def _ensure(team: Team) -> ExternalDataSource:
return ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=team.organization_id)
+def _create_server(org: Organization, **overrides: object) -> DuckgresServer:
+ return DuckgresServer.objects.create(organization=org, **{**_CONNECTION, **overrides})
+
+
@pytest.mark.django_db
class TestEnsureManagedWarehouseDirectSource:
- def test_creates_a_restricted_postgres_query_source_from_the_server(self) -> None:
+ 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)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
- _add_membership(team)
+ _create_server(org)
source = _ensure(team)
@@ -136,25 +108,17 @@ class TestEnsureManagedWarehouseDirectSource:
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.
+ # 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"] == f"posthog_team_{team.id}"
- assert source.job_inputs["password"] == _PROJECT_READER_PASSWORD
- assert source.connection_metadata["credential_kind"] == "project_reader"
+ 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)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
- _add_membership(team)
+ _create_server(org)
first = _ensure(team)
second = _ensure(team)
@@ -162,107 +126,87 @@ class TestEnsureManagedWarehouseDirectSource:
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:
+ 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.
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
- _add_membership(team)
- 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}
+ _create_server(org)
+ _add_membership(team, legacy_shared=True)
- with patch.object(managed_warehouse, "configure_project_reader", side_effect=configure_project_reader):
- source = _ensure(team)
+ 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
+ assert source.connection_metadata["credential_kind"] == "org_root"
- def test_does_not_expose_legacy_shared_tables(self) -> None:
+ 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.
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
- _add_membership(team, legacy_shared=True)
+ _create_server(org)
- with pytest.raises(ValueError, match="shared managed warehouse tables"):
- _ensure(team)
+ source = _ensure(team)
- assert not ExternalDataSource.objects.filter(team_id=team.id).exists()
+ assert source.direct_query_enabled is True
+ assert isinstance(source.connection_metadata, dict)
+ assert source.connection_metadata["credential_kind"] == "org_root"
- def test_does_not_promote_a_user_source_with_the_reserved_prefix(self) -> None:
+ def test_refreshes_a_project_reader_source_onto_the_root_credential(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
- _add_membership(team)
- user_source = ExternalDataSource.objects.create(
+ _create_server(org)
+ source = ExternalDataSource.objects.create(
team=team,
- source_id="user-source",
- connection_id="user-connection",
- destination_id="user-destination",
+ 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": "user-password"},
- connection_metadata={"engine": "duckdb"},
+ 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,
+ },
)
- user_schema = ExternalDataSchema.objects.create(
+ team_schema = ExternalDataSchema.objects.create(
team=team,
- source=user_source,
- name="events_other_team",
+ source=source,
+ name="posthog.events_prod",
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
+ 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:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
- _add_membership(team)
+ _create_server(org)
source = ExternalDataSource.objects.create(
team=team,
source_id="managed-source",
@@ -305,20 +249,15 @@ class TestReconcileManagedWarehouseTables:
def _setup(self) -> tuple[Organization, Team]:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
+ _create_server(org)
_add_membership(team)
return org, team
- def test_discovers_only_the_teams_tables_and_makes_them_queryable(self) -> None:
+ def test_discovers_the_whole_org_catalog_and_makes_it_queryable(self) -> None:
org, team = self._setup()
- # The endpoint would also list other environments' tables; only this team's two are exposed.
+ 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.
discovered = [
_source_schema("events_prod"),
_source_schema("persons_prod"),
@@ -326,6 +265,9 @@ class TestReconcileManagedWarehouseTables:
_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"),
]
with patch(
@@ -341,9 +283,11 @@ 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",
}
assert set(
DataWarehouseTable.raw_objects.filter(external_data_source_id=source.id, deleted=False).values_list(
@@ -352,9 +296,11 @@ 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(
@@ -386,17 +332,33 @@ class TestReconcileManagedWarehouseTables:
]
query_cursor.execute.assert_called_once_with(sql, None)
- forbidden_query = HogQLQueryExecutor(
- query="SELECT uuid FROM posthog.events_other",
+ # 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),
)
- with pytest.raises(QueryError):
- forbidden_query.generate_clickhouse_sql()
+ 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
- def test_reintrospects_to_pick_up_new_tables_in_project_schemas(self) -> None:
+ def test_discovers_only_internal_schemas_registers_nothing(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("pg_stat_activity", "pg_catalog"),
+ _source_schema("tables", "information_schema"),
+ ],
+ ):
+ 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_reintrospects_to_pick_up_new_tables(self) -> None:
org, team = self._setup()
with patch(
"products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
@@ -446,42 +408,6 @@ class TestReconcileManagedWarehouseTables:
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()
@@ -497,8 +423,15 @@ class TestReconcileManagedWarehouseTables:
def test_periodic_sweep_schedules_every_managed_project(self) -> None:
org, team = self._setup()
all_rows = _MEMBERSHIPS[str(org.id)] + [
- # Legacy shared-table membership: nothing to expose, must be skipped.
- {"org_id": str(org.id), "team_id": team.id + 1, "schema_name": "team_x", "events_table_name": "events"}
+ # Legacy shared-table membership: root-backed sources support it, so the
+ # sweep schedules it like any other row.
+ {
+ "org_id": str(org.id),
+ "team_id": team.id + 1,
+ "schema_name": "team_x",
+ "backfill_enabled": True,
+ "events_table_name": "events",
+ }
]
with (
@@ -509,7 +442,8 @@ class TestReconcileManagedWarehouseTables:
):
reconcile_all_managed_warehouse_tables_task()
- schedule.assert_called_once_with(team_id=team.id, organization_id=str(org.id))
+ assert schedule.call_count == 2
+ assert {call.kwargs["team_id"] for call in schedule.call_args_list} == {team.id, team.id + 1}
def test_periodic_sweep_skips_run_when_control_plane_unreachable(self) -> None:
with (
@@ -522,59 +456,38 @@ class TestReconcileManagedWarehouseTables:
schedule.assert_not_called()
- 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.
+ 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)
- DuckgresServer.objects.create(
- organization=org, host=_CONNECTION["host"], port=5432, database="ducklake", username="root", password="pw"
- )
+ _create_server(org)
reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
- assert not ExternalDataSource.objects.filter(team_id=team.id).exists()
+ assert ExternalDataSource.objects.filter(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX).exists()
- def test_does_not_reconcile_legacy_shared_tables(self) -> None:
- org = Organization.objects.create(name="Org")
- team = Team.objects.create(organization=org)
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
+ def test_reconciles_for_a_legacy_shared_tables_team(self) -> None:
+ org, team = self._setup()
+ _clear_memberships()
_add_membership(team, legacy_shared=True)
with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas"
+ "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)
- assert not ExternalDataSource.objects.filter(team_id=team.id).exists()
- get_schemas.assert_not_called()
+ get_schemas.assert_called_once()
+ source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ assert ExternalDataSchema.objects.filter(source_id=source.id, name="posthog.events").exists()
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",
- )
- DuckgresServer.objects.create(
- organization=org_b,
- host="b.example.com",
- port=5432,
- database="ducklake",
- username="root",
- password="org-b-password",
- )
+ _create_server(org_a, host="a.example.com", password="org-a-password")
+ _create_server(org_b, host="b.example.com", password="org-b-password")
_add_membership(team_b, "b")
with patch(
@@ -582,7 +495,6 @@ class TestReconcileManagedWarehouseTables:
) 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()
@@ -592,27 +504,42 @@ 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"],
- )
- _add_membership(team)
+ server = _create_server(org)
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:
+ def test_update_root_password_rotates_the_server_and_every_managed_source(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)
+
+ update_managed_warehouse_root_password(organization_id=org.id, password="rotated")
+
+ source.refresh_from_db()
+ other_source.refresh_from_db()
+ server.refresh_from_db()
+ assert isinstance(source.job_inputs, dict)
+ assert isinstance(other_source.job_inputs, dict)
+ assert source.job_inputs["password"] == "rotated"
+ assert other_source.job_inputs["password"] == "rotated"
+ assert server.password == "rotated"
+
+ def test_update_root_password_skips_soft_deleted_sources(self) -> None:
org, _team, source, server = self._org_team_source()
+ soft_delete_managed_warehouse_sources(organization_id=org.id)
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"
+ 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"
def test_soft_delete_removes_sources_and_their_tables(self) -> None:
org, team, source, _server = self._org_team_source()
@@ -627,8 +554,6 @@ class TestManagedWarehouseLifecycle:
)
soft_delete_managed_warehouse_sources(organization_id=org.id)
- # Deprovision removes the org's team rows from the control plane.
- _clear_memberships()
source.refresh_from_db()
table.refresh_from_db()
@@ -650,18 +575,9 @@ class TestManagedWarehouseLifecycle:
def test_soft_delete_is_atomic_across_all_organization_sources(self) -> None:
org = Organization.objects.create(name="Org")
- DuckgresServer.objects.create(
- organization=org,
- host=_CONNECTION["host"],
- port=_CONNECTION["port"],
- database=_CONNECTION["database"],
- username=_CONNECTION["username"],
- password=_CONNECTION["password"],
- )
+ _create_server(org)
team_a = Team.objects.create(organization=org)
team_b = Team.objects.create(organization=org)
- _add_membership(team_a, "a")
- _add_membership(team_b, "b")
source_a = _ensure(team_a)
source_b = _ensure(team_b)
original_save = ExternalDataSource.save
@@ -683,6 +599,11 @@ class TestManagedWarehouseLifecycle:
assert source_b.deleted is False
+class TestInternalSchemas:
+ def test_excludes_only_engine_internals(self) -> None:
+ assert internal_schemas() == {"pg_catalog", "information_schema", "pg_toast", "system"}
+
+
@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"