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(managed-warehouse): mint SQL editor credentials at runtime (#83784)

Benjamin Knofe-Videreaa1d65b05fb
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 361db006721f..57bcc8bb3c2c 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -824,6 +824,7 @@ rules:
|CIMDVerificationToken
|IdentityProviderConfig
|LegalDocument
+ |ManagedWarehouseSourceLifecycle
|OrganizationMembership
|OrganizationDomain
|OrganizationIntegration
@@ -895,6 +896,7 @@ rules:
|CIMDVerificationToken
|IdentityProviderConfig
|LegalDocument
+ |ManagedWarehouseSourceLifecycle
|OrganizationMembership
|OrganizationDomain
|OrganizationIntegration
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.md
index 15bb0cc602ab..c83bcb47bb5f 100644
--- a/docs/internal/managed-warehouse-sql-editor.md
+++ b/docs/internal/managed-warehouse-sql-editor.md
@@ -1,22 +1,38 @@
# Managed warehouse connections in the SQL editor
-The `managed-warehouse-sql-editor` feature flag switches which managed warehouse connection appears for each project:
+The `managed-warehouse-sql-editor` feature flag controls which managed warehouse connection appears in the database chooser. With the flag enabled, PostHog prefers a secretless `duckgres_service` source and presents it as `PostHog (Managed warehouse)`. An existing configured `project_reader` source remains a temporary built-in compatibility path when no dynamic source exists. With the flag disabled, a grandfathered static organization-login source remains an ordinary external Duckgres connection.
-- When disabled, which is the default, PostHog keeps the source as an ordinary external Duckgres connection. External-source access controls apply, the option uses DuckDB branding and source settings, and queries use the existing PostgreSQL direct adapter.
-- When enabled, PostHog hides the external representation from the connection chooser. If the reserved source contains a configured Duckgres `project_reader` credential, it appears as `PostHog (Managed warehouse)` below `PostHog (ClickHouse)`. Every project member can use it without external-source access controls.
+`MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED` is a deployment-wide operational gate that defaults to false. While it is false, provision and project onboarding preserve the existing static `org_root` source behavior and do not create dynamic sources. While it is true, new source setup creates `duckgres_service` sources. These rows persist no host, username, password, or credential ID. They persist only the non-secret lifecycle generation that created them.
-Enabling the flag without a ready project reader shows neither representation. The flag only controls chooser visibility. It does not change a source row's adapter or access policy, revoke saved connection IDs, or create, rotate, or delete credentials or catalog metadata.
+Existing active `project_reader` and static organization-login sources remain byte-for-byte unchanged. Turning the operational gate off leaves a same-generation dynamic source byte-for-byte unchanged and never copies the stored root secret into that row. After a failed cleanup, a genuine reprovision keeps an existing dynamic source but advances its lifecycle marker and makes readers from the old generation unavailable. Without a dynamic source, gate-off reprovision makes stale readers unavailable before creating the static source. Dynamic-mode reconciliation never creates or revives sources. While the operational gate is off, reconciliation may complete generation-fenced static source setup after a successful provision, but it does not revive an unfenced legacy tombstone.
-Duckgres enforces the reader's read-only, project-scoped query policy in built-in mode. PostHog requires the reserved source to be enabled, marked as a configured `project_reader`, and use the expected `posthog_team_<team_id>` login. Sources backed by the organization login and pending or malformed readers are not eligible for built-in mode. This integration assumes provisioning has already created the project reader.
+Dynamic raw queries use the native Duckgres pgwire adapter. At physical connection acquisition, PostHog mints a short-lived organization-root-shaped service credential for a principal containing the project ID and stable PostHog user ID. Email addresses are never used. Schema discovery uses a distinct project-scoped system principal, so background work never impersonates an interactive user. Credentials are cached briefly by organization, principal, and lifecycle generation, with per-key singleflight, early independent replacement, bounded failure backoff, and no shared credential rotation. A rapid deprovision and reprovision therefore cannot reuse a credential from the old generation. An unexpired cached credential can bridge a temporary control-plane outage; an expired credential fails closed. The connection must include `sslmode=require`, and there is no stored-root fallback.
-A ready project-reader source always uses the built-in policy, even while hidden. Raw queries use a native pgwire adapter. The adapter uses the exact reader connection stored on the resolved source, sends one SQL statement unchanged, and does not build a HogQL database or load the third-party PostgreSQL source stack. It never falls back to the organization's stored login. Duckgres authorizes `project_reader` statements through its PostgreSQL query gateway, so raw statements must use PostgreSQL-compatible syntax. Queries that return more than 50,000 rows fail and ask the user to add a `LIMIT` clause. Non-raw queries continue through the PostgreSQL and HogQL path with the same source credential.
+Existing project readers retain their stored, project-scoped credential and native-adapter behavior. Existing static organization-login sources retain the PostgreSQL adapter and external-source access controls. Saved connection IDs continue to resolve according to the source's own credential mode even when that mode is not the chooser's preferred entry.
-Hostname resolution is bounded to 15 seconds before libpq applies its per-attempt 15-second connection timeout. Canceling an asynchronous query signals the active pgwire connection instead of only revoking its Celery task.
+The native adapter sends one PostgreSQL-compatible statement unchanged, supports asynchronous cancellation, applies the existing connection deadline and statement timeout, and rejects results above 50,000 rows. Non-raw project-reader and static-source queries continue through their existing PostgreSQL/HogQL path; the PostgreSQL adapter is unchanged.
-A legacy source backed by the stored server login always remains an external connection, even while hidden from the chooser. It stays visible in external-source management, keeps external-source and table access controls, and uses the existing PostgreSQL direct adapter.
+Reconciliation treats dynamic, project-reader, and static sources as independent catalogs and introspects each with its own credential mode. A failure in one source does not block the others. Dynamic discovery requires TLS and uses its system principal. Reconciliation runs when warehouse status is read, coalesced to once a minute, and in a twice-hourly periodic sweep. Dropped and recreated tables revive their existing catalog entries.
-PostHog reconciles the legacy connection and a ready reader into separate table catalogs. A failure or missing credential in one mode does not block the other. Reconciliation runs when warehouse status is read, coalesced to once a minute, and in a twice-hourly periodic sweep. Duckgres limits reader discovery to the project's allowed namespaces. The sweep makes newly created tables visible without requiring a visit to Data ops. Each source reconcile opens a warehouse session, so it is not more frequent. If a physical table is dropped and recreated with the same name, reconciliation revives its existing catalog entry.
+An organization-scoped generation fence orders local source lifecycle work around remote provision and deprovision calls. Successful explicit provision or onboarding owns source creation. A stale provision completion cannot revive a source after a later deprovision, and an old cleanup retry cannot delete a genuinely reprovisioned source. Reconciliation also requires the same active generation before and after remote schema discovery.
-The configured source row is the local readiness marker for built-in mode. Query and picker paths use its encrypted reader connection directly. If the reader no longer exists in Duckgres, connection attempts fail without trying a broader credential.
+Deprovision captures the active generation before the control-plane request and deactivates only that generation. A direct 404 is authoritative absence. If the request times out or returns 409, PostHog reads warehouse status. It converges local cleanup only when the warehouse is `deleting`, `deleted`, or absent. A ready warehouse remains active. Failed local dynamic source setup schedules a generation-fenced v2 retry; retries from an inactive or newer generation do nothing. With the operational gate off, periodic reconciliation repairs failed static source setup against the active generation.
-Deploy this code to every web and Celery worker before provisioning project-reader rows. Older workers can mistake the newest reserved row for the legacy source and replace its credentials. Keep the feature flag disabled until a ready reader exists for the project.
+## Deployment and rollback
+
+1. Deploy this code to every web and Celery worker with `MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=false`.
+2. Confirm provision and onboarding still create or maintain static `org_root` sources.
+3. Drain old web and Celery workers. Also drain queued, reserved, scheduled, and retry messages for `products.data_warehouse.backend.tasks.soft_delete_managed_warehouse_sources`.
+4. Enable `MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=true` on web and Celery together. Only then do producers emit the generation-aware v2 cleanup and source-recovery tasks.
+
+The legacy cleanup task keeps its one-argument wire signature so a new worker can consume messages queued by an old worker. While the gate is off, new producers emit only that legacy task. The handler takes the organization lock: it cleans the current inactive generation, does nothing for an active lifecycle, and uses unconditional legacy behavior only when no lifecycle row exists. While the gate is on, the legacy handler does nothing and producers emit only versioned generation-aware tasks. This prevents either worker version from receiving a payload shape it cannot execute during the drain.
+
+Before enablement, rollback is a normal code rollback. After enablement, disable the gate to stop creating dynamic sources, but keep the new binaries running so existing dynamic sources remain queryable. Do not deploy old binaries until no live `duckgres_service` sources remain or an explicit conversion process has replaced them with static sources.
+
+Dynamic source creation while the gate is enabled, query authentication, schema discovery, and generation-fenced deprovision cleanup do not read `DuckgresServer`. The model remains for gate-off static source creation, persistence of the one-time provision response, and rotating root passwords on grandfathered static sources.
+
+## Failure recovery
+
+If source setup fails after successful provision or onboarding, the versioned retry task uses the original team, organization, and generation. It is safe to retry. If the warehouse was deprovisioned or reprovisioned, the generation check turns the task into a no-op.
+
+If deprovision reports that the control plane accepted deletion but local SQL connection state could not be updated, retry deprovision. PostHog checks authoritative status before changing local state. If source cleanup fails after local deactivation, the versioned cleanup task retries with the exact inactive generation.
diff --git a/posthog/hogql/direct_sql/__init__.py b/posthog/hogql/direct_sql/__init__.py
index 93a65a3c07b3..0701c4403e36 100644
--- a/posthog/hogql/direct_sql/__init__.py
+++ b/posthog/hogql/direct_sql/__init__.py
@@ -1,4 +1,9 @@
-from posthog.hogql.direct_sql.adapter import DirectQueryRequest, DirectQueryResult, DirectSQLAdapter
+from posthog.hogql.direct_sql.adapter import (
+ DirectQueryPrincipal,
+ DirectQueryRequest,
+ DirectQueryResult,
+ DirectSQLAdapter,
+)
from posthog.hogql.direct_sql.capability import direct_capable_source_types, is_direct_capable
from posthog.hogql.direct_sql.clickhouse_adapter import ClickHouseAdapter
from posthog.hogql.direct_sql.duckgres_adapter import DuckgresRawAdapter
@@ -35,6 +40,7 @@ def get_raw_adapter_for_source(source: ExternalDataSource) -> DirectSQLAdapter |
__all__ = [
"DirectQueryRequest",
+ "DirectQueryPrincipal",
"DirectQueryResult",
"DirectSQLAdapter",
"ClickHouseAdapter",
diff --git a/posthog/hogql/direct_sql/adapter.py b/posthog/hogql/direct_sql/adapter.py
index 24fa96d66b4a..bd25f0850c7d 100644
--- a/posthog/hogql/direct_sql/adapter.py
+++ b/posthog/hogql/direct_sql/adapter.py
@@ -1,4 +1,5 @@
import dataclasses
+from dataclasses import field
from typing import TYPE_CHECKING, Any, Protocol
from posthog.hogql.constants import HogQLDialect, HogQLGlobalSettings
@@ -9,6 +10,13 @@ if TYPE_CHECKING:
from products.warehouse_sources.backend.facade.models import ExternalDataSource
+from posthog.dataclasses import frozen
+
+
+@frozen
+class DirectQueryPrincipal:
+ value: str
+
@dataclasses.dataclass(frozen=False)
class DirectQueryRequest:
@@ -20,6 +28,7 @@ class DirectQueryRequest:
timings: HogQLTimings
query_type: str
debug: bool
+ principal: DirectQueryPrincipal | None = field(default=None)
cancellation_token: str | None = None
diff --git a/posthog/hogql/direct_sql/duckgres_adapter.py b/posthog/hogql/direct_sql/duckgres_adapter.py
index e3f7498b3a50..53ddb2fda413 100644
--- a/posthog/hogql/direct_sql/duckgres_adapter.py
+++ b/posthog/hogql/direct_sql/duckgres_adapter.py
@@ -35,6 +35,10 @@ from posthog.dataclasses import frozen
from posthog.direct_query_cancellation import is_direct_query_cancellation_requested
from posthog.psycopg_helpers import resolve_psycopg_hostaddr_with_timeout
+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseSourceAuth, ServiceCredentialUnavailable
+from products.managed_warehouse.backend.facade.sql_editor import resolve_managed_warehouse_postgres_connection
+from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
+
if TYPE_CHECKING:
from psycopg.pq.abc import PGresult
@@ -66,7 +70,7 @@ logger = structlog.get_logger(__name__)
@frozen
-class _DuckgresProjectReaderConfig:
+class _DuckgresConnectionConfig:
host: str
port: int
database: str
@@ -245,7 +249,7 @@ def _wait_for_duckgres_connection(
def _connect_duckgres_address(
- source_config: _DuckgresProjectReaderConfig,
+ source_config: _DuckgresConnectionConfig,
hostaddr: str | None,
deadline: float,
abort_check: Callable[[], None],
@@ -278,7 +282,7 @@ def _connect_duckgres_address(
def _connect_duckgres_project_reader(
- source_config: _DuckgresProjectReaderConfig,
+ source_config: _DuckgresConnectionConfig,
team_id: int,
cancellation_token: str | None,
) -> psycopg.Connection[tuple[object, ...]]:
@@ -335,9 +339,7 @@ class DuckgresRawAdapter:
engine = "duckgres"
dialect: HogQLDialect | None = None
- def validate_source_config(
- self, source: ExternalDataSource, team: Team
- ) -> tuple[None, _DuckgresProjectReaderConfig]:
+ def validate_source_config(self, source: ExternalDataSource, team: Team) -> tuple[None, _DuckgresConnectionConfig]:
if source.team_id != team.pk or not source.is_managed_warehouse_ready:
raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)
@@ -372,7 +374,7 @@ class DuckgresRawAdapter:
if not 1 <= port <= 65535:
raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)
- return None, _DuckgresProjectReaderConfig(
+ return None, _DuckgresConnectionConfig(
host=host,
port=port,
database=database,
@@ -383,6 +385,39 @@ class DuckgresRawAdapter:
def prepare_raw_sql(self, sql: str) -> str:
return ensure_single_direct_statement(sql)
+ def _resolve_source_config(self, request: DirectQueryRequest) -> _DuckgresConnectionConfig:
+ metadata = request.source.connection_metadata
+ credential_kind = metadata.get("credential_kind") if isinstance(metadata, dict) else None
+ lifecycle_generation = metadata.get("lifecycle_generation") if isinstance(metadata, dict) else None
+ if credential_kind != MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND:
+ return self.validate_source_config(request.source, request.team)[1]
+ if not request.source.is_dynamic_managed_warehouse or request.principal is None:
+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)
+
+ try:
+ connection = resolve_managed_warehouse_postgres_connection(
+ source_auth=ManagedWarehouseSourceAuth(
+ prefix=request.source.prefix,
+ system_managed=request.source.is_system_managed,
+ credential_kind=credential_kind,
+ lifecycle_generation=(lifecycle_generation if isinstance(lifecycle_generation, int) else None),
+ ),
+ organization_id=request.team.organization_id,
+ team_id=request.team.pk,
+ principal=request.principal.value,
+ )
+ except ServiceCredentialUnavailable as error:
+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR) from error
+ if connection is None or connection.sslmode != "require":
+ raise ExposedHogQLError(MANAGED_WAREHOUSE_UNAVAILABLE_ERROR)
+ return _DuckgresConnectionConfig(
+ host=connection.host,
+ port=connection.port,
+ database=connection.database,
+ user=connection.username,
+ password=connection.password,
+ )
+
def execute(self, request: DirectQueryRequest) -> DirectQueryResult:
statement_timeout_seconds = max(
request.settings.max_execution_time or DIRECT_DUCKGRES_DEFAULT_STATEMENT_TIMEOUT_SECONDS, 1
@@ -396,7 +431,7 @@ class DuckgresRawAdapter:
try:
with request.timings.measure("duckgres_execute"), observe_direct_query("duckgres"):
with request.timings.measure("duckgres_source_validation"):
- _, source_config = self.validate_source_config(request.source, request.team)
+ source_config = self._resolve_source_config(request)
try:
with request.timings.measure("duckgres_connect", emit_span=True):
connection_context = _connect_duckgres_project_reader(
diff --git a/posthog/hogql/query.py b/posthog/hogql/query.py
index d12c445b3792..84289551177a 100644
--- a/posthog/hogql/query.py
+++ b/posthog/hogql/query.py
@@ -41,6 +41,7 @@ from posthog.hogql.direct_connection import (
raw_query_denied_by_table_access,
)
from posthog.hogql.direct_sql import (
+ DirectQueryPrincipal,
DirectQueryRequest,
DirectSQLAdapter,
ensure_single_direct_statement,
@@ -494,6 +495,11 @@ class HogQLQueryExecutor:
timings=self.timings,
query_type=self.query_type,
debug=bool(self.debug),
+ principal=(
+ DirectQueryPrincipal(value=f"posthog:sql-editor:team:{self.team.pk}:user:{self.user.pk}")
+ if isinstance(self.user, User) and self.user.pk is not None
+ else None
+ ),
cancellation_token=cancellation_token,
)
)
diff --git a/posthog/hogql/test/test_direct_connection.py b/posthog/hogql/test/test_direct_connection.py
index 138b54bf1bed..c923b4d6b06a 100644
--- a/posthog/hogql/test/test_direct_connection.py
+++ b/posthog/hogql/test/test_direct_connection.py
@@ -106,6 +106,8 @@ class TestGetDirectConnectionSource(APIBaseTest):
[
("reader_flag_off", "project_reader", False, True),
("reader_flag_on", "project_reader", True, True),
+ ("dynamic_flag_off", "duckgres_service", False, True),
+ ("dynamic_flag_on", "duckgres_service", True, True),
("legacy_flag_off", "org_root", False, False),
("legacy_flag_on", "org_root", True, False),
]
@@ -122,14 +124,17 @@ class TestGetDirectConnectionSource(APIBaseTest):
membership.save()
external_source = self._create_source(access_method=ExternalDataSource.AccessMethod.DIRECT)
- managed_source = self._create_managed_source(
- connection_metadata={
- "engine": "duckdb",
- "system_managed": True,
- "credential_kind": credential_kind,
- "reader_configured": credential_kind == "project_reader",
- }
- )
+ connection_metadata: dict[str, object] = {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": credential_kind,
+ "reader_configured": credential_kind == "project_reader",
+ }
+ source_overrides: dict[str, object] = {"connection_metadata": connection_metadata}
+ if credential_kind == "duckgres_service":
+ source_overrides["job_inputs"] = {}
+ connection_metadata["lifecycle_generation"] = 1
+ managed_source = self._create_managed_source(**source_overrides)
AccessControl.objects.create(
team=self.team,
resource="external_data_source",
@@ -153,6 +158,23 @@ class TestGetDirectConnectionSource(APIBaseTest):
get_direct_connection_source(self.team, str(source.id), require_pure_direct=True),
source,
)
+
+ @parameterized.expand([("flag_off", False), ("flag_on", True)])
+ def test_saved_dynamic_connection_id_resolves_independently_of_picker_flag(
+ self, _name: str, flag_enabled: bool
+ ) -> None:
+ source = self._create_managed_source(
+ job_inputs={},
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ },
+ )
+ self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
+
+ self.assertEqual(get_direct_connection_source(self.team, str(source.id)), source)
self.assertEqual(
get_direct_external_data_source_for_connection(self.team.id, str(source.id)),
source,
diff --git a/posthog/hogql/test/test_direct_duckgres_query.py b/posthog/hogql/test/test_direct_duckgres_query.py
index 1e1286cf92e7..c5e997fcd8e5 100644
--- a/posthog/hogql/test/test_direct_duckgres_query.py
+++ b/posthog/hogql/test/test_direct_duckgres_query.py
@@ -14,6 +14,7 @@ from psycopg import pq
from posthog.hogql.constants import HogQLGlobalSettings
from posthog.hogql.database.database import Database
from posthog.hogql.direct_sql import DuckgresRawAdapter, PostgresAdapter, get_adapter, get_raw_adapter_for_source
+from posthog.hogql.direct_sql.adapter import DirectQueryPrincipal
from posthog.hogql.direct_sql.duckgres_adapter import _DuckgresStreamingClientCursor
from posthog.hogql.errors import ExposedHogQLError, QueryError, TableAccessDeniedError
from posthog.hogql.query import HogQLQueryExecutor
@@ -71,6 +72,19 @@ class TestDuckgresRawAdapterSelection(SimpleTestCase):
),
PostgresAdapter,
)
+
+ def test_selects_native_adapter_for_secretless_service_credentials(self) -> None:
+ source = self._source(
+ job_inputs={},
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ },
+ )
+
+ self.assertIsInstance(get_raw_adapter_for_source(source), DuckgresRawAdapter)
self.assertIsInstance(
get_raw_adapter_for_source(self._source(prefix="customer_postgres", connection_metadata={})),
PostgresAdapter,
@@ -236,6 +250,17 @@ class TestDirectDuckgresQuery(APIBaseTest):
),
)
+ def _dynamic_managed_source(self, *, source_id: str = "managed-service-source") -> ExternalDataSource:
+ return self._managed_source(
+ source_id=source_id,
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ },
+ )
+
@staticmethod
def _connection_with_result(rows: list[tuple[object, ...]], type_code: int = 23) -> tuple[MagicMock, MagicMock]:
cursor = MagicMock()
@@ -328,6 +353,63 @@ class TestDirectDuckgresQuery(APIBaseTest):
connection.execute.assert_called_once_with("USE ducklake")
cursor.stream.assert_called_once_with("SELECT 1 AS value", None)
+ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")
+ @patch("posthog.hogql.direct_sql.duckgres_adapter.resolve_managed_warehouse_postgres_connection")
+ def test_dynamic_source_mints_for_the_stable_user_identity_and_uses_tls(self, resolve_connection, connect) -> None:
+ source = self._dynamic_managed_source()
+ source.job_inputs = {}
+ source.save(update_fields=["job_inputs"])
+ resolve_connection.return_value = MagicMock(
+ host="managed.example.com",
+ port=5432,
+ database="ducklake",
+ username="svc_generated",
+ password="service-secret",
+ sslmode="require",
+ )
+ connection, _cursor = self._connection_with_result([(1,)])
+ connect.return_value.__enter__.return_value = connection
+
+ HogQLQueryExecutor(
+ query="SELECT 1 AS value",
+ team=self.team,
+ user=self.user,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ ).execute()
+
+ resolve_connection.assert_called_once()
+ self.assertEqual(
+ resolve_connection.call_args.kwargs["principal"],
+ f"posthog:sql-editor:team:{self.team.pk}:user:{self.user.pk}",
+ )
+ self.assertNotIn(self.user.email, resolve_connection.call_args.kwargs["principal"])
+ source_config = connect.call_args.args[0]
+ self.assertEqual(source_config.user, "svc_generated")
+ self.assertEqual(source_config.password, "service-secret")
+
+ @patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")
+ def test_dynamic_source_without_a_real_user_fails_closed(self, connect) -> None:
+ source = self._dynamic_managed_source()
+ source.job_inputs = {}
+ source.save(update_fields=["job_inputs"])
+
+ with self.assertRaisesMessage(ExposedHogQLError, "Managed warehouse is unavailable"):
+ HogQLQueryExecutor(
+ query="SELECT 1",
+ team=self.team,
+ connection_id=str(source.id),
+ send_raw_query=True,
+ ).execute()
+
+ connect.assert_not_called()
+
+ def test_request_principal_is_a_narrow_immutable_contract(self) -> None:
+ principal = DirectQueryPrincipal(value="posthog:sql-editor:team:1:user:2")
+
+ with self.assertRaises(AttributeError):
+ principal.__setattr__("value", "changed")
+
@patch("posthog.hogql.direct_sql.duckgres_adapter._connect_duckgres_address")
def test_rejects_multiple_statements_before_connecting(self, connect) -> None:
source = self._managed_source()
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.py
index 1b5c996b32c8..66f70b531fde 100644
--- a/posthog/settings/base_variables.py
+++ b/posthog/settings/base_variables.py
@@ -76,6 +76,9 @@ PERSONAL_SPEND_CROSS_REGION_SECRET: str = get_from_env("PERSONAL_SPEND_CROSS_REG
DUCKGRES_API_URL: str | None = get_from_env("DUCKGRES_API_URL", optional=True)
DUCKGRES_INTERNAL_SECRET: str | None = get_from_env("DUCKGRES_INTERNAL_SECRET", optional=True)
DUCKGRES_PG_PORT: int = get_from_env("DUCKGRES_PG_PORT", 5432, type_cast=int)
+MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED: bool = get_from_env(
+ "MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED", False, type_cast=str_to_bool
+)
# Bulk deletion operations can be disabled during database migrations
DISABLE_BULK_DELETES: bool = get_from_env("DISABLE_BULK_DELETES", False, type_cast=str_to_bool)
diff --git a/products/data_warehouse/backend/facade/api.py b/products/data_warehouse/backend/facade/api.py
index 7a07ecfcf3a1..2097144f004d 100644
--- a/products/data_warehouse/backend/facade/api.py
+++ b/products/data_warehouse/backend/facade/api.py
@@ -72,6 +72,7 @@ _LAZY = {
"reconcile_redshift_schemas": "redshift_helpers",
"reproject_direct_redshift_table": "redshift_helpers",
"schedule_managed_warehouse_tables_reconcile": "tasks.tasks",
+ "schedule_managed_warehouse_direct_source_ensure": "tasks.tasks",
"schedule_soft_delete_managed_warehouse_sources": "tasks.tasks",
"HogQLQueryFixerTool": "max_tools",
"hide_direct_mysql_table": "direct_mysql",
diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.py
index e60e7928fecf..65600191aa31 100644
--- a/products/data_warehouse/backend/tasks/tasks.py
+++ b/products/data_warehouse/backend/tasks/tasks.py
@@ -1,5 +1,7 @@
from uuid import UUID
+from django.conf import settings
+
import structlog
from celery import shared_task
from prometheus_client import Counter
@@ -47,9 +49,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
-# A team can have both a legacy and a project-reader catalog, and each metadata query
-# has a 10-minute database timeout. Cover both serial queries so another task cannot
-# overlap the catalog writes near the old lock boundary.
+# A team can temporarily have dynamic, project-reader, and static compatibility
+# catalogs, and each metadata query has a 10-minute database timeout. Cover the
+# serial queries so another task cannot overlap catalog writes near the lock boundary.
MANAGED_WAREHOUSE_RECONCILE_LOCK_TIMEOUT_SECONDS = 30 * 60
MANAGED_WAREHOUSE_RECONCILE_INTERVAL_SECONDS = 60
@@ -90,17 +92,85 @@ def schedule_managed_warehouse_tables_reconcile(*, team_id: int, organization_id
)
@skip_team_scope_audit
def soft_delete_managed_warehouse_sources_task(organization_id: str) -> None:
+ from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
+ soft_delete_legacy_managed_warehouse_sources,
+ )
+
+ if settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ logger.warning("Ignoring a legacy managed warehouse cleanup task after dynamic auth enablement")
+ return
+ soft_delete_legacy_managed_warehouse_sources(organization_id=organization_id)
+
+
+@shared_task(
+ ignore_result=True,
+ name="products.data_warehouse.backend.tasks.soft_delete_managed_warehouse_sources_v2",
+ autoretry_for=(Exception,),
+ retry_backoff=60,
+ retry_backoff_max=3600,
+ max_retries=10,
+)
+@skip_team_scope_audit
+def soft_delete_managed_warehouse_sources_v2_task(organization_id: str, expected_generation: int) -> None:
from products.managed_warehouse.backend.facade.connection import (
soft_delete_managed_warehouse_sources, # noqa: PLC0415
)
- soft_delete_managed_warehouse_sources(organization_id=organization_id)
+ soft_delete_managed_warehouse_sources(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
-def schedule_soft_delete_managed_warehouse_sources(*, organization_id: str | UUID) -> None:
+def schedule_soft_delete_managed_warehouse_sources(*, organization_id: str | UUID, expected_generation: int) -> None:
+ if settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ soft_delete_managed_warehouse_sources_v2_task.delay(
+ organization_id=str(organization_id),
+ expected_generation=expected_generation,
+ )
+ return
soft_delete_managed_warehouse_sources_task.delay(organization_id=str(organization_id))
+@shared_task(
+ ignore_result=True,
+ name="products.data_warehouse.backend.tasks.ensure_managed_warehouse_direct_source_v2",
+ autoretry_for=(Exception,),
+ retry_backoff=60,
+ retry_backoff_max=3600,
+ max_retries=10,
+)
+@skip_team_scope_audit
+def ensure_managed_warehouse_direct_source_v2_task(
+ team_id: int,
+ organization_id: str,
+ expected_generation: int,
+) -> None:
+ if not settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ return
+ from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
+ ensure_managed_warehouse_direct_source,
+ )
+
+ ensure_managed_warehouse_direct_source(
+ team_id=team_id,
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
+
+
+def schedule_managed_warehouse_direct_source_ensure(
+ *, team_id: int, organization_id: str | UUID, expected_generation: int
+) -> None:
+ if not settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ return
+ ensure_managed_warehouse_direct_source_v2_task.delay(
+ team_id=team_id,
+ organization_id=str(organization_id),
+ expected_generation=expected_generation,
+ )
+
+
@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:
diff --git a/products/managed_warehouse/backend/facade/connection.py b/products/managed_warehouse/backend/facade/connection.py
index 67e46dc710b2..fafca0d19080 100644
--- a/products/managed_warehouse/backend/facade/connection.py
+++ b/products/managed_warehouse/backend/facade/connection.py
@@ -7,23 +7,65 @@ from uuid import UUID
from products.managed_warehouse.backend.logic import connection as connection_logic
__all__ = [
+ "activate_managed_warehouse_source_lifecycle",
+ "deactivate_managed_warehouse_source_lifecycle",
"ensure_managed_warehouse_direct_source",
+ "get_active_managed_warehouse_source_generation",
+ "get_managed_warehouse_source_generation",
"reconcile_managed_warehouse_tables",
+ "soft_delete_legacy_managed_warehouse_sources",
"soft_delete_managed_warehouse_sources",
"update_managed_warehouse_root_password",
]
-def ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> None:
- connection_logic.ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)
+def get_active_managed_warehouse_source_generation(*, organization_id: str | UUID) -> int | None:
+ return connection_logic.get_active_managed_warehouse_source_generation(organization_id=organization_id)
+
+
+def get_managed_warehouse_source_generation(*, organization_id: str | UUID) -> int:
+ return connection_logic.get_managed_warehouse_source_generation(organization_id=organization_id)
+
+
+def activate_managed_warehouse_source_lifecycle(*, organization_id: str | UUID, expected_generation: int) -> int | None:
+ return connection_logic.activate_managed_warehouse_source_lifecycle(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
+
+
+def deactivate_managed_warehouse_source_lifecycle(
+ *, organization_id: str | UUID, expected_generation: int
+) -> int | None:
+ return connection_logic.deactivate_managed_warehouse_source_lifecycle(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
+
+
+def ensure_managed_warehouse_direct_source(
+ *, team_id: int, organization_id: str | UUID, expected_generation: int
+) -> None:
+ connection_logic.ensure_managed_warehouse_direct_source(
+ team_id=team_id,
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:
connection_logic.reconcile_managed_warehouse_tables(team_id=team_id, organization_id=organization_id)
-def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID) -> None:
- connection_logic.soft_delete_managed_warehouse_sources(organization_id=organization_id)
+def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID, expected_generation: int) -> None:
+ connection_logic.soft_delete_managed_warehouse_sources(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
+
+
+def soft_delete_legacy_managed_warehouse_sources(*, organization_id: str | UUID) -> None:
+ connection_logic.soft_delete_legacy_managed_warehouse_sources(organization_id=organization_id)
def update_managed_warehouse_root_password(*, organization_id: str | UUID, password: str) -> None:
diff --git a/products/managed_warehouse/backend/facade/contracts.py b/products/managed_warehouse/backend/facade/contracts.py
index c229e4bd3c9a..60a6164bbfe2 100644
--- a/products/managed_warehouse/backend/facade/contracts.py
+++ b/products/managed_warehouse/backend/facade/contracts.py
@@ -32,7 +32,9 @@ __all__ = [
"DuckLakeTableResult",
"DucklingTables",
"ManagedWarehouseBackfillState",
+ "ManagedWarehousePostgresConnection",
"ManagedWarehouseProvisionStatus",
+ "ManagedWarehouseSourceAuth",
"ManagedWarehouseSourceJobRecord",
"ManagedWarehouseSourceJobStatus",
"ManagedWarehouseSourceJobUpdate",
@@ -100,6 +102,26 @@ class ServiceCredentialUnavailable(RuntimeError):
to the stored server login or fail the run."""
+@frozen
+class ManagedWarehousePostgresConnection:
+ host: str
+ port: int
+ database: str
+ username: str
+ password: str = field(repr=False)
+ sslmode: str
+
+
+@frozen
+class ManagedWarehouseSourceAuth:
+ """Non-secret source fields needed to choose managed warehouse authentication."""
+
+ prefix: str | None
+ system_managed: bool
+ credential_kind: str | None
+ lifecycle_generation: int | None
+
+
@dataclass(frozen=True, kw_only=True)
class ManagedWarehouseProvisionStatus:
"""Whether an organization has a stored managed-warehouse connection."""
diff --git a/products/managed_warehouse/backend/facade/sql_editor.py b/products/managed_warehouse/backend/facade/sql_editor.py
new file mode 100644
index 000000000000..bc7507d1964b
--- /dev/null
+++ b/products/managed_warehouse/backend/facade/sql_editor.py
@@ -0,0 +1,5 @@
+from products.managed_warehouse.backend.logic.sql_editor_credentials import (
+ resolve_managed_warehouse_postgres_connection,
+)
+
+__all__ = ["resolve_managed_warehouse_postgres_connection"]
diff --git a/products/managed_warehouse/backend/logic/connection.py b/products/managed_warehouse/backend/logic/connection.py
index fb57b618375e..762680d3e944 100644
--- a/products/managed_warehouse/backend/logic/connection.py
+++ b/products/managed_warehouse/backend/logic/connection.py
@@ -1,30 +1,47 @@
"""Expose a managed Duckgres warehouse in the SQL editor as a Postgres connection.
-Each enrolled team keeps its auto-provisioned external source backed by the stored server
-login. If a confirmed ``project_reader`` source also exists, it has an independent catalog.
-This module does not create, replace, or rotate project readers.
+Each member team gets a Postgres ``ExternalDataSource`` whose short-lived Duckgres
+credential is resolved when a connection is opened. Duckgres root sees every schema in
+the warehouse, so the connection discovers and exposes the whole org catalog without
+per-team namespace configuration. Setup happens in two steps:
+
+1. ``ensure_managed_warehouse_direct_source`` creates the source row after explicit
+ successful provision or onboarding, so the connection appears immediately.
+2. ``reconcile_managed_warehouse_tables`` only updates an existing live source 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.
-``soft_delete_managed_warehouse_sources`` handles deprovisioning of the whole warehouse.
-Deleting a team removes its project-scoped source through the existing model cascade.
+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
+from datetime import datetime
from uuid import UUID, uuid4
+from django.conf import settings
from django.db import transaction
from django.db.models import QuerySet
from django.utils import timezone
import structlog
+from posthog.dataclasses import frozen
+from posthog.models.organization import Organization
from posthog.models.team.team import Team
from products.data_warehouse.backend.facade.api import reconcile_postgres_schemas
-from products.managed_warehouse.backend.models import DuckgresServer
+from products.managed_warehouse.backend.facade.contracts import ManagedWarehouseSourceAuth
+from products.managed_warehouse.backend.logic.sql_editor_credentials import (
+ MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ resolve_managed_warehouse_postgres_connection,
+)
+from products.managed_warehouse.backend.models import DuckgresServer, ManagedWarehouseSourceLifecycle
from products.warehouse_sources.backend.facade.models import (
MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS,
MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
@@ -41,7 +58,8 @@ logger = structlog.get_logger(__name__)
MANAGED_WAREHOUSE_SOURCE_DESCRIPTION = "Managed warehouse (auto-provisioned)"
# Database engine internals — never warehouse data. Sidebar hygiene, not permissioning:
-# The discovery login may expose engine internals, so this denylist keeps them out of the sidebar.
+# 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"})
@@ -59,8 +77,58 @@ def _managed_source_queryset(team_id: int) -> QuerySet[ExternalDataSource]:
)
+def _source_auth(source: ExternalDataSource) -> ManagedWarehouseSourceAuth:
+ metadata = source.connection_metadata if isinstance(source.connection_metadata, dict) else {}
+ credential_kind = metadata.get("credential_kind")
+ lifecycle_generation = metadata.get("lifecycle_generation")
+ return ManagedWarehouseSourceAuth(
+ prefix=source.prefix,
+ system_managed=metadata.get("system_managed") is True,
+ credential_kind=credential_kind if isinstance(credential_kind, str) else None,
+ lifecycle_generation=(lifecycle_generation if isinstance(lifecycle_generation, int) else None),
+ )
+
+
+def _is_dynamic_managed_warehouse_source(source: ExternalDataSource) -> bool:
+ return _source_auth(source).credential_kind == MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
+
+
+def _credential_kind(source: ExternalDataSource) -> str | None:
+ return _source_auth(source).credential_kind
+
+
+def _schema_discovery_principal(team_id: int) -> str:
+ return f"posthog:sql-editor-schema-discovery:team:{team_id}"
+
+
+@frozen
+class _LifecycleSnapshot:
+ organization_exists: bool
+ desired_active: bool
+ generation: int | None
+
+
+def _lifecycle_snapshot(organization_id: str | UUID, *, lock: bool = False) -> _LifecycleSnapshot:
+ organization_queryset = Organization.objects.only("id")
+ if lock:
+ organization_queryset = organization_queryset.select_for_update()
+ if not organization_queryset.filter(id=organization_id).exists():
+ return _LifecycleSnapshot(organization_exists=False, desired_active=False, generation=None)
+ lifecycle_queryset = ManagedWarehouseSourceLifecycle.objects.filter(organization_id=organization_id)
+ if lock:
+ lifecycle_queryset = lifecycle_queryset.select_for_update()
+ lifecycle = lifecycle_queryset.first()
+ if lifecycle is None:
+ return _LifecycleSnapshot(organization_exists=True, desired_active=True, generation=None)
+ return _LifecycleSnapshot(
+ organization_exists=True,
+ desired_active=lifecycle.desired_active,
+ generation=lifecycle.generation,
+ )
+
+
def _source_config(server: DuckgresServer) -> dict[str, object]:
- """Snapshot the stored server login into the source's job_inputs."""
+ """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(
{
@@ -73,11 +141,116 @@ def _source_config(server: DuckgresServer) -> dict[str, object]:
).to_dict()
-def _is_project_reader_source(source: ExternalDataSource) -> bool:
- metadata = source.connection_metadata
- return (
- isinstance(metadata, dict)
- and metadata.get("credential_kind") == MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND
+def _set_dynamic_source_auth(source: ExternalDataSource, *, lifecycle_generation: int) -> ExternalDataSource:
+ source.access_method = ExternalDataSource.AccessMethod.DIRECT
+ source.direct_query_enabled = True
+ source.connection_metadata = {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ "lifecycle_generation": lifecycle_generation,
+ }
+ source.job_inputs = {}
+ source.deleted = False
+ source.deleted_at = None
+ source.save(
+ update_fields=[
+ "access_method",
+ "direct_query_enabled",
+ "connection_metadata",
+ "job_inputs",
+ "deleted",
+ "deleted_at",
+ "updated_at",
+ ]
+ )
+ return source
+
+
+def _tombstone_source(source: ExternalDataSource) -> None:
+ now = timezone.now()
+ DataWarehouseTable.raw_objects.filter(external_data_source_id=source.id, deleted=False).update(
+ deleted=True,
+ deleted_at=now,
+ updated_at=now,
+ )
+ source.deleted = True
+ source.deleted_at = now
+ source.save(update_fields=["deleted", "deleted_at", "updated_at"])
+
+
+def _ensure_managed_source_locked(
+ *, team_id: int, convert_active_legacy: bool, lifecycle_generation: int
+) -> ExternalDataSource:
+ sources = list(_managed_source_queryset(team_id).select_for_update().order_by("-created_at"))
+ if convert_active_legacy:
+ for source in sources:
+ if not source.deleted and _credential_kind(source) == MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND:
+ _tombstone_source(source)
+
+ live_dynamic = next(
+ (source for source in sources if not source.deleted and _is_dynamic_managed_warehouse_source(source)), None
+ )
+ if live_dynamic is not None:
+ return _set_dynamic_source_auth(live_dynamic, lifecycle_generation=lifecycle_generation)
+
+ live_reader = next(
+ (
+ source
+ for source in sources
+ if not source.deleted
+ and _credential_kind(source) == MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND
+ and source.is_managed_warehouse_ready
+ ),
+ None,
+ )
+ live_legacy = next(
+ (
+ source
+ for source in sources
+ if not source.deleted and _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS
+ ),
+ None,
+ )
+ if live_legacy is not None:
+ return (
+ _set_dynamic_source_auth(live_legacy, lifecycle_generation=lifecycle_generation)
+ if convert_active_legacy
+ else live_legacy
+ )
+ if live_reader is not None:
+ return live_reader
+
+ tombstoned_dynamic = next((source for source in sources if _is_dynamic_managed_warehouse_source(source)), None)
+ if tombstoned_dynamic is not None:
+ return _set_dynamic_source_auth(tombstoned_dynamic, lifecycle_generation=lifecycle_generation)
+ if convert_active_legacy:
+ tombstoned_legacy = next(
+ (source for source in sources if _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS),
+ None,
+ )
+ if tombstoned_legacy is not None:
+ return _set_dynamic_source_auth(tombstoned_legacy, lifecycle_generation=lifecycle_generation)
+
+ 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={},
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ description=MANAGED_WAREHOUSE_SOURCE_DESCRIPTION,
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ created_via=ExternalDataSource.CreatedVia.WEB,
+ direct_query_enabled=True,
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ "lifecycle_generation": lifecycle_generation,
+ },
)
@@ -86,20 +259,20 @@ def _ensure_stored_login_source_locked(*, team_id: int, server: DuckgresServer)
(
source
for source in _managed_source_queryset(team_id).select_for_update().order_by("deleted", "-created_at")
- if not _is_project_reader_source(source)
+ if _credential_kind(source) != MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND
),
None,
)
-
config = _source_config(server)
if existing is not None:
update_fields: list[str] = []
connection_metadata = dict(existing.connection_metadata or {})
if connection_metadata.get("credential_kind") not in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS:
- # Catalog rows discovered with an unknown credential scope cannot be reused safely.
now = timezone.now()
DataWarehouseTable.raw_objects.filter(
- team_id=team_id, external_data_source_id=existing.id, deleted=False
+ 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:
@@ -123,6 +296,7 @@ def _ensure_stored_login_source_locked(*, team_id: int, server: DuckgresServer)
"credential_kind": "org_root",
}
migrated.pop("reader_configured", None)
+ migrated.pop("lifecycle_generation", None)
existing.connection_metadata = migrated
update_fields.append("connection_metadata")
if existing.deleted:
@@ -154,70 +328,153 @@ def _ensure_stored_login_source_locked(*, team_id: int, server: DuckgresServer)
)
-def ensure_managed_warehouse_direct_source(*, team_id: int, organization_id: str | UUID) -> ExternalDataSource:
- """Create or refresh the external source backed by the stored server login."""
+def _locked_source_lifecycle(organization_id: str | UUID) -> ManagedWarehouseSourceLifecycle:
+ # The organization row serializes first-time lifecycle-row creation as well as all
+ # later generation reads/writes. This avoids relying on DuckgresServer for lifecycle
+ # coordination and gives every team in an organization one common fence.
+ organization = Organization.objects.select_for_update().only("id").get(id=organization_id)
+ lifecycle, _created = ManagedWarehouseSourceLifecycle.objects.get_or_create(organization=organization)
+ return lifecycle
+
+
+def get_active_managed_warehouse_source_generation(*, organization_id: str | UUID) -> int | None:
+ """Capture the current active generation before onboarding an additional team."""
with transaction.atomic():
- server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)
+ lifecycle = _locked_source_lifecycle(organization_id)
+ return lifecycle.generation if lifecycle.desired_active else None
+
+
+def get_managed_warehouse_source_generation(*, organization_id: str | UUID) -> int:
+ """Capture the current generation before a provision request, active or inactive."""
+ with transaction.atomic():
+ return _locked_source_lifecycle(organization_id).generation
+
+
+def activate_managed_warehouse_source_lifecycle(*, organization_id: str | UUID, expected_generation: int) -> int | None:
+ """Conditionally advance after provision, unless a newer lifecycle operation won."""
+ with transaction.atomic():
+ lifecycle = _locked_source_lifecycle(organization_id)
+ if lifecycle.generation != expected_generation:
+ return None
+ was_inactive = not lifecycle.desired_active
+ lifecycle.generation += 1
+ lifecycle.desired_active = True
+ lifecycle.legacy_conversion_generation = lifecycle.generation if was_inactive else None
+ lifecycle.save(update_fields=["generation", "desired_active", "legacy_conversion_generation"])
+ return lifecycle.generation
+
+
+def deactivate_managed_warehouse_source_lifecycle(
+ *, organization_id: str | UUID, expected_generation: int
+) -> int | None:
+ """Mark the lifecycle inactive once and return the cleanup operation generation."""
+ with transaction.atomic():
+ organization = Organization.objects.select_for_update().only("id").filter(id=organization_id).first()
+ if organization is None:
+ return None
+ lifecycle, _created = ManagedWarehouseSourceLifecycle.objects.get_or_create(organization=organization)
+ if lifecycle.generation != expected_generation:
+ return None
+ if lifecycle.desired_active:
+ lifecycle.generation += 1
+ lifecycle.desired_active = False
+ lifecycle.legacy_conversion_generation = None
+ lifecycle.save(update_fields=["generation", "desired_active", "legacy_conversion_generation"])
+ return lifecycle.generation
+
+
+def ensure_managed_warehouse_direct_source(
+ *, team_id: int, organization_id: str | UUID, expected_generation: int
+) -> ExternalDataSource | None:
+ """Create or refresh a source only if no deprovision happened since the request began."""
+ with transaction.atomic():
+ lifecycle = _locked_source_lifecycle(organization_id)
+ if not lifecycle.desired_active or lifecycle.generation != expected_generation:
+ return None
Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)
- return _ensure_stored_login_source_locked(team_id=team_id, server=server)
+ if not settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ sources = list(_managed_source_queryset(team_id).select_for_update().order_by("-created_at"))
+ convert_active_legacy = lifecycle.legacy_conversion_generation == expected_generation
+ if convert_active_legacy:
+ for source in sources:
+ if (
+ not source.deleted
+ and _credential_kind(source) == MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND
+ ):
+ _tombstone_source(source)
+ live_dynamic = next(
+ (source for source in sources if not source.deleted and _is_dynamic_managed_warehouse_source(source)),
+ None,
+ )
+ if live_dynamic is not None:
+ if _source_auth(live_dynamic).lifecycle_generation != expected_generation:
+ return _set_dynamic_source_auth(
+ live_dynamic,
+ lifecycle_generation=expected_generation,
+ )
+ return live_dynamic
+ server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)
+ return _ensure_stored_login_source_locked(team_id=team_id, server=server)
+ return _ensure_managed_source_locked(
+ team_id=team_id,
+ convert_active_legacy=lifecycle.legacy_conversion_generation == expected_generation,
+ lifecycle_generation=expected_generation,
+ )
-def _reconcile_managed_warehouse_source(
- *,
- team_id: int,
- organization_id: str | UUID,
- source_id: UUID,
- expected_mode: ManagedWarehouseSQLMode,
-) -> None:
+def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str | UUID, source_id: UUID) -> None:
+ lifecycle_snapshot = _lifecycle_snapshot(organization_id)
+ if not lifecycle_snapshot.desired_active:
+ return
with transaction.atomic():
- if expected_mode == ManagedWarehouseSQLMode.EXTERNAL:
- server_exists = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).exists()
- if not server_exists:
- return
team = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()
if team is None:
return
- source = (
- _managed_source_queryset(team_id)
- .select_for_update()
- .filter(
- id=source_id,
- deleted=False,
- )
- .first()
- )
- if source is None or source.managed_warehouse_sql_mode != expected_mode:
+ source = _managed_source_queryset(team_id).select_for_update().filter(id=source_id, deleted=False).first()
+ if source is None:
return
- source_config = dict(source.job_inputs or {})
+ source_id = source.id
source_api_version = source.api_version
+ credential_kind = _credential_kind(source)
excluded_schemas = internal_schemas()
source_impl = SourceRegistry.get_source(ExternalDataSourceType.POSTGRES)
try:
+ dynamic_connection = resolve_managed_warehouse_postgres_connection(
+ source_auth=_source_auth(source),
+ organization_id=organization_id,
+ team_id=team_id,
+ principal=_schema_discovery_principal(team_id),
+ )
+ source_config = (
+ {
+ "host": dynamic_connection.host,
+ "port": dynamic_connection.port,
+ "database": dynamic_connection.database,
+ "user": dynamic_connection.username,
+ "password": dynamic_connection.password,
+ }
+ if dynamic_connection is not None
+ else dict(source.job_inputs or {})
+ )
config = source_impl.parse_config(source_config)
discovered = source_impl.get_schemas(
- config, team_id, api_version=source_impl.resolve_api_version(source_api_version)
+ config,
+ team_id,
+ api_version=source_impl.resolve_api_version(source_api_version),
+ require_ssl=dynamic_connection is not None and dynamic_connection.sslmode == "require",
)
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,
- source_id=source_id,
- source_mode=expected_mode,
- exc_info=True,
- )
+ logger.warning("Managed warehouse introspection failed; will retry", team_id=team_id, exc_info=True)
return
source_schemas = [schema for schema in discovered if (schema.source_schema or "") not in excluded_schemas]
with transaction.atomic():
- # Revalidate after live introspection so deprovision wins the race.
- if expected_mode == ManagedWarehouseSQLMode.EXTERNAL:
- server_exists = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).exists()
- if not server_exists:
- return
+ if _lifecycle_snapshot(organization_id, lock=True) != lifecycle_snapshot:
+ return
team = Team.objects.select_for_update().only("id").filter(id=team_id, organization_id=organization_id).first()
if team is None:
return
@@ -228,10 +485,13 @@ def _reconcile_managed_warehouse_source(
id=source_id,
deleted=False,
access_method=ExternalDataSource.AccessMethod.DIRECT,
+ direct_query_enabled=True,
)
.first()
)
- if source is None or source.managed_warehouse_sql_mode != expected_mode:
+ if source is None:
+ return
+ if _credential_kind(source) != credential_kind:
return
for schema in source_schemas:
@@ -251,45 +511,65 @@ def _reconcile_managed_warehouse_source(
def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:
- """Discover each live managed-warehouse catalog using that source's own credentials."""
- legacy_source_id: UUID | None = None
- reader_source_id: UUID | None = None
- try:
- with transaction.atomic():
- server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()
- Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)
- sources = list(_managed_source_queryset(team_id).select_for_update().order_by("-created_at"))
- has_tombstone = any(source.deleted for source in sources)
- has_live_legacy_source = any(
- not source.deleted and not _is_project_reader_source(source) for source in sources
- )
- # Explicit reprovisioning revives one mode; tombstones left for the other mode remain authoritative.
- if server is not None and (not has_tombstone or has_live_legacy_source):
- legacy_source_id = _ensure_stored_login_source_locked(team_id=team_id, server=server).id
-
- reader_source = next(
- (source for source in sources if not source.deleted and source.is_managed_warehouse_ready),
- None,
- )
- if reader_source is not None:
- reader_source_id = reader_source.id
- except Team.DoesNotExist:
- return
+ """Reconcile every live managed catalog with that source's own credential mode."""
+ if not settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ lifecycle_snapshot = _lifecycle_snapshot(organization_id)
+ if not lifecycle_snapshot.desired_active:
+ return
+ try:
+ if lifecycle_snapshot.generation is not None:
+ ensure_managed_warehouse_direct_source(
+ team_id=team_id,
+ organization_id=organization_id,
+ expected_generation=lifecycle_snapshot.generation,
+ )
+ else:
+ _ensure_unfenced_legacy_source_for_reconcile(
+ team_id=team_id,
+ organization_id=organization_id,
+ )
+ except (DuckgresServer.DoesNotExist, Team.DoesNotExist):
+ return
- if legacy_source_id is not None:
+ candidates = _managed_source_queryset(team_id).filter(deleted=False).order_by("created_at")
+ source_ids = [
+ source.id for source in candidates if source.managed_warehouse_sql_mode != ManagedWarehouseSQLMode.UNAVAILABLE
+ ]
+ for source_id in source_ids:
_reconcile_managed_warehouse_source(
team_id=team_id,
organization_id=organization_id,
- source_id=legacy_source_id,
- expected_mode=ManagedWarehouseSQLMode.EXTERNAL,
+ source_id=source_id,
)
- if reader_source_id is not None:
- _reconcile_managed_warehouse_source(
- team_id=team_id,
- organization_id=organization_id,
- source_id=reader_source_id,
- expected_mode=ManagedWarehouseSQLMode.BUILT_IN,
+
+
+def _ensure_unfenced_legacy_source_for_reconcile(
+ *, team_id: int, organization_id: str | UUID
+) -> ExternalDataSource | None:
+ """Keep pre-lifecycle workers recoverable without weakening a lifecycle fence."""
+ with transaction.atomic():
+ organization = Organization.objects.select_for_update().only("id").filter(id=organization_id).first()
+ if organization is None or ManagedWarehouseSourceLifecycle.objects.filter(organization=organization).exists():
+ return None
+ Team.objects.select_for_update().only("id").get(id=team_id, organization_id=organization_id)
+ sources = list(_managed_source_queryset(team_id).select_for_update().order_by("-created_at"))
+ live_dynamic = next(
+ (source for source in sources if not source.deleted and _is_dynamic_managed_warehouse_source(source)),
+ None,
+ )
+ if live_dynamic is not None:
+ return live_dynamic
+ has_tombstone = any(source.deleted for source in sources)
+ has_live_legacy = any(
+ not source.deleted and _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS
+ for source in sources
)
+ if has_tombstone and not has_live_legacy:
+ return None
+ server = DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()
+ if server is None:
+ return None
+ return _ensure_stored_login_source_locked(team_id=team_id, server=server)
def _managed_sources_for_org(organization_id: str | UUID) -> QuerySet[ExternalDataSource]:
@@ -302,10 +582,9 @@ def _managed_sources_for_org(organization_id: str | UUID) -> QuerySet[ExternalDa
def update_managed_warehouse_root_password(*, organization_id: str | UUID, password: str) -> None:
- """Rotate the stored root password without modifying project-reader sources.
+ """Rotate the stored root password and active legacy sources for the organization.
- Stored-login sources snapshot the root credential into ``job_inputs``. Project-reader
- passwords have a separate lifecycle and must remain unchanged.
+ Dynamic sources mint credentials at connection time and are intentionally skipped.
"""
with transaction.atomic():
server = DuckgresServer.objects.select_for_update().get(organization_id=organization_id)
@@ -314,23 +593,80 @@ def update_managed_warehouse_root_password(*, organization_id: str | UUID, passw
config = _source_config(server)
for source in _managed_sources_for_org(organization_id).select_for_update().order_by("team_id"):
- if _is_project_reader_source(source):
+ if _credential_kind(source) in {
+ MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
+ }:
continue
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."""
+def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID, expected_generation: int) -> None:
+ """Fence stale setup requests and atomically tombstone all current query sources."""
now = timezone.now()
+ cleanup_error: Exception | None = None
with transaction.atomic():
- DuckgresServer.objects.select_for_update().filter(organization_id=organization_id).first()
+ organization = Organization.objects.select_for_update().only("id").filter(id=organization_id).first()
+ if organization is None:
+ return
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.filter(organization=organization).first()
+ if lifecycle is None or lifecycle.desired_active or lifecycle.generation != expected_generation:
+ return
+
+ # The inactive generation was committed immediately after remote deprovision.
+ # Keep source tombstoning atomic, while allowing a retry with this same token.
+ try:
+ with transaction.atomic():
+ _soft_delete_sources_for_inactive_generation_locked(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ now=now,
+ )
+ except Exception as error:
+ cleanup_error = error
+
+ if cleanup_error is not None:
+ raise cleanup_error
+
+
+def soft_delete_legacy_managed_warehouse_sources(*, organization_id: str | UUID) -> None:
+ if settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ return
+ now = timezone.now()
+ with transaction.atomic():
+ organization = Organization.objects.select_for_update().only("id").filter(id=organization_id).first()
+ if organization is None:
+ return
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.filter(organization=organization).first()
+ if lifecycle is not None:
+ _soft_delete_sources_for_inactive_generation_locked(
+ organization_id=organization_id,
+ expected_generation=lifecycle.generation,
+ now=now,
+ )
+ return
sources = list(_managed_sources_for_org(organization_id).select_for_update().order_by("team_id"))
- 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"])
+ _soft_delete_sources_locked(sources=sources, now=now)
+
+
+def _soft_delete_sources_for_inactive_generation_locked(
+ *, organization_id: str | UUID, expected_generation: int, now: datetime
+) -> None:
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.filter(organization_id=organization_id).first()
+ if lifecycle is None or lifecycle.desired_active or lifecycle.generation != expected_generation:
+ return
+ sources = list(_managed_sources_for_org(organization_id).select_for_update().order_by("team_id"))
+ _soft_delete_sources_locked(sources=sources, now=now)
+
+
+def _soft_delete_sources_locked(*, sources: list[ExternalDataSource], now: datetime) -> None:
+ 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/managed_warehouse/backend/logic/sql_editor_credentials.py b/products/managed_warehouse/backend/logic/sql_editor_credentials.py
new file mode 100644
index 000000000000..e18486d350e3
--- /dev/null
+++ b/products/managed_warehouse/backend/logic/sql_editor_credentials.py
@@ -0,0 +1,258 @@
+from __future__ import annotations
+
+from collections import OrderedDict
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from datetime import UTC, datetime, timedelta
+from threading import Condition, Lock
+from uuid import UUID
+
+from posthog.dataclasses import frozen
+
+from products.managed_warehouse.backend.facade.contracts import (
+ ManagedWarehousePostgresConnection,
+ ManagedWarehouseSourceAuth,
+ ServiceCredential,
+)
+from products.managed_warehouse.backend.service_credentials import ServiceCredentialUnavailable, mint_service_credential
+from products.warehouse_sources.backend.facade.models import (
+ MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ MANAGED_WAREHOUSE_SOURCE_PREFIX,
+)
+
+SQL_EDITOR_CREDENTIAL_REFRESH_MARGIN = timedelta(minutes=1)
+SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF = timedelta(seconds=5)
+SQL_EDITOR_CREDENTIAL_MINT_TIMEOUT_SECONDS = 3
+SQL_EDITOR_CREDENTIAL_CACHE_SIZE = 512
+
+CredentialMint = Callable[[str, int, str], ServiceCredential]
+Clock = Callable[[], datetime]
+
+
+def _utcnow() -> datetime:
+ return datetime.now(UTC)
+
+
+def _mint_sql_editor_credential(organization_id: str, team_id: int, principal: str) -> ServiceCredential:
+ return mint_service_credential(
+ organization_id,
+ team_id,
+ principal=principal,
+ timeout_seconds=SQL_EDITOR_CREDENTIAL_MINT_TIMEOUT_SECONDS,
+ )
+
+
+@dataclass(frozen=False)
+class _OrganizationCredentialState:
+ condition: Condition = field(default_factory=Condition)
+ credential: ServiceCredential | None = None
+ refreshing: bool = False
+ retry_after: datetime | None = None
+ failure_category: str | None = None
+ failure_message: str | None = None
+ leases: int = 0
+
+
+@frozen
+class _CredentialCacheKey:
+ organization_id: str
+ principal: str
+ lifecycle_generation: int
+
+
+class ServiceCredentialCache:
+ def __init__(
+ self,
+ *,
+ mint: CredentialMint = _mint_sql_editor_credential,
+ now: Clock = _utcnow,
+ maxsize: int = SQL_EDITOR_CREDENTIAL_CACHE_SIZE,
+ ) -> None:
+ self._mint = mint
+ self._now = now
+ self._maxsize = maxsize
+ self._states: OrderedDict[_CredentialCacheKey, _OrganizationCredentialState] = OrderedDict()
+ self._states_lock = Lock()
+
+ def get(
+ self,
+ organization_id: str | UUID,
+ team_id: int,
+ *,
+ principal: str,
+ lifecycle_generation: int = 0,
+ ) -> ServiceCredential:
+ cache_key = _CredentialCacheKey(
+ organization_id=str(organization_id),
+ principal=principal,
+ lifecycle_generation=lifecycle_generation,
+ )
+ state = self._state_for(cache_key)
+ try:
+ return self._get_from_state(state, cache_key, team_id)
+ finally:
+ self._release_state(cache_key, state)
+
+ def _get_from_state(
+ self, state: _OrganizationCredentialState, cache_key: _CredentialCacheKey, team_id: int
+ ) -> ServiceCredential:
+ with state.condition:
+ now = self._now()
+ cached = state.credential
+ if cached is not None and cached.expires_at > now + SQL_EDITOR_CREDENTIAL_REFRESH_MARGIN:
+ return cached
+
+ if state.retry_after is not None and now < state.retry_after:
+ if cached is not None and cached.expires_at > now:
+ return cached
+ raise self._failure_from_state(state, "service credential mint is backed off")
+
+ if state.refreshing:
+ if cached is not None and cached.expires_at > now:
+ return cached
+ refresh_finished = state.condition.wait_for(
+ lambda: not state.refreshing,
+ timeout=SQL_EDITOR_CREDENTIAL_MINT_TIMEOUT_SECONDS + 1,
+ )
+ if not refresh_finished:
+ raise ServiceCredentialUnavailable("service credential mint timed out")
+ now = self._now()
+ cached = state.credential
+ if cached is not None and cached.expires_at > now:
+ return cached
+ raise self._failure_from_state(state, "service credential mint failed")
+
+ state.refreshing = True
+
+ try:
+ minted = self._mint(cache_key.organization_id, team_id, cache_key.principal)
+ self._validate_minted_credential(minted)
+ except ServiceCredentialUnavailable:
+ with state.condition:
+ state.refreshing = False
+ state.failure_category = "unavailable"
+ # The control-plane exception may have parsed response data in its
+ # traceback or message. Retain only a fixed, public-safe summary.
+ state.failure_message = "service credential mint unavailable"
+ state.retry_after = self._now() + SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF
+ cached = state.credential
+ state.condition.notify_all()
+ if cached is not None and cached.expires_at > self._now():
+ return cached
+ raise ServiceCredentialUnavailable(state.failure_message) from None
+ except Exception:
+ with state.condition:
+ state.refreshing = False
+ state.failure_category = "unexpected"
+ state.failure_message = "service credential mint failed unexpectedly"
+ state.retry_after = self._now() + SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF
+ cached = state.credential
+ state.condition.notify_all()
+ if cached is not None and cached.expires_at > self._now():
+ return cached
+ raise ServiceCredentialUnavailable(state.failure_message) from None
+ except BaseException:
+ with state.condition:
+ state.refreshing = False
+ state.failure_category = "interrupted"
+ state.failure_message = "service credential mint was interrupted"
+ state.retry_after = self._now() + SQL_EDITOR_CREDENTIAL_RETRY_BACKOFF
+ state.condition.notify_all()
+ raise
+
+ with state.condition:
+ state.credential = minted
+ state.refreshing = False
+ state.retry_after = None
+ state.failure_category = None
+ state.failure_message = None
+ state.condition.notify_all()
+ return minted
+
+ def _validate_minted_credential(self, credential: ServiceCredential) -> None:
+ if credential.expires_at <= self._now():
+ raise ServiceCredentialUnavailable("service credential mint returned an expired credential")
+ if (
+ not credential.connect.host
+ or credential.connect.port <= 0
+ or not credential.connect.database
+ or credential.connect.sslmode != "require"
+ ):
+ raise ServiceCredentialUnavailable("SQL editor service credential requires a complete secure sslmode")
+
+ @staticmethod
+ def _failure_from_state(state: _OrganizationCredentialState, fallback: str) -> ServiceCredentialUnavailable:
+ return ServiceCredentialUnavailable(state.failure_message or fallback)
+
+ def _state_for(self, cache_key: _CredentialCacheKey) -> _OrganizationCredentialState:
+ with self._states_lock:
+ state = self._states.get(cache_key)
+ if state is not None:
+ self._states.move_to_end(cache_key)
+ state.leases += 1
+ return state
+
+ if len(self._states) >= self._maxsize:
+ eviction_key: _CredentialCacheKey | None = None
+ for existing_key, existing_state in self._states.items():
+ if existing_state.leases == 0:
+ eviction_key = existing_key
+ break
+ if eviction_key is None:
+ raise ServiceCredentialUnavailable("service credential cache is at capacity")
+ del self._states[eviction_key]
+
+ state = _OrganizationCredentialState(leases=1)
+ self._states[cache_key] = state
+ return state
+
+ def _release_state(self, cache_key: _CredentialCacheKey, state: _OrganizationCredentialState) -> None:
+ with self._states_lock:
+ if self._states.get(cache_key) is state:
+ state.leases -= 1
+
+
+_service_credential_cache = ServiceCredentialCache()
+
+
+def _is_dynamic_managed_warehouse_source(source_auth: ManagedWarehouseSourceAuth) -> bool:
+ return (
+ source_auth.prefix == MANAGED_WAREHOUSE_SOURCE_PREFIX
+ and source_auth.system_managed
+ and source_auth.credential_kind == MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
+ )
+
+
+def resolve_managed_warehouse_postgres_connection(
+ *,
+ source_auth: ManagedWarehouseSourceAuth,
+ organization_id: str | UUID,
+ team_id: int,
+ principal: str,
+ credential_cache: ServiceCredentialCache | None = None,
+) -> ManagedWarehousePostgresConnection | None:
+ if not _is_dynamic_managed_warehouse_source(source_auth):
+ return None
+ if (
+ source_auth.lifecycle_generation is None
+ or isinstance(source_auth.lifecycle_generation, bool)
+ or source_auth.lifecycle_generation < 0
+ ):
+ raise ServiceCredentialUnavailable("managed warehouse source has no valid lifecycle generation")
+
+ credential = (credential_cache or _service_credential_cache).get(
+ organization_id,
+ team_id,
+ principal=principal,
+ lifecycle_generation=source_auth.lifecycle_generation,
+ )
+ if credential.connect.sslmode != "require":
+ raise ServiceCredentialUnavailable("SQL editor service credential requires a secure sslmode")
+ return ManagedWarehousePostgresConnection(
+ host=credential.connect.host,
+ port=credential.connect.port,
+ database=credential.connect.database,
+ username=credential.credential_id,
+ password=credential.credential_secret,
+ sslmode=credential.connect.sslmode,
+ )
diff --git a/products/managed_warehouse/backend/migrations/0004_managedwarehousesourcelifecycle.py b/products/managed_warehouse/backend/migrations/0004_managedwarehousesourcelifecycle.py
new file mode 100644
index 000000000000..d780b85b575b
--- /dev/null
+++ b/products/managed_warehouse/backend/migrations/0004_managedwarehousesourcelifecycle.py
@@ -0,0 +1,32 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("managed_warehouse", "0003_remove_duckgres_batch_sink_state"),
+ ("posthog", "1304_organization_has_active_subscription"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="ManagedWarehouseSourceLifecycle",
+ fields=[
+ (
+ "organization",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ related_name="managed_warehouse_source_lifecycle",
+ serialize=False,
+ to="posthog.organization",
+ db_constraint=False,
+ ),
+ ),
+ ("generation", models.PositiveBigIntegerField(default=0)),
+ ("desired_active", models.BooleanField(default=True)),
+ ("legacy_conversion_generation", models.PositiveBigIntegerField(blank=True, null=True)),
+ ],
+ options={"db_table": "posthog_managedwarehousesourcelifecycle"},
+ ),
+ ]
diff --git a/products/managed_warehouse/backend/migrations/max_migration.txt b/products/managed_warehouse/backend/migrations/max_migration.txt
index ee613f55db27..83d513125aff 100644
--- a/products/managed_warehouse/backend/migrations/max_migration.txt
+++ b/products/managed_warehouse/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_remove_duckgres_batch_sink_state
+0004_managedwarehousesourcelifecycle
diff --git a/products/managed_warehouse/backend/models.py b/products/managed_warehouse/backend/models.py
index 316fdc6923cc..d66e3ac00c4a 100644
--- a/products/managed_warehouse/backend/models.py
+++ b/products/managed_warehouse/backend/models.py
@@ -74,6 +74,24 @@ class DuckgresServer(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
}
+class ManagedWarehouseSourceLifecycle(models.Model):
+ """Non-secret generation fence for managed SQL-editor source lifecycle operations."""
+
+ organization = models.OneToOneField(
+ "posthog.Organization",
+ on_delete=models.CASCADE,
+ primary_key=True,
+ related_name="managed_warehouse_source_lifecycle",
+ db_constraint=False,
+ )
+ generation = models.PositiveBigIntegerField(default=0)
+ desired_active = models.BooleanField(default=True)
+ legacy_conversion_generation = models.PositiveBigIntegerField(null=True, blank=True)
+
+ class Meta:
+ db_table = "posthog_managedwarehousesourcelifecycle"
+
+
@receiver(post_save, sender=DuckgresServer, dispatch_uid="observe_duckgres_server_save")
def _observe_duckgres_server_save(*, created: bool, **kwargs: object) -> None:
record_duckgres_server_access("create" if created else "update")
diff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.py
index 604625cb53e0..67337d79c317 100644
--- a/products/managed_warehouse/backend/presentation/views.py
+++ b/products/managed_warehouse/backend/presentation/views.py
@@ -266,6 +266,7 @@ def provision(
schema_name_error = _validate_schema_name(schema_name)
if schema_name_error or schema_name is None:
return Response({"error": schema_name_error or "schema_name is required"}, status=status.HTTP_400_BAD_REQUEST)
+ source_generation = _managed_source_generation(organization_id)
resp = _request(
"POST",
organization_id,
@@ -285,12 +286,23 @@ def provision(
require_enabled=require_enabled,
)
if status.is_success(resp.status_code) and isinstance(resp.data, dict):
+ activated_generation = _activate_managed_source_lifecycle(
+ organization_id,
+ expected_generation=source_generation,
+ )
+ if activated_generation is None:
+ logger.warning(
+ "Skipping stale managed warehouse provision completion",
+ organization_id=str(organization_id),
+ expected_generation=source_generation,
+ )
+ return resp
_invalidate_team_state_cache(organization_id)
_persist_duckgres_server(organization_id, database_name, resp.data)
# Complete the row BEFORE registering the team: registration kicks off the
# 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)
+ _register_provisioning_team(organization_id, team_id, activated_generation)
# The bucket is internal infra detail, persisted above and consumed by the
# backfill via cp_bucket_for — not part of the UI-facing ProvisionWarehouseResponse
# schema. Strip it so the response matches its OpenAPI contract.
@@ -350,7 +362,7 @@ def team_backfill_state(team_id: int) -> dict[str, object]:
return {"has_backfill": state.has_backfill, "table_suffix": state.table_suffix}
-def _register_provisioning_team(organization_id: UUID | str, team_id: int) -> None:
+def _register_provisioning_team(organization_id: UUID | str, team_id: int, source_generation: int) -> None:
"""Finish the provisioning (calling) team's onboarding after its row exists.
duckgres creates the provisioning team's row from the provision request itself (and
@@ -362,26 +374,84 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int) -> No
the one-time provision password is never lost to it.
"""
try:
- _ensure_direct_source(team_id, organization_id)
+ _ensure_direct_source(team_id, organization_id, source_generation)
_schedule_earliest_event_date_sync(team_id)
except Exception:
logger.exception("Failed to register provisioning team after provision", team_id=team_id)
-def _ensure_direct_source(team_id: int, organization_id: UUID | str) -> None:
- """Best-effort: create or refresh the team's external managed-warehouse source.
+def _active_managed_source_generation(organization_id: UUID | str) -> int | None:
+ from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
+ get_active_managed_warehouse_source_generation,
+ )
- This snapshots the stored DuckgresServer login. Project-reader provisioning has a
- separate lifecycle, and this path never creates or modifies one.
- """
+ return get_active_managed_warehouse_source_generation(organization_id=organization_id)
+
+
+def _managed_source_generation(organization_id: UUID | str) -> int:
+ from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
+ get_managed_warehouse_source_generation,
+ )
+
+ return get_managed_warehouse_source_generation(organization_id=organization_id)
+
+
+def _activate_managed_source_lifecycle(
+ organization_id: UUID | str,
+ *,
+ expected_generation: int,
+) -> int | None:
+ from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
+ activate_managed_warehouse_source_lifecycle,
+ )
+
+ return activate_managed_warehouse_source_lifecycle(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
+
+
+def _deactivate_managed_source_lifecycle(
+ organization_id: UUID | str,
+ *,
+ expected_generation: int,
+) -> int | None:
+ from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
+ deactivate_managed_warehouse_source_lifecycle,
+ )
+
+ return deactivate_managed_warehouse_source_lifecycle(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
+
+
+def _ensure_direct_source(team_id: int, organization_id: UUID | str, source_generation: int) -> None:
try:
from products.managed_warehouse.backend.facade.connection import ( # noqa: PLC0415
ensure_managed_warehouse_direct_source,
)
- ensure_managed_warehouse_direct_source(team_id=team_id, organization_id=organization_id)
+ ensure_managed_warehouse_direct_source(
+ team_id=team_id,
+ organization_id=organization_id,
+ expected_generation=source_generation,
+ )
except Exception:
logger.exception("Failed to register managed warehouse query source", team_id=team_id)
+ if settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED:
+ try:
+ from products.data_warehouse.backend.facade.api import ( # noqa: PLC0415
+ schedule_managed_warehouse_direct_source_ensure,
+ )
+
+ schedule_managed_warehouse_direct_source_ensure(
+ team_id=team_id,
+ organization_id=organization_id,
+ expected_generation=source_generation,
+ )
+ except Exception:
+ logger.exception("Failed to schedule managed warehouse query source recovery", team_id=team_id)
def _persist_duckgres_server(organization_id: UUID | str, database_name: str | None, body: dict) -> None:
@@ -596,6 +666,13 @@ def onboard_team(
status=status.HTTP_400_BAD_REQUEST,
)
+ source_generation = _active_managed_source_generation(organization_id)
+ if source_generation is None:
+ return Response(
+ {"error": "No managed warehouse is provisioned for this organization. Provision one first."},
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+
try:
existing = _get_project_team_row(organization_id=organization_id, team_id=team_id)
except RuntimeError:
@@ -638,7 +715,7 @@ def onboard_team(
if not status.is_success(resp.status_code):
return resp
- _ensure_direct_source(team_id, organization_id)
+ _ensure_direct_source(team_id, organization_id, source_generation)
_schedule_earliest_event_date_sync(team_id)
return Response({"onboarded": True, "schema_name": schema_name}, status=status.HTTP_200_OK)
@@ -762,29 +839,67 @@ def block_team_deletion(team_id: int, organization_id: UUID | str) -> str | None
def deprovision(organization_id: UUID | str, require_enabled: bool = True) -> Response:
+ expected_generation = _active_managed_source_generation(organization_id)
+ inactive_cleanup_generation = _managed_source_generation(organization_id) if expected_generation is None else None
resp = _request("POST", organization_id, "/deprovision", require_enabled=require_enabled)
- if status.is_success(resp.status_code):
- _invalidate_team_state_cache(organization_id)
- # 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.
+ control_plane_converged = status.is_success(resp.status_code) or resp.status_code == status.HTTP_404_NOT_FOUND
+ if not control_plane_converged and (
+ resp.status_code == status.HTTP_409_CONFLICT or resp.status_code >= status.HTTP_500_INTERNAL_SERVER_ERROR
+ ):
+ status_response = _request(
+ "GET",
+ organization_id,
+ "/warehouse/status",
+ require_enabled=False,
+ )
+ control_plane_converged = status_response.status_code == status.HTTP_404_NOT_FOUND or (
+ status_response.status_code == status.HTTP_200_OK
+ and isinstance(status_response.data, dict)
+ and status_response.data.get("state") in {"deleting", "deleted"}
+ )
+ if not control_plane_converged:
+ return resp
+ converged_response = (
+ resp
+ if status.is_success(resp.status_code)
+ else Response({"status": "deprovisioning started"}, status=status.HTTP_202_ACCEPTED)
+ )
+ _invalidate_team_state_cache(organization_id)
+ cleanup_generation = inactive_cleanup_generation
+ if expected_generation is not None:
try:
- _remove_direct_connection_sources(organization_id)
+ cleanup_generation = _deactivate_managed_source_lifecycle(
+ organization_id,
+ expected_generation=expected_generation,
+ )
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
+ logger.exception("Failed to record managed warehouse deprovision", organization_id=str(organization_id))
+ return Response(
+ {
+ "error": "The warehouse accepted deprovisioning, but its local SQL connection state was not updated. Retry deprovisioning."
+ },
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+ if cleanup_generation is None:
+ return converged_response
+ try:
+ _remove_direct_connection_sources(organization_id, cleanup_generation)
+ except Exception:
+ logger.exception("Failed to remove managed warehouse query sources", organization_id=str(organization_id))
+ try:
+ _schedule_remove_direct_connection_sources(organization_id, cleanup_generation)
+ 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 converged_response
def deprovision_for_org_deletion(organization_id: UUID | str) -> None:
@@ -798,8 +913,8 @@ def deprovision_for_org_deletion(organization_id: UUID | str) -> None:
No-op for orgs without a managed warehouse (mirrors ``block_team_deletion``'s gating,
so unrelated org deletions never touch the control plane). Idempotent against
- duckgres: 404 (warehouse unknown to the control plane) and 409 (teardown already
- started or finished — deprovision is not re-POSTable) are treated as converged. Any
+ duckgres: 404 means the warehouse is absent. A repeated deprovision that returns 409
+ is normalized to 202 only after status reports ``deleting`` or ``deleted``. Any
other failure raises so the Temporal activity retries: the org-record deletion (whose
cascade drops the ``DuckgresServer`` pointer) is conditional on this call being
accepted, so a persistent duckgres outage stalls the deletion workflow — visibly, and
@@ -821,7 +936,7 @@ def deprovision_for_org_deletion(organization_id: UUID | str) -> None:
organization_id=org_id,
)
return
- if resp.status_code in (status.HTTP_404_NOT_FOUND, status.HTTP_409_CONFLICT):
+ if resp.status_code == status.HTTP_404_NOT_FOUND:
logger.info(
"Managed warehouse already deprovisioned or unknown to duckgres; continuing organization deletion",
organization_id=org_id,
@@ -842,23 +957,29 @@ def deprovision_for_org_deletion(organization_id: UUID | str) -> None:
)
-def _remove_direct_connection_sources(organization_id: UUID | str) -> None:
+def _remove_direct_connection_sources(organization_id: UUID | str, expected_generation: int) -> None:
"""Soft-delete the org's auto-created Postgres query connections after deprovisioning."""
from products.managed_warehouse.backend.facade.connection import (
soft_delete_managed_warehouse_sources, # noqa: PLC0415
)
- soft_delete_managed_warehouse_sources(organization_id=organization_id)
+ soft_delete_managed_warehouse_sources(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
-def _schedule_remove_direct_connection_sources(organization_id: UUID | str) -> None:
+def _schedule_remove_direct_connection_sources(organization_id: UUID | str, expected_generation: int) -> 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)
+ schedule_soft_delete_managed_warehouse_sources(
+ organization_id=organization_id,
+ expected_generation=expected_generation,
+ )
def ensure_direct_connection_tables(team_id: int, organization_id: UUID | str) -> None:
diff --git a/products/managed_warehouse/backend/service_credentials.py b/products/managed_warehouse/backend/service_credentials.py
index ae01dd1d0c67..2429cabe26ea 100644
--- a/products/managed_warehouse/backend/service_credentials.py
+++ b/products/managed_warehouse/backend/service_credentials.py
@@ -96,6 +96,7 @@ def mint_service_credential(
*,
principal: str,
ttl_seconds: int = DEFAULT_CREDENTIAL_TTL_SECONDS,
+ timeout_seconds: int | None = None,
) -> ServiceCredential:
"""Mint a new org-scoped service credential for a short-lived job.
@@ -116,17 +117,23 @@ def mint_service_credential(
ttl_seconds = max(MIN_CREDENTIAL_TTL_SECONDS, min(ttl_seconds, MAX_CREDENTIAL_TTL_SECONDS))
+ request_kwargs: dict[str, Any] = {
+ "json_body": {
+ "principal": principal,
+ "ttl_seconds": ttl_seconds,
+ },
+ "require_enabled": False,
+ }
+ if timeout_seconds is not None:
+ request_kwargs["timeout"] = timeout_seconds
+
response = _request(
"POST",
organization_id,
"/service-credentials",
- json_body={
- "principal": principal,
- "ttl_seconds": ttl_seconds,
- },
# Backend caller: never gate on the user-facing data-warehouse feature
# flag (a dagster worker may not have the flag definition loaded).
- require_enabled=False,
+ **request_kwargs,
)
if not status.is_success(response.status_code):
raise ServiceCredentialUnavailable(
diff --git a/products/managed_warehouse/backend/tests/api/test_presentation.py b/products/managed_warehouse/backend/tests/api/test_presentation.py
index f611a1cd63d1..0b3d089ca6c3 100644
--- a/products/managed_warehouse/backend/tests/api/test_presentation.py
+++ b/products/managed_warehouse/backend/tests/api/test_presentation.py
@@ -14,6 +14,7 @@ from posthog.models import Organization, Team
from products.managed_warehouse.backend.facade.cp_teams import clear_team_membership_cache
from products.managed_warehouse.backend.models import DuckgresServer
from products.managed_warehouse.backend.presentation import views as managed_warehouse
+from products.warehouse_sources.backend.facade.models import ExternalDataSource
@pytest.fixture(autouse=True)
@@ -67,9 +68,15 @@ def test_reset_password_reports_local_persistence_failure(
@patch("products.data_warehouse.backend.facade.api.schedule_soft_delete_managed_warehouse_sources")
@patch("products.managed_warehouse.backend.facade.connection.soft_delete_managed_warehouse_sources")
+@patch("products.managed_warehouse.backend.presentation.views._deactivate_managed_source_lifecycle", return_value=7)
+@patch("products.managed_warehouse.backend.presentation.views._active_managed_source_generation", return_value=6)
@patch("products.managed_warehouse.backend.presentation.views._request")
def test_deprovision_schedules_cleanup_retry_when_inline_cleanup_fails(
- mock_request: MagicMock, mock_soft_delete: MagicMock, mock_schedule: MagicMock
+ mock_request: MagicMock,
+ _mock_active_generation: MagicMock,
+ _mock_deactivate: 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.
@@ -80,14 +87,21 @@ def test_deprovision_schedules_cleanup_retry_when_inline_cleanup_fails(
response = managed_warehouse.deprovision(organization_id)
assert response.status_code == 202
- mock_schedule.assert_called_once_with(organization_id=organization_id)
+ mock_soft_delete.assert_called_once_with(organization_id=organization_id, expected_generation=7)
+ mock_schedule.assert_called_once_with(organization_id=organization_id, expected_generation=7)
@patch("products.data_warehouse.backend.facade.api.schedule_soft_delete_managed_warehouse_sources")
@patch("products.managed_warehouse.backend.facade.connection.soft_delete_managed_warehouse_sources")
+@patch("products.managed_warehouse.backend.presentation.views._deactivate_managed_source_lifecycle", return_value=7)
+@patch("products.managed_warehouse.backend.presentation.views._active_managed_source_generation", return_value=6)
@patch("products.managed_warehouse.backend.presentation.views._request")
def test_deprovision_reports_when_cleanup_and_its_retry_cannot_be_scheduled(
- mock_request: MagicMock, mock_soft_delete: MagicMock, mock_schedule: MagicMock
+ mock_request: MagicMock,
+ _mock_active_generation: MagicMock,
+ _mock_deactivate: 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")
@@ -101,6 +115,111 @@ def test_deprovision_reports_when_cleanup_and_its_retry_cannot_be_scheduled(
}
+@patch("products.managed_warehouse.backend.presentation.views._remove_direct_connection_sources")
+@patch("products.managed_warehouse.backend.presentation.views._deactivate_managed_source_lifecycle", return_value=7)
+@patch("products.managed_warehouse.backend.presentation.views._active_managed_source_generation", return_value=6)
+@patch("products.managed_warehouse.backend.presentation.views._request")
+def test_deprovision_converges_locally_when_an_accepted_request_times_out(
+ mock_request: MagicMock,
+ _mock_active_generation: MagicMock,
+ mock_deactivate: MagicMock,
+ mock_remove_sources: MagicMock,
+) -> None:
+ organization_id = uuid4()
+ mock_request.side_effect = [
+ Response({"error": "timed out"}, status=504),
+ Response({"state": "deleting"}, status=200),
+ ]
+
+ response = managed_warehouse.deprovision(organization_id)
+
+ assert response.status_code == 202
+ mock_deactivate.assert_called_once_with(organization_id, expected_generation=6)
+ mock_remove_sources.assert_called_once_with(organization_id, 7)
+
+
+@patch("products.managed_warehouse.backend.presentation.views._remove_direct_connection_sources")
+@patch("products.managed_warehouse.backend.presentation.views._deactivate_managed_source_lifecycle", return_value=7)
+@patch("products.managed_warehouse.backend.presentation.views._active_managed_source_generation", return_value=6)
+@patch("products.managed_warehouse.backend.presentation.views._request")
+def test_deprovision_converges_locally_when_the_control_plane_reports_the_warehouse_absent(
+ mock_request: MagicMock,
+ _mock_active_generation: MagicMock,
+ mock_deactivate: MagicMock,
+ mock_remove_sources: MagicMock,
+) -> None:
+ organization_id = uuid4()
+ mock_request.return_value = Response({"error": "not found"}, status=404)
+
+ response = managed_warehouse.deprovision(organization_id)
+
+ assert response.status_code == 202
+ assert response.data == {"status": "deprovisioning started"}
+ mock_request.assert_called_once_with("POST", organization_id, "/deprovision", require_enabled=True)
+ mock_deactivate.assert_called_once_with(organization_id, expected_generation=6)
+ mock_remove_sources.assert_called_once_with(organization_id, 7)
+
+
+@patch("products.managed_warehouse.backend.presentation.views._remove_direct_connection_sources")
+@patch("products.managed_warehouse.backend.presentation.views._deactivate_managed_source_lifecycle")
+@patch("products.managed_warehouse.backend.presentation.views._active_managed_source_generation", return_value=6)
+@patch("products.managed_warehouse.backend.presentation.views._request")
+def test_deprovision_does_not_clean_up_on_a_genuine_conflict(
+ mock_request: MagicMock,
+ _mock_active_generation: MagicMock,
+ mock_deactivate: MagicMock,
+ mock_remove_sources: MagicMock,
+) -> None:
+ mock_request.side_effect = [
+ Response({"error": "conflict"}, status=409),
+ Response({"state": "ready"}, status=200),
+ ]
+
+ response = managed_warehouse.deprovision(uuid4())
+
+ assert response.status_code == 409
+ mock_deactivate.assert_not_called()
+ mock_remove_sources.assert_not_called()
+
+
+def test_deprovision_retry_after_local_cleanup_failure_converges_from_control_plane_status() -> None:
+ organization_id = uuid4()
+ with (
+ patch.object(
+ managed_warehouse,
+ "_request",
+ side_effect=[
+ Response({"status": "deprovisioning started"}, status=202),
+ Response({"error": "already deleting"}, status=409),
+ Response({"state": "deleting"}, status=200),
+ ],
+ ),
+ patch.object(managed_warehouse, "_active_managed_source_generation", side_effect=[6, None]),
+ patch.object(managed_warehouse, "_managed_source_generation", return_value=7),
+ patch.object(managed_warehouse, "_deactivate_managed_source_lifecycle", return_value=7) as deactivate,
+ patch.object(
+ managed_warehouse,
+ "_remove_direct_connection_sources",
+ side_effect=[RuntimeError("database unavailable"), None],
+ ) as remove_sources,
+ patch.object(
+ managed_warehouse,
+ "_schedule_remove_direct_connection_sources",
+ side_effect=RuntimeError("broker unavailable"),
+ ),
+ ):
+ first = managed_warehouse.deprovision(organization_id)
+ second = managed_warehouse.deprovision(organization_id)
+
+ assert first.status_code == 500
+ assert second.status_code == 202
+ deactivate.assert_called_once_with(organization_id, expected_generation=6)
+ assert remove_sources.call_args_list == [
+ ((organization_id, 7),),
+ ((organization_id, 7),),
+ ]
+
+
@pytest.mark.django_db
@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)
@patch("products.managed_warehouse.backend.presentation.views._request")
@@ -127,10 +246,53 @@ def test_provision_persists_duckgres_server_on_success(mock_request: MagicMock)
assert server.bucket_region is None
+def test_provision_captures_generation_before_request_and_skips_local_writes_if_activation_loses(
+ _onboarding_side_effects,
+) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ call_order: list[object] = []
+
+ def capture_generation(_organization_id) -> int:
+ call_order.append("capture")
+ return 7
+
+ def request(*_args, **_kwargs) -> Response:
+ call_order.append("request")
+ return Response(
+ {"status": "provisioning started", "org": str(org.id), "username": "root", "password": "secret"},
+ status=202,
+ )
+
+ def lose_activation(_organization_id, expected_generation: int) -> None:
+ call_order.append(("activate", expected_generation))
+ return None
+
+ with (
+ patch.object(managed_warehouse, "_managed_source_generation", side_effect=capture_generation),
+ patch.object(managed_warehouse, "_request", side_effect=request),
+ patch.object(managed_warehouse, "_activate_managed_source_lifecycle", side_effect=lose_activation),
+ patch.object(managed_warehouse, "_persist_duckgres_server") as persist,
+ patch.object(managed_warehouse, "_register_provisioning_team") as register,
+ ):
+ response = managed_warehouse.provision(org.id, "my-warehouse", team.id, "events")
+
+ assert response.status_code == 202
+ assert call_order == ["capture", "request", ("activate", 7)]
+ persist.assert_not_called()
+ register.assert_not_called()
+ _onboarding_side_effects.ensure.assert_not_called()
+ assert not DuckgresServer.objects.filter(organization_id=org.id).exists()
+ assert not ExternalDataSource._base_manager.filter(team_id=team.id).exists()
+
+
@pytest.mark.django_db
@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)
@patch("products.managed_warehouse.backend.presentation.views._request")
-def test_provision_sends_team_id_and_schema_name_to_control_plane(mock_request: MagicMock) -> None:
+def test_provision_sends_team_id_and_schema_name_to_control_plane(
+ mock_request: MagicMock, _onboarding_side_effects
+) -> None:
# The provisioning team becomes the warehouse's first team via the org-teams API:
# the outbound body carries team_id + schema_name and never default_team_id (dropped
# along with duckgres's whole default/billing-team concept).
@@ -160,6 +322,11 @@ def test_provision_sends_team_id_and_schema_name_to_control_plane(mock_request:
"persons_table_name": "persons_prod_events",
"schema_data_imports_name": "posthog_data_imports_prod_events",
}
+ _onboarding_side_effects.ensure.assert_called_once_with(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=1,
+ )
@pytest.mark.django_db
@@ -182,6 +349,36 @@ def test_provision_succeeds_even_when_the_team_row_completion_fails(mock_request
assert resp.status_code == 202
+@override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True)
+@patch("products.data_warehouse.backend.facade.api.schedule_managed_warehouse_direct_source_ensure")
+@patch("products.managed_warehouse.backend.presentation.views._request")
+def test_provision_schedules_generation_fenced_source_recovery_when_inline_ensure_fails(
+ mock_request: MagicMock,
+ mock_schedule_ensure: MagicMock,
+ _onboarding_side_effects,
+) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ mock_request.side_effect = [
+ Response(
+ {"status": "provisioning started", "org": str(org.id), "username": "root", "password": "secret"},
+ status=202,
+ ),
+ Response({"team_id": team.id, "schema_name": "events"}, status=200),
+ ]
+ _onboarding_side_effects.ensure.side_effect = RuntimeError("database unavailable")
+
+ response = managed_warehouse.provision(org.id, "my-warehouse", team.id, "events")
+
+ assert response.status_code == 202
+ mock_schedule_ensure.assert_called_once_with(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=1,
+ )
+
+
@parameterized.expand(
[
("US", "posthog-duckling-0194d6405db400006cde48d6114c0f99-mw-prod-us", "us-east-1"),
@@ -236,7 +433,11 @@ def test_provision_registers_calling_team_only(mock_request: MagicMock, _onboard
# The control plane creates the provisioning team's row from the provision request itself;
# locally only that team gets its query connection and earliest-date sync kicked off.
- _onboarding_side_effects.ensure.assert_called_once_with(team_id=team.id, organization_id=org.id)
+ _onboarding_side_effects.ensure.assert_called_once_with(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=1,
+ )
_onboarding_side_effects.task.delay.assert_called_once_with(team.id)
@@ -539,10 +740,42 @@ def test_onboard_team_creates_duckgres_row_with_legacy_names(
"schema_data_imports_name": "posthog_data_imports_my_events",
}
# Onboarding's tail: the query connection and the earliest-date sync.
- _onboarding_side_effects.ensure.assert_called_once_with(team_id=team.id, organization_id=org.id)
+ _onboarding_side_effects.ensure.assert_called_once_with(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=0,
+ )
_onboarding_side_effects.task.delay.assert_called_once_with(team.id)
+@override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True)
+@patch("products.data_warehouse.backend.facade.api.schedule_managed_warehouse_direct_source_ensure")
+@patch("products.managed_warehouse.backend.presentation.views.is_enabled", return_value=True)
+@patch("products.managed_warehouse.backend.presentation.views._request")
+def test_onboard_team_schedules_generation_fenced_source_recovery_when_inline_ensure_fails(
+ mock_request: MagicMock,
+ _mock_enabled: MagicMock,
+ mock_schedule_ensure: MagicMock,
+ _onboarding_side_effects,
+) -> None:
+ org, team, _ = _provisioned_org()
+ mock_request.side_effect = [
+ Response({"teams": []}, status=200),
+ Response({"team_id": team.id, "schema_name": "my_events"}, status=200),
+ ]
+ _onboarding_side_effects.ensure.side_effect = RuntimeError("database unavailable")
+
+ response = managed_warehouse.onboard_team(org.id, team.id, "my_events")
+
+ assert response.status_code == 200
+ mock_schedule_ensure.assert_called_once_with(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=0,
+ )
+
+
@pytest.mark.django_db
@patch("products.managed_warehouse.backend.presentation.views.is_enabled", return_value=True)
@patch("products.managed_warehouse.backend.presentation.views._request")
@@ -617,7 +850,11 @@ def test_onboard_team_same_name_is_idempotent(
assert resp.status_code == 200
assert resp.data == {"onboarded": True, "schema_name": "first"}
assert [c.args[0] for c in mock_request.call_args_list] == ["GET"]
- _onboarding_side_effects.ensure.assert_called_once_with(team_id=team.id, organization_id=org.id)
+ _onboarding_side_effects.ensure.assert_called_once_with(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=0,
+ )
@pytest.mark.django_db
@@ -933,7 +1170,6 @@ def test_deprovision_for_org_deletion_deprovisions_the_orgs_warehouse(mock_depro
@parameterized.expand(
[
("unknown_to_duckgres", 404),
- ("teardown_already_started", 409),
("provisioning_api_not_configured", 501),
]
)
@@ -942,8 +1178,7 @@ def test_deprovision_for_org_deletion_deprovisions_the_orgs_warehouse(mock_depro
def test_deprovision_for_org_deletion_treats_converged_states_as_done(
_name: str, cp_status: int, mock_deprovision: MagicMock
) -> None:
- # 404 (no warehouse in duckgres), 409 (teardown already started/finished — deprovision is not
- # re-POSTable), and 501 (no provisioning API configured) all mean there is nothing to start.
+ # 404 (no warehouse in duckgres) and 501 (no provisioning API configured) mean there is nothing to start.
org, _team, _server = _provisioned_org()
mock_deprovision.return_value = Response({"error": "nope"}, status=cp_status)
diff --git a/products/managed_warehouse/backend/tests/test_connection.py b/products/managed_warehouse/backend/tests/test_connection.py
index 5c39ea12179d..2882778f8d1f 100644
--- a/products/managed_warehouse/backend/tests/test_connection.py
+++ b/products/managed_warehouse/backend/tests/test_connection.py
@@ -1,8 +1,12 @@
+from copy import deepcopy
from typing import TypedDict
import pytest
from unittest.mock import MagicMock, patch
+from django.db.models import OneToOneField
+from django.test import override_settings
+
from parameterized import parameterized
from posthog.hogql.direct_connection import get_direct_connection_source
@@ -12,19 +16,32 @@ from posthog.models import Organization, Team
from products.data_warehouse.backend.facade.api import DIRECT_POSTGRES_URL_PATTERN
from products.data_warehouse.backend.facade.tasks import reconcile_all_managed_warehouse_tables_task
+from products.data_warehouse.backend.tasks.tasks import (
+ ensure_managed_warehouse_direct_source_v2_task,
+ schedule_managed_warehouse_direct_source_ensure,
+ schedule_soft_delete_managed_warehouse_sources,
+ soft_delete_managed_warehouse_sources_task,
+ soft_delete_managed_warehouse_sources_v2_task,
+)
from products.managed_warehouse.backend.facade.contracts import (
+ ManagedWarehousePostgresConnection,
ManagedWarehouseTableNames,
ManagedWarehouseTeamMembership,
)
from products.managed_warehouse.backend.logic.connection import (
MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ activate_managed_warehouse_source_lifecycle,
+ deactivate_managed_warehouse_source_lifecycle,
ensure_managed_warehouse_direct_source,
+ get_active_managed_warehouse_source_generation,
+ get_managed_warehouse_source_generation,
internal_schemas,
reconcile_managed_warehouse_tables,
+ soft_delete_legacy_managed_warehouse_sources,
soft_delete_managed_warehouse_sources,
update_managed_warehouse_root_password,
)
-from products.managed_warehouse.backend.models import DuckgresServer
+from products.managed_warehouse.backend.models import DuckgresServer, ManagedWarehouseSourceLifecycle
from products.managed_warehouse.backend.presentation import views as managed_warehouse
from products.warehouse_sources.backend.facade.models import (
MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
@@ -33,6 +50,7 @@ from products.warehouse_sources.backend.facade.models import (
ExternalDataSource,
)
from products.warehouse_sources.backend.facade.source_management import SourceSchema
+from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.postgres import (
PostgresSourceConfig,
)
@@ -112,7 +130,30 @@ def _cp_memberships():
def _ensure(team: Team) -> ExternalDataSource:
- return ensure_managed_warehouse_direct_source(team_id=team.id, organization_id=team.organization_id)
+ current_generation = get_managed_warehouse_source_generation(organization_id=team.organization_id)
+ generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=team.organization_id,
+ expected_generation=current_generation,
+ )
+ assert generation is not None
+ source = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=team.organization_id,
+ expected_generation=generation,
+ )
+ assert source is not None
+ return source
+
+
+def _cleanup(org: Organization) -> None:
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+ generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert generation is not None
+ soft_delete_managed_warehouse_sources(organization_id=org.id, expected_generation=generation)
def _create_server(org: Organization, **overrides: object) -> DuckgresServer:
@@ -177,19 +218,68 @@ def _create_stored_login_source(team: Team) -> ExternalDataSource:
)
+def _create_dynamic_source(team: Team, *, lifecycle_generation: int = 1) -> ExternalDataSource:
+ return ExternalDataSource.objects.create(
+ team=team,
+ source_id=f"dynamic-source-{team.id}",
+ connection_id=f"dynamic-connection-{team.id}",
+ destination_id=f"dynamic-destination-{team.id}",
+ status=ExternalDataSource.Status.RUNNING,
+ source_type="Postgres",
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ access_method=ExternalDataSource.AccessMethod.DIRECT,
+ direct_query_enabled=True,
+ job_inputs={},
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": lifecycle_generation,
+ },
+ )
+
+
@pytest.mark.django_db
class TestEnsureManagedWarehouseDirectSource:
- def test_creates_a_stored_login_source_when_project_reader_is_missing(self) -> None:
+ @pytest.fixture(autouse=True)
+ def _enable_dynamic_auth(self, settings) -> None:
+ settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED = True
+
+ def test_creates_a_secretless_service_source_when_no_compatibility_source_exists(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
source = _ensure(team)
- assert source.is_legacy_managed_warehouse
+ assert source.is_dynamic_managed_warehouse
+ assert source.job_inputs == {}
+ assert isinstance(source.connection_metadata, dict)
+ assert source.connection_metadata["lifecycle_generation"] == 1
assert ExternalDataSource.objects.filter(team_id=team.id).count() == 1
- def test_creates_a_stored_login_source_without_overwriting_a_project_reader(self) -> None:
+ def test_explicit_ensure_scrubs_secrets_and_credential_ids_from_an_existing_dynamic_source(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = _create_dynamic_source(team)
+ source.job_inputs = {"password": "must-not-persist"}
+ assert isinstance(source.connection_metadata, dict)
+ source.connection_metadata = {**source.connection_metadata, "credential_id": "svc_must_not_persist"}
+ source.save(update_fields=["job_inputs", "connection_metadata"])
+
+ ensured = _ensure(team)
+
+ ensured.refresh_from_db()
+ assert ensured.id == source.id
+ assert ensured.job_inputs == {}
+ assert ensured.connection_metadata == {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ }
+
+ def test_preserves_a_project_reader_in_place_without_creating_a_new_source(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
@@ -202,54 +292,94 @@ class TestEnsureManagedWarehouseDirectSource:
source.refresh_from_db()
reader.refresh_from_db()
- assert source.id != reader.id
- assert source.description == "Managed warehouse (auto-provisioned)"
- assert source.access_method == ExternalDataSource.AccessMethod.DIRECT
- assert source.direct_query_enabled is True
- assert isinstance(source.job_inputs, dict)
- assert {key: source.job_inputs[key] for key in ("host", "port", "database", "user", "password")} == {
- "host": _CONNECTION["host"],
- "port": str(_CONNECTION["port"]),
- "database": _CONNECTION["database"],
- "user": _CONNECTION["username"],
- "password": _CONNECTION["password"],
- }
- assert source.connection_metadata == {
- "engine": "duckdb",
- "system_managed": True,
- "credential_kind": "org_root",
- }
+ assert source.id == reader.id
assert reader.job_inputs == original_reader_inputs
assert reader.is_managed_warehouse_ready
- def test_refreshes_the_existing_stored_login_source(self) -> None:
+ def test_existing_active_static_source_is_grandfathered_byte_for_byte(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org, password="new-password")
reader = _create_project_reader_source(team)
source = _create_stored_login_source(team)
source.job_inputs = {**(source.job_inputs or {}), "password": "stale-password"}
- source.access_method = ExternalDataSource.AccessMethod.WAREHOUSE
- source.direct_query_enabled = False
- source.deleted = True
- source.save(update_fields=["job_inputs", "access_method", "direct_query_enabled", "deleted"])
+ source.save(update_fields=["job_inputs"])
+ source.refresh_from_db()
+ original_inputs = deepcopy(source.job_inputs)
+ original_metadata = deepcopy(source.connection_metadata)
refreshed = _ensure(team)
refreshed.refresh_from_db()
reader.refresh_from_db()
assert refreshed.id == source.id
- assert isinstance(refreshed.job_inputs, dict)
- assert refreshed.job_inputs["password"] == "new-password"
- assert refreshed.access_method == ExternalDataSource.AccessMethod.DIRECT
- assert refreshed.direct_query_enabled is True
- assert refreshed.deleted is False
- assert isinstance(refreshed.connection_metadata, dict)
- assert refreshed.connection_metadata["credential_kind"] == "org_root"
+ assert refreshed.job_inputs == original_inputs
+ assert refreshed.connection_metadata == original_metadata
assert isinstance(reader.job_inputs, dict)
assert reader.job_inputs["password"] == _PROJECT_READER_PASSWORD
assert reader.is_managed_warehouse_ready
+ def test_new_active_generation_converts_static_source_left_by_failed_cleanup(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ static_source = _create_stored_login_source(team)
+ first_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ active_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=first_generation,
+ )
+ assert active_generation is not None
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert cleanup_generation is not None
+
+ converted = _ensure(team)
+
+ assert converted.id == static_source.id
+ assert converted.is_dynamic_managed_warehouse
+ assert converted.job_inputs == {}
+
+ @parameterized.expand([(False,), (True,)])
+ def test_new_active_generation_replaces_a_project_reader_left_by_failed_cleanup(
+ self, with_static_source: bool
+ ) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ reader = _create_project_reader_source(team)
+ reader_table = DataWarehouseTable.objects.create(
+ team=team,
+ name="reader_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=DIRECT_POSTGRES_URL_PATTERN,
+ external_data_source=reader,
+ columns={},
+ )
+ static_source = _create_stored_login_source(team) if with_static_source else None
+ first_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ active_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=first_generation,
+ )
+ assert active_generation is not None
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert cleanup_generation is not None
+
+ replacement = _ensure(team)
+
+ reader.refresh_from_db()
+ reader_table.refresh_from_db()
+ assert reader.deleted
+ assert reader_table.deleted
+ assert replacement.is_dynamic_managed_warehouse
+ if static_source is not None:
+ assert replacement.id == static_source.id
+ assert replacement.id != reader.id
+
def test_missing_server_does_not_modify_a_ready_project_reader(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
@@ -269,8 +399,7 @@ class TestEnsureManagedWarehouseDirectSource:
original_job_inputs = dict(source.job_inputs)
original_metadata = dict(source.connection_metadata)
- with pytest.raises(DuckgresServer.DoesNotExist):
- _ensure(team)
+ assert _ensure(team).id == source.id
source.refresh_from_db()
assert source.job_inputs == original_job_inputs
@@ -284,7 +413,7 @@ class TestEnsureManagedWarehouseDirectSource:
(True, False),
]
)
- def test_creates_legacy_without_promoting_or_replacing_an_unready_project_reader(
+ def test_creates_dynamic_without_promoting_or_replacing_an_unready_project_reader(
self, reader_configured: bool, direct_query_enabled: bool
) -> None:
org = Organization.objects.create(name="Org")
@@ -299,17 +428,125 @@ class TestEnsureManagedWarehouseDirectSource:
assert isinstance(source.job_inputs, dict)
original_job_inputs = dict(source.job_inputs)
- legacy_source = _ensure(team)
+ dynamic_source = _ensure(team)
source.refresh_from_db()
- assert legacy_source.id != source.id
- assert legacy_source.is_legacy_managed_warehouse
+ assert dynamic_source.id != source.id
+ assert dynamic_source.is_dynamic_managed_warehouse
+ assert dynamic_source.job_inputs == {}
assert source.job_inputs == original_job_inputs
assert isinstance(source.connection_metadata, dict)
assert source.connection_metadata["reader_configured"] is reader_configured
assert source.direct_query_enabled is direct_query_enabled
+class TestDynamicSourceCreationGate:
+ @override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False)
+ def test_gate_off_preserves_the_static_stored_login_source(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+
+ source = _ensure(team)
+
+ assert source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL
+ assert isinstance(source.connection_metadata, dict)
+ assert isinstance(source.job_inputs, dict)
+ assert source.connection_metadata["credential_kind"] == "org_root"
+ assert source.job_inputs["host"] == _CONNECTION["host"]
+ assert source.job_inputs["user"] == _CONNECTION["username"]
+ assert source.job_inputs["password"] == _CONNECTION["password"]
+
+ def test_gate_off_preserves_an_existing_dynamic_source_without_persisting_the_root_secret(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org, password="must-not-be-copied")
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True):
+ source = _ensure(team)
+ source.refresh_from_db()
+ original_metadata = deepcopy(source.connection_metadata)
+ original_job_inputs = deepcopy(source.job_inputs)
+ original_updated_at = source.updated_at
+ generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert generation is not None
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
+ ensured = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=generation,
+ )
+
+ assert ensured is not None
+ assert ensured.id == source.id
+ ensured.refresh_from_db()
+ assert ensured.connection_metadata == original_metadata
+ assert ensured.job_inputs == original_job_inputs == {}
+ assert ensured.updated_at == original_updated_at
+
+ def test_gate_off_genuine_reprovision_updates_dynamic_generation_and_tombstones_stale_reader(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org, password="must-not-be-copied")
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True):
+ dynamic = _ensure(team)
+ reader = _create_project_reader_source(team)
+ reader_table = DataWarehouseTable.objects.create(
+ team=team,
+ name="reader_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=DIRECT_POSTGRES_URL_PATTERN,
+ external_data_source=reader,
+ columns={},
+ )
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+ inactive_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert inactive_generation is not None
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
+ reprovisioned = _ensure(team)
+
+ assert reprovisioned.id == dynamic.id
+ assert reprovisioned.is_dynamic_managed_warehouse
+ assert reprovisioned.job_inputs == {}
+ assert isinstance(reprovisioned.connection_metadata, dict)
+ assert reprovisioned.connection_metadata["lifecycle_generation"] == inactive_generation + 1
+ assert "must-not-be-copied" not in str(reprovisioned.job_inputs)
+ reader.refresh_from_db()
+ reader_table.refresh_from_db()
+ assert reader.deleted is True
+ assert reader_table.deleted is True
+
+ def test_gate_off_genuine_reprovision_tombstones_stale_reader_before_creating_static_source(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+ reader = _create_project_reader_source(team)
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+ inactive_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert inactive_generation is not None
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
+ replacement = _ensure(team)
+
+ reader.refresh_from_db()
+ assert reader.deleted is True
+ assert replacement.id != reader.id
+ assert replacement.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL
+ assert isinstance(replacement.connection_metadata, dict)
+ assert replacement.connection_metadata["credential_kind"] == "org_root"
+
+
def _source_schema(table_name: str, source_schema: str = "posthog") -> SourceSchema:
return SourceSchema(
name=f"{source_schema}.{table_name}",
@@ -323,10 +560,15 @@ def _source_schema(table_name: str, source_schema: str = "posthog") -> SourceSch
@pytest.mark.django_db
class TestReconcileManagedWarehouseTables:
+ @pytest.fixture(autouse=True)
+ def _enable_dynamic_auth(self, settings) -> None:
+ settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED = True
+
def _setup(self) -> tuple[Organization, Team]:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
+ _create_project_reader_source(team)
_add_membership(team)
return org, team
@@ -446,6 +688,59 @@ class TestReconcileManagedWarehouseTables:
assert ExternalDataSchema.objects.filter(source=stored_login, name="posthog.events").exists()
assert ExternalDataSchema.objects.filter(source=reader, name="posthog.events").exists()
+ def test_reconciles_dynamic_reader_and_static_catalogs_independently(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ dynamic = _create_dynamic_source(team)
+ reader = _create_project_reader_source(team)
+ stored_login = _create_stored_login_source(team)
+ seen_users: list[str] = []
+
+ dynamic.refresh_from_db()
+ reader.refresh_from_db()
+ stored_login.refresh_from_db()
+ assert dynamic.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN
+ assert reader.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN
+ assert stored_login.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL
+
+ dynamic_connection = ManagedWarehousePostgresConnection(
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username="svc_discovery",
+ password="service-secret",
+ sslmode="require",
+ )
+
+ def resolve_connection_for_source(
+ *, source_auth: object, **_kwargs: object
+ ) -> ManagedWarehousePostgresConnection | None:
+ return dynamic_connection if getattr(source_auth, "credential_kind", None) == "duckgres_service" else None
+
+ def discover(config: PostgresSourceConfig, *_args: object, **_kwargs: object) -> list[SourceSchema]:
+ seen_users.append(config.user)
+ return [_source_schema(f"events_{config.user}")]
+
+ with (
+ patch(
+ "products.managed_warehouse.backend.logic.connection.resolve_managed_warehouse_postgres_connection",
+ side_effect=resolve_connection_for_source,
+ ) as resolve_connection_mock,
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ side_effect=discover,
+ ),
+ ):
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ assert set(seen_users) == {"svc_discovery", f"posthog_team_{team.id}", _CONNECTION["username"]}
+ assert resolve_connection_mock.call_args.kwargs["principal"] == (
+ f"posthog:sql-editor-schema-discovery:team:{team.id}"
+ )
+ assert ExternalDataSchema.objects.filter(source=dynamic).exists()
+ assert ExternalDataSchema.objects.filter(source=reader).exists()
+ assert ExternalDataSchema.objects.filter(source=stored_login).exists()
+
def test_legacy_introspection_failure_does_not_block_ready_reader_reconciliation(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
@@ -468,33 +763,36 @@ class TestReconcileManagedWarehouseTables:
assert not ExternalDataSchema.objects.filter(source=stored_login).exists()
assert ExternalDataSchema.objects.filter(source=reader, name="posthog.events").exists()
- @parameterized.expand([("external", False), ("built_in", True)])
- def test_reconciles_after_reprovision_with_another_mode_tombstoned(
- self, _name: str, revive_project_reader: bool
- ) -> None:
+ def test_genuine_reprovision_reconciles_converted_dynamic_source_without_reviving_reader(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
reader = _create_project_reader_source(team)
- stored_login = _create_stored_login_source(team)
- soft_delete_managed_warehouse_sources(organization_id=org.id)
+ _create_stored_login_source(team)
+ _cleanup(org)
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
- return_value=[_source_schema("events")],
- ) as get_schemas:
+ with (
+ patch(
+ "products.managed_warehouse.backend.logic.connection.resolve_managed_warehouse_postgres_connection",
+ return_value=ManagedWarehousePostgresConnection(
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username="svc_discovery",
+ password="service-secret",
+ sslmode="require",
+ ),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ return_value=[_source_schema("events")],
+ ) as get_schemas,
+ ):
reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
get_schemas.assert_not_called()
- if revive_project_reader:
- reader.deleted = False
- reader.deleted_at = None
- reader.save(update_fields=["deleted", "deleted_at", "updated_at"])
- revived_source = reader
- tombstoned_source = stored_login
- else:
- revived_source = _ensure(team)
- tombstoned_source = reader
+ revived_source = _ensure(team)
+ tombstoned_source = reader
reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
revived_source.refresh_from_db()
@@ -512,7 +810,7 @@ class TestReconcileManagedWarehouseTables:
(True, False),
]
)
- def test_unready_reader_does_not_block_legacy_reconciliation(
+ def test_unready_reader_does_not_block_dynamic_reconciliation(
self, reader_configured: bool, direct_query_enabled: bool
) -> None:
org = Organization.objects.create(name="Org")
@@ -523,6 +821,7 @@ class TestReconcileManagedWarehouseTables:
reader_configured=reader_configured,
direct_query_enabled=direct_query_enabled,
)
+ dynamic_source = _ensure(team)
seen_users: list[str] = []
@@ -530,18 +829,27 @@ class TestReconcileManagedWarehouseTables:
seen_users.append(config.user)
return [_source_schema("events")]
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
- side_effect=discover,
+ with (
+ patch(
+ "products.managed_warehouse.backend.logic.connection.resolve_managed_warehouse_postgres_connection",
+ return_value=ManagedWarehousePostgresConnection(
+ host=_CONNECTION["host"],
+ port=_CONNECTION["port"],
+ database=_CONNECTION["database"],
+ username="svc_discovery",
+ password="service-secret",
+ sslmode="require",
+ ),
+ ),
+ patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ side_effect=discover,
+ ),
):
reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
- legacy_source = ExternalDataSource.objects.get(
- team_id=team.id,
- connection_metadata__credential_kind="org_root",
- )
- assert seen_users == [_CONNECTION["username"]]
- assert ExternalDataSchema.objects.filter(source=legacy_source, name="posthog.events").exists()
+ assert seen_users == ["svc_discovery"]
+ assert ExternalDataSchema.objects.filter(source=dynamic_source, name="posthog.events").exists()
assert not ExternalDataSchema.objects.filter(source=reader).exists()
def test_successful_internal_only_discovery_clears_stale_catalog(self) -> None:
@@ -679,6 +987,125 @@ class TestReconcileManagedWarehouseTables:
schedule.assert_not_called()
+ def test_periodic_reconcile_does_not_create_a_missing_connection(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+
+ 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._base_manager.filter(
+ team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX
+ ).exists()
+ get_schemas.assert_not_called()
+
+ def test_gate_off_periodic_reconcile_recovers_a_static_source_after_inline_setup_failed(self, settings) -> None:
+ settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED = False
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+ generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ active_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=generation,
+ )
+ assert active_generation is not None
+ assert not ExternalDataSource._base_manager.filter(
+ team_id=team.id,
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ ).exists()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ return_value=[],
+ ):
+ 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.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL
+ assert isinstance(source.connection_metadata, dict)
+ assert source.connection_metadata["credential_kind"] == "org_root"
+ assert isinstance(source.job_inputs, dict)
+ assert source.job_inputs["password"] == _CONNECTION["password"]
+
+ def test_gate_off_periodic_reconcile_does_not_revive_an_unfenced_legacy_tombstone(self, settings) -> None:
+ settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED = False
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+ source = _create_stored_login_source(team)
+ source.deleted = True
+ source.save(update_fields=["deleted", "updated_at"])
+ assert not ManagedWarehouseSourceLifecycle.objects.filter(organization=org).exists()
+
+ 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
+ get_schemas.assert_not_called()
+
+ def test_cleanup_before_periodic_reconcile_does_not_revive_the_source(self) -> None:
+ org, team = self._setup()
+ _cleanup(org)
+
+ 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 = ExternalDataSource._base_manager.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ assert source.deleted is True
+ get_schemas.assert_not_called()
+
+ def test_cleanup_during_introspection_wins_before_catalog_registration(self) -> None:
+ org, team = self._setup()
+
+ def discover_after_cleanup(*_args: object, **_kwargs: object) -> list[SourceSchema]:
+ _cleanup(org)
+ return [_source_schema("events")]
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ side_effect=discover_after_cleanup,
+ ):
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ source = ExternalDataSource._base_manager.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ assert source.deleted is True
+ assert not ExternalDataSchema.objects.filter(source_id=source.id).exists()
+
+ def test_deprovision_and_reprovision_during_introspection_invalidates_the_discovery_generation(self) -> None:
+ org, team = self._setup()
+ source = ExternalDataSource.objects.get(team_id=team.id, prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
+ initial_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert initial_generation is not None
+
+ def discover_across_reprovision(*_args: object, **_kwargs: object) -> list[SourceSchema]:
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=initial_generation,
+ )
+ assert cleanup_generation is not None
+ reprovision_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=cleanup_generation,
+ )
+ assert reprovision_generation is not None
+ return [_source_schema("events")]
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ side_effect=discover_across_reprovision,
+ ):
+ reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
+
+ assert not ExternalDataSchema.objects.filter(source=source, name="posthog.events").exists()
+
def test_reconciles_for_a_legacy_shared_tables_team(self) -> None:
org, team = self._setup()
_clear_memberships()
@@ -713,6 +1140,10 @@ class TestReconcileManagedWarehouseTables:
@pytest.mark.django_db
class TestManagedWarehouseLifecycle:
+ @pytest.fixture(autouse=True)
+ def _enable_dynamic_auth(self, settings) -> None:
+ settings.MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED = True
+
def _org_team_source(self) -> tuple[Organization, Team, ExternalDataSource, DuckgresServer]:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
@@ -738,7 +1169,7 @@ class TestManagedWarehouseLifecycle:
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)
+ _cleanup(org)
update_managed_warehouse_root_password(organization_id=org.id, password="rotated")
@@ -760,7 +1191,7 @@ class TestManagedWarehouseLifecycle:
options={},
)
- soft_delete_managed_warehouse_sources(organization_id=org.id)
+ _cleanup(org)
source.refresh_from_db()
table.refresh_from_db()
@@ -780,6 +1211,68 @@ class TestManagedWarehouseLifecycle:
)
get_schemas.assert_not_called()
+ def test_rapid_deprovision_and_reprovision_updates_the_dynamic_source_generation(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+ source = _ensure(team)
+ assert isinstance(source.connection_metadata, dict)
+ first_generation = source.connection_metadata["lifecycle_generation"]
+
+ _cleanup(org)
+ reprovisioned = _ensure(team)
+
+ assert reprovisioned.id == source.id
+ assert isinstance(reprovisioned.connection_metadata, dict)
+ assert reprovisioned.connection_metadata["lifecycle_generation"] > first_generation
+
+ def test_delayed_legacy_cleanup_cannot_delete_a_genuinely_reprovisioned_source(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+ original = _ensure(team)
+ _cleanup(org)
+ reprovisioned = _ensure(team)
+ assert reprovisioned.id == original.id
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
+ soft_delete_legacy_managed_warehouse_sources(organization_id=org.id)
+
+ reprovisioned.refresh_from_db()
+ assert reprovisioned.deleted is False
+ assert reprovisioned.is_dynamic_managed_warehouse
+
+ def test_legacy_cleanup_uses_the_current_inactive_generation(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ _create_server(org)
+ source = _ensure(team)
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert cleanup_generation is not None
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
+ soft_delete_legacy_managed_warehouse_sources(organization_id=org.id)
+
+ source.refresh_from_db()
+ assert source.deleted is True
+
+ def test_legacy_cleanup_remains_unconditional_for_an_org_without_lifecycle_state(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = _create_stored_login_source(team)
+ assert not ManagedWarehouseSourceLifecycle.objects.filter(organization=org).exists()
+
+ with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
+ soft_delete_legacy_managed_warehouse_sources(organization_id=org.id)
+
+ source.refresh_from_db()
+ assert source.deleted is True
+
def test_soft_delete_is_atomic_across_all_organization_sources(self) -> None:
org = Organization.objects.create(name="Org")
_create_server(org)
@@ -798,12 +1291,189 @@ class TestManagedWarehouseLifecycle:
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)
+ _cleanup(org)
source_a.refresh_from_db()
source_b.refresh_from_db()
assert source_a.deleted is False
assert source_b.deleted is False
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.get(organization_id=org.id)
+ assert lifecycle.desired_active is False
+ assert lifecycle.generation > 0
+
+ def test_cleanup_invalidates_an_ensure_that_started_before_deprovision(self) -> None:
+ org, team, source, _server = self._org_team_source()
+ generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert generation is not None
+
+ _cleanup(org)
+ stale_result = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=generation,
+ )
+
+ source.refresh_from_db()
+ assert stale_result is None
+ assert source.deleted is True
+
+ def test_successful_ensure_before_cleanup_is_tombstoned_by_cleanup(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert generation is not None
+
+ source = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=generation,
+ )
+ _cleanup(org)
+
+ assert source is not None
+ source.refresh_from_db()
+ assert source.deleted is True
+
+ def test_repeated_deactivation_reuses_the_same_cleanup_generation(self) -> None:
+ org = Organization.objects.create(name="Org")
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+
+ first_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert first_generation is not None
+ second_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=first_generation,
+ )
+
+ assert second_generation == first_generation
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.get(organization_id=org.id)
+ assert lifecycle.desired_active is False
+ assert lifecycle.generation == first_generation
+
+ def test_deactivation_only_advances_the_captured_active_generation(self) -> None:
+ org = Organization.objects.create(name="Org")
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+
+ lost = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation + 1,
+ )
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.get(organization_id=org.id)
+
+ assert lost is None
+ assert lifecycle.desired_active
+ assert lifecycle.generation == active_generation
+
+ def test_late_provision_activation_cannot_overwrite_a_newer_deprovision(self) -> None:
+ org = Organization.objects.create(name="Org")
+ provision_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=provision_generation,
+ )
+
+ activated_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=provision_generation,
+ )
+
+ assert cleanup_generation is not None
+ assert activated_generation is None
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.get(organization_id=org.id)
+ assert lifecycle.desired_active is False
+ assert lifecycle.generation == cleanup_generation
+
+ def test_genuine_reprovision_conditionally_activates_the_inactive_generation(self) -> None:
+ org = Organization.objects.create(name="Org")
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ provision_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+
+ activated_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=provision_generation,
+ )
+
+ assert cleanup_generation == provision_generation
+ assert provision_generation is not None
+ assert activated_generation == provision_generation + 1
+ lifecycle = ManagedWarehouseSourceLifecycle.objects.get(organization_id=org.id)
+ assert lifecycle.desired_active is True
+ assert lifecycle.generation == activated_generation
+
+ def test_old_cleanup_retry_cannot_delete_a_genuine_reprovision_after_failed_cleanup(self) -> None:
+ org, team, source, _server = self._org_team_source()
+ source.job_inputs = {"user": "root", "password": "grandfathered"}
+ source.connection_metadata = {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "org_root",
+ }
+ source.save(update_fields=["job_inputs", "connection_metadata", "updated_at"])
+ active_generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert active_generation is not None
+ cleanup_generation = deactivate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=active_generation,
+ )
+ assert cleanup_generation is not None
+
+ with (
+ patch.object(ExternalDataSource, "save", side_effect=RuntimeError("database write failed")),
+ pytest.raises(RuntimeError, match="database write failed"),
+ ):
+ soft_delete_managed_warehouse_sources(
+ organization_id=org.id,
+ expected_generation=cleanup_generation,
+ )
+
+ expected_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ provision_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=expected_generation,
+ )
+ assert provision_generation is not None
+ reprovisioned = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=provision_generation,
+ )
+ soft_delete_managed_warehouse_sources(
+ organization_id=org.id,
+ expected_generation=cleanup_generation,
+ )
+
+ assert reprovisioned is not None
+ reprovisioned.refresh_from_db()
+ assert reprovisioned.deleted is False
+ assert reprovisioned.job_inputs == {}
+ assert isinstance(reprovisioned.connection_metadata, dict)
+ assert reprovisioned.connection_metadata["credential_kind"] == "duckgres_service"
+
+ def test_delayed_cleanup_for_a_deleted_organization_is_a_converged_noop(self) -> None:
+ organization_id = Organization.objects.create(name="Org").id
+ Organization.objects.filter(id=organization_id).delete()
+
+ soft_delete_managed_warehouse_sources(
+ organization_id=organization_id,
+ expected_generation=7,
+ )
+
+ assert not ManagedWarehouseSourceLifecycle.objects.filter(organization_id=organization_id).exists()
+
+ def test_lifecycle_organization_relation_has_no_database_constraint(self) -> None:
+ field = ManagedWarehouseSourceLifecycle._meta.get_field("organization")
+ assert isinstance(field, OneToOneField)
+ assert field.db_constraint is False # type: ignore[attr-defined]
class TestInternalSchemas:
@@ -818,3 +1488,74 @@ def test_ready_status_queues_table_discovery(mock_schedule: MagicMock) -> None:
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)
+
+
+@override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False)
+@patch("products.managed_warehouse.backend.facade.connection.soft_delete_legacy_managed_warehouse_sources")
+def test_old_one_argument_cleanup_message_runs_on_a_new_worker(mock_soft_delete: MagicMock) -> None:
+ soft_delete_managed_warehouse_sources_task("org-1")
+
+ mock_soft_delete.assert_called_once_with(organization_id="org-1")
+
+
+@override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True)
+@patch("products.managed_warehouse.backend.facade.connection.soft_delete_legacy_managed_warehouse_sources")
+def test_old_cleanup_message_cannot_delete_dynamic_sources_after_the_rollout(mock_soft_delete: MagicMock) -> None:
+ soft_delete_managed_warehouse_sources_task("org-1")
+
+ mock_soft_delete.assert_not_called()
+
+
+@override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True)
+@patch("products.managed_warehouse.backend.facade.connection.soft_delete_managed_warehouse_sources")
+def test_v2_cleanup_task_carries_the_original_deprovision_generation(mock_soft_delete: MagicMock) -> None:
+ soft_delete_managed_warehouse_sources_v2_task("org-1", 7)
+
+ mock_soft_delete.assert_called_once_with(organization_id="org-1", expected_generation=7)
+
+
[email protected]([(False,), (True,)])
+def test_source_cleanup_scheduler_uses_a_rolling_compatible_task(dynamic_auth_enabled: bool) -> None:
+ assert soft_delete_managed_warehouse_sources_task.name == (
+ "products.data_warehouse.backend.tasks.soft_delete_managed_warehouse_sources"
+ )
+ assert soft_delete_managed_warehouse_sources_v2_task.name == (
+ "products.data_warehouse.backend.tasks.soft_delete_managed_warehouse_sources_v2"
+ )
+ with (
+ override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=dynamic_auth_enabled),
+ patch.object(soft_delete_managed_warehouse_sources_task, "delay") as legacy_delay,
+ patch.object(soft_delete_managed_warehouse_sources_v2_task, "delay") as v2_delay,
+ ):
+ schedule_soft_delete_managed_warehouse_sources(organization_id="org-1", expected_generation=7)
+
+ if dynamic_auth_enabled:
+ legacy_delay.assert_not_called()
+ v2_delay.assert_called_once_with(organization_id="org-1", expected_generation=7)
+ else:
+ legacy_delay.assert_called_once_with(organization_id="org-1")
+ v2_delay.assert_not_called()
+
+
+@override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True)
+@patch("products.managed_warehouse.backend.facade.connection.ensure_managed_warehouse_direct_source")
+def test_v2_source_recovery_task_rechecks_the_generation(mock_ensure: MagicMock) -> None:
+ ensure_managed_warehouse_direct_source_v2_task(42, "org-1", 7)
+
+ mock_ensure.assert_called_once_with(team_id=42, organization_id="org-1", expected_generation=7)
+
+
+def test_source_recovery_scheduler_is_only_emitted_after_the_rollout_gate() -> None:
+ with (
+ patch.object(ensure_managed_warehouse_direct_source_v2_task, "delay") as delay,
+ override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False),
+ ):
+ schedule_managed_warehouse_direct_source_ensure(team_id=42, organization_id="org-1", expected_generation=7)
+ delay.assert_not_called()
+
+ with (
+ patch.object(ensure_managed_warehouse_direct_source_v2_task, "delay") as delay,
+ override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=True),
+ ):
+ schedule_managed_warehouse_direct_source_ensure(team_id=42, organization_id="org-1", expected_generation=7)
+ delay.assert_called_once_with(team_id=42, organization_id="org-1", expected_generation=7)
diff --git a/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py b/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py
new file mode 100644
index 000000000000..83fcadb688a2
--- /dev/null
+++ b/products/managed_warehouse/backend/tests/test_sql_editor_credentials.py
@@ -0,0 +1,487 @@
+from concurrent.futures import ThreadPoolExecutor
+from datetime import UTC, datetime, timedelta
+from threading import Event, Lock
+
+import pytest
+from unittest.mock import patch
+
+from products.managed_warehouse.backend.facade.contracts import (
+ ManagedWarehouseSourceAuth,
+ ServiceCredential,
+ ServiceCredentialConnect,
+)
+from products.managed_warehouse.backend.logic import sql_editor_credentials
+from products.managed_warehouse.backend.logic.sql_editor_credentials import (
+ MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ ServiceCredentialCache,
+ resolve_managed_warehouse_postgres_connection,
+)
+from products.managed_warehouse.backend.service_credentials import ServiceCredentialUnavailable
+from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX
+
+SQL_EDITOR_PRINCIPAL = "posthog:sql-editor:team:1:user:1"
+
+
+def _credential(credential_id: str, expires_at: datetime) -> ServiceCredential:
+ return ServiceCredential(
+ credential_id=credential_id,
+ credential_secret=f"secret-{credential_id}",
+ expires_at=expires_at,
+ connect=ServiceCredentialConnect(
+ host="warehouse.dw.us.postwh.com",
+ port=5432,
+ database="ducklake",
+ sslmode="require",
+ ),
+ )
+
+
+def test_concurrent_callers_share_one_in_flight_mint() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ mint_started = Event()
+ allow_mint = Event()
+ mint_count = 0
+ count_lock = Lock()
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ nonlocal mint_count
+ with count_lock:
+ mint_count += 1
+ mint_started.set()
+ assert allow_mint.wait(timeout=5)
+ return _credential("svc_one", now + timedelta(minutes=15))
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ first = executor.submit(cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ assert mint_started.wait(timeout=5)
+ second = executor.submit(cache.get, "org-1", 2, principal=SQL_EDITOR_PRINCIPAL)
+ allow_mint.set()
+
+ assert first.result().credential_id == "svc_one"
+ assert second.result().credential_id == "svc_one"
+ assert mint_count == 1
+
+
+def test_principals_never_share_cached_credentials_within_an_organization() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ minted_for: list[str] = []
+
+ def mint(_organization_id: str, _team_id: int, principal: str) -> ServiceCredential:
+ minted_for.append(principal)
+ return _credential(f"svc_{len(minted_for)}", now + timedelta(minutes=15))
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+ user_one = "posthog:sql-editor:team:1:user:1"
+ user_two = "posthog:sql-editor:team:1:user:2"
+
+ assert cache.get("org-1", 1, principal=user_one).credential_id == "svc_1"
+ assert cache.get("org-1", 1, principal=user_two).credential_id == "svc_2"
+ assert cache.get("org-1", 1, principal=user_one).credential_id == "svc_1"
+ assert minted_for == [user_one, user_two]
+
+
+def test_lifecycle_generations_never_share_cached_credentials_for_the_same_principal() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ minted: list[str] = []
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ credential_id = f"svc_{len(minted) + 1}"
+ minted.append(credential_id)
+ return _credential(credential_id, now + timedelta(minutes=15))
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ first = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=3)
+ same_generation = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=3)
+ reprovisioned = cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL, lifecycle_generation=5)
+
+ assert first.credential_id == "svc_1"
+ assert same_generation.credential_id == "svc_1"
+ assert reprovisioned.credential_id == "svc_2"
+ assert minted == ["svc_1", "svc_2"]
+
+
+def test_replaces_a_credential_before_expiry_with_an_independent_mint() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ minted = [
+ _credential("svc_old", now + timedelta(minutes=2)),
+ _credential("svc_new", now + timedelta(minutes=15)),
+ ]
+
+ cache = ServiceCredentialCache(mint=lambda _organization_id, _team_id, _principal: minted.pop(0), now=lambda: now)
+
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_old"
+ now += timedelta(seconds=61)
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_new"
+ assert minted == []
+
+
+def test_uses_an_unexpired_cached_credential_during_a_mint_outage_but_fails_after_expiry() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ original = _credential("svc_old", now + timedelta(minutes=2))
+ mint_count = 0
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ nonlocal mint_count
+ mint_count += 1
+ if mint_count == 1:
+ return original
+ raise ServiceCredentialUnavailable("control plane unavailable")
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ now += timedelta(seconds=61)
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ now += timedelta(seconds=60)
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+
+
+def test_failed_early_replacement_is_backed_off_while_cached_credential_remains_valid() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ original = _credential("svc_old", now + timedelta(minutes=2))
+ mint_count = 0
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ nonlocal mint_count
+ mint_count += 1
+ if mint_count == 1:
+ return original
+ raise ServiceCredentialUnavailable("control plane unavailable")
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ now += timedelta(seconds=61)
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ assert mint_count == 2
+
+
+def test_unexpected_early_replacement_failure_serves_and_backs_off_an_unexpired_credential() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ original = _credential("svc_old", now + timedelta(minutes=2))
+ mint_count = 0
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ nonlocal mint_count
+ mint_count += 1
+ if mint_count == 1:
+ return original
+ raise RuntimeError("unexpected control-plane client failure")
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ now += timedelta(seconds=61)
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ assert mint_count == 2
+
+
+def test_stalled_refresh_for_one_organization_does_not_block_another() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ org_one_started = Event()
+ release_org_one = Event()
+
+ def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ if organization_id == "org-1":
+ org_one_started.set()
+ assert release_org_one.wait(timeout=5)
+ return _credential(f"svc_{organization_id}", now + timedelta(minutes=15))
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ org_one = executor.submit(cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ assert org_one_started.wait(timeout=5)
+ org_two = executor.submit(cache.get, "org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
+ assert org_two.result(timeout=1).credential_id == "svc_org-2"
+ release_org_one.set()
+
+ assert org_one.result().credential_id == "svc_org-1"
+
+
+def test_per_organization_singleflight_state_is_bounded() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ mint_count = 0
+
+ def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ nonlocal mint_count
+ mint_count += 1
+ return _credential(f"svc_{organization_id}_{mint_count}", now + timedelta(minutes=15))
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now, maxsize=1)
+
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ cache.get("org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+
+ assert mint_count == 3
+
+
+def test_in_use_state_cannot_be_evicted_and_is_evictable_after_release() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ state_leased = Event()
+ release_state = Event()
+ mint_counts: dict[str, int] = {}
+
+ def mint(organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ mint_counts[organization_id] = mint_counts.get(organization_id, 0) + 1
+ return _credential(f"svc_{organization_id}", now + timedelta(minutes=15))
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now, maxsize=1)
+ original_state_for = cache._state_for
+ first_org_one_lookup = True
+
+ def pausing_state_for(cache_key: sql_editor_credentials._CredentialCacheKey):
+ nonlocal first_org_one_lookup
+ state = original_state_for(cache_key)
+ if (
+ cache_key.organization_id == "org-1"
+ and cache_key.principal == SQL_EDITOR_PRINCIPAL
+ and cache_key.lifecycle_generation == 0
+ and first_org_one_lookup
+ ):
+ first_org_one_lookup = False
+ state_leased.set()
+ assert release_state.wait(timeout=5)
+ return state
+
+ with patch.object(cache, "_state_for", side_effect=pausing_state_for):
+ with ThreadPoolExecutor(max_workers=2) as executor:
+ org_one = executor.submit(cache.get, "org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ assert state_leased.wait(timeout=5)
+ with pytest.raises(ServiceCredentialUnavailable, match="at capacity"):
+ cache.get("org-2", 2, principal=SQL_EDITOR_PRINCIPAL)
+ release_state.set()
+ assert org_one.result(timeout=5).credential_id == "svc_org-1"
+
+ assert cache.get("org-2", 2, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_org-2"
+
+ assert mint_counts == {"org-1": 1, "org-2": 1}
+
+
+def test_sql_editor_mint_uses_a_short_request_timeout() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ with patch(
+ "products.managed_warehouse.backend.logic.sql_editor_credentials.mint_service_credential",
+ return_value=_credential("svc_one", now + timedelta(minutes=15)),
+ ) as mint:
+ sql_editor_credentials._mint_sql_editor_credential("org-1", 1, SQL_EDITOR_PRINCIPAL)
+
+ assert mint.call_args.kwargs["timeout_seconds"] == 3
+ assert mint.call_args.kwargs["principal"] == SQL_EDITOR_PRINCIPAL
+
+
+def test_does_not_return_a_credential_that_expires_during_a_failed_replacement() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ original = _credential("svc_old", now + timedelta(minutes=2))
+ mint_count = 0
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ nonlocal mint_count, now
+ mint_count += 1
+ if mint_count == 1:
+ return original
+ now += timedelta(minutes=1)
+ raise ServiceCredentialUnavailable("control plane unavailable")
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL) is original
+ now += timedelta(seconds=61)
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+
+
+def test_failure_state_does_not_retain_exception_tracebacks_or_secret_bearing_locals() -> None:
+ def malformed(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ malformed_payload = {"credential_secret": "must-not-remain-reachable"}
+ assert malformed_payload
+ raise ServiceCredentialUnavailable("malformed control-plane response: must-not-remain-reachable")
+
+ cache = ServiceCredentialCache(mint=malformed)
+
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+
+ state = next(iter(cache._states.values()))
+ assert not any(isinstance(value, BaseException) for value in vars(state).values())
+ assert "must-not-remain-reachable" not in repr(vars(state))
+
+
+def test_unexpected_refresh_replaces_stale_failure_state_and_is_backed_off() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ failures = [
+ ServiceCredentialUnavailable("old unavailable failure"),
+ RuntimeError("new unexpected failure"),
+ ]
+
+ def mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ raise failures.pop(0)
+
+ cache = ServiceCredentialCache(mint=mint, now=lambda: now)
+
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ now += timedelta(seconds=6)
+ with pytest.raises(ServiceCredentialUnavailable, match="unexpected"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ with pytest.raises(ServiceCredentialUnavailable, match="unexpected"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+
+ assert failures == []
+
+
+def test_insecure_connect_bundle_is_not_cached_and_the_next_call_can_recover() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ insecure = ServiceCredential(
+ credential_id="svc_insecure",
+ credential_secret="secret-insecure",
+ expires_at=now + timedelta(minutes=15),
+ connect=ServiceCredentialConnect(
+ host="warehouse.dw.us.postwh.com",
+ port=5432,
+ database="ducklake",
+ sslmode="prefer",
+ ),
+ )
+ minted = [insecure, _credential("svc_secure", now + timedelta(minutes=15))]
+ cache = ServiceCredentialCache(mint=lambda _organization_id, _team_id, _principal: minted.pop(0), now=lambda: now)
+
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL)
+ now += timedelta(seconds=6)
+
+ assert cache.get("org-1", 1, principal=SQL_EDITOR_PRINCIPAL).credential_id == "svc_secure"
+ assert minted == []
+
+
+def test_dynamic_source_fails_closed_when_no_credential_can_be_minted(monkeypatch: pytest.MonkeyPatch) -> None:
+ def unavailable(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ raise ServiceCredentialUnavailable("control plane unavailable")
+
+ monkeypatch.setattr(
+ sql_editor_credentials,
+ "_service_credential_cache",
+ ServiceCredentialCache(mint=unavailable),
+ )
+ source_auth = ManagedWarehouseSourceAuth(
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ system_managed=True,
+ credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ lifecycle_generation=1,
+ )
+
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ resolve_managed_warehouse_postgres_connection(
+ source_auth=source_auth,
+ organization_id="org-1",
+ team_id=1,
+ principal=SQL_EDITOR_PRINCIPAL,
+ )
+
+
+def test_unmarked_source_uses_legacy_connection_details_without_minting(monkeypatch: pytest.MonkeyPatch) -> None:
+ def unexpected_mint(_organization_id: str, _team_id: int, _principal: str) -> ServiceCredential:
+ raise AssertionError("legacy sources must not mint service credentials")
+
+ monkeypatch.setattr(
+ sql_editor_credentials,
+ "_service_credential_cache",
+ ServiceCredentialCache(mint=unexpected_mint),
+ )
+ source_auth = ManagedWarehouseSourceAuth(
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ system_managed=True,
+ credential_kind=None,
+ lifecycle_generation=None,
+ )
+
+ assert (
+ resolve_managed_warehouse_postgres_connection(
+ source_auth=source_auth,
+ organization_id="org-1",
+ team_id=1,
+ principal=SQL_EDITOR_PRINCIPAL,
+ )
+ is None
+ )
+
+
+def test_dynamic_connection_carries_required_sslmode() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ cache = ServiceCredentialCache(
+ mint=lambda _organization_id, _team_id, _principal: _credential("svc_one", now + timedelta(minutes=15)),
+ now=lambda: now,
+ )
+ source_auth = ManagedWarehouseSourceAuth(
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ system_managed=True,
+ credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ lifecycle_generation=1,
+ )
+
+ connection = resolve_managed_warehouse_postgres_connection(
+ source_auth=source_auth,
+ organization_id="org-1",
+ team_id=1,
+ principal=SQL_EDITOR_PRINCIPAL,
+ credential_cache=cache,
+ )
+
+ assert connection is not None
+ assert connection.sslmode == "require"
+
+
+def test_dynamic_connection_rejects_an_insecure_control_plane_sslmode() -> None:
+ now = datetime(2026, 1, 1, tzinfo=UTC)
+ credential = _credential("svc_one", now + timedelta(minutes=15))
+ credential = ServiceCredential(
+ credential_id=credential.credential_id,
+ credential_secret=credential.credential_secret,
+ expires_at=credential.expires_at,
+ connect=ServiceCredentialConnect(
+ host=credential.connect.host,
+ port=credential.connect.port,
+ database=credential.connect.database,
+ sslmode="prefer",
+ ),
+ )
+ cache = ServiceCredentialCache(mint=lambda _organization_id, _team_id, _principal: credential, now=lambda: now)
+ source_auth = ManagedWarehouseSourceAuth(
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ system_managed=True,
+ credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ lifecycle_generation=1,
+ )
+
+ with pytest.raises(ServiceCredentialUnavailable, match="service credential mint unavailable"):
+ resolve_managed_warehouse_postgres_connection(
+ source_auth=source_auth,
+ organization_id="org-1",
+ team_id=1,
+ principal=SQL_EDITOR_PRINCIPAL,
+ credential_cache=cache,
+ )
+
+
+def test_dynamic_source_without_a_lifecycle_generation_fails_closed() -> None:
+ source_auth = ManagedWarehouseSourceAuth(
+ prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
+ system_managed=True,
+ credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
+ lifecycle_generation=None,
+ )
+
+ with pytest.raises(ServiceCredentialUnavailable, match="lifecycle generation"):
+ resolve_managed_warehouse_postgres_connection(
+ source_auth=source_auth,
+ organization_id="org-1",
+ team_id=1,
+ principal=SQL_EDITOR_PRINCIPAL,
+ )
diff --git a/products/warehouse_sources/backend/facade/models.py b/products/warehouse_sources/backend/facade/models.py
index 3db7850850dd..6cd146e8105a 100644
--- a/products/warehouse_sources/backend/facade/models.py
+++ b/products/warehouse_sources/backend/facade/models.py
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.models.external_data_schema import (
from products.warehouse_sources.backend.models.external_data_source import (
MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS,
MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
+ MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
MANAGED_WAREHOUSE_SOURCE_PREFIX,
ExternalDataSource,
get_direct_external_data_source_for_connection,
@@ -70,6 +71,7 @@ __all__ = [
"ExternalDataSource",
"MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS",
"MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND",
+ "MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND",
"MANAGED_WAREHOUSE_SOURCE_PREFIX",
"PendingSourceCredential",
"SERIALIZED_FIELD_TO_CLICKHOUSE_MAPPING",
diff --git a/products/warehouse_sources/backend/models/external_data_source.py b/products/warehouse_sources/backend/models/external_data_source.py
index a35cbac3db2a..dff1c75bcae6 100644
--- a/products/warehouse_sources/backend/models/external_data_source.py
+++ b/products/warehouse_sources/backend/models/external_data_source.py
@@ -20,6 +20,7 @@ logger = structlog.get_logger(__name__)
MANAGED_WAREHOUSE_SOURCE_PREFIX = "managed_warehouse"
MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND = "project_reader"
+MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND = "duckgres_service"
MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS = frozenset({"org_root", "stored_server_login"})
SYSTEM_MANAGED_SOURCE_PREFIXES = frozenset({MANAGED_WAREHOUSE_SOURCE_PREFIX})
@@ -161,10 +162,23 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
@classmethod
def ready_managed_warehouse_q(cls) -> models.Q:
+ return (
+ cls.managed_warehouse_identity_q()
+ & models.Q(direct_query_enabled=True)
+ & (
+ models.Q(connection_metadata__credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND)
+ | models.Q(
+ connection_metadata__credential_kind=MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
+ connection_metadata__reader_configured=True,
+ )
+ )
+ )
+
+ @classmethod
+ def dynamic_managed_warehouse_q(cls) -> models.Q:
return cls.managed_warehouse_identity_q() & models.Q(
direct_query_enabled=True,
- connection_metadata__credential_kind=MANAGED_WAREHOUSE_PROJECT_READER_CREDENTIAL_KIND,
- connection_metadata__reader_configured=True,
+ connection_metadata__credential_kind=MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
)
def _has_valid_managed_warehouse_connection_inputs(self, *, expected_user: str | None = None) -> bool:
@@ -219,9 +233,26 @@ class ExternalDataSource(ModelActivityMixin, CreatedMetaFields, UpdatedMetaField
return self._has_valid_managed_warehouse_connection_inputs(expected_user=f"posthog_team_{self.team_id}")
+ @property
+ def is_dynamic_managed_warehouse(self) -> bool:
+ metadata = self.connection_metadata
+ return (
+ self.is_managed_warehouse
+ and self.direct_query_enabled
+ and isinstance(metadata, dict)
+ and metadata.get("credential_kind") == MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND
+ and isinstance(metadata.get("lifecycle_generation"), int)
+ and not isinstance(metadata.get("lifecycle_generation"), bool)
+ and metadata["lifecycle_generation"] >= 0
+ and self.job_inputs == {}
+ )
+
@property
def managed_warehouse_sql_mode(self) -> ManagedWarehouseSQLMode:
- if self.is_managed_warehouse_ready:
+ # Accepted interim contract for the default-off rollout: provisioning already exposes organization-root
+ # access, so duckgres_service is intentionally the built-in organization connection. Project-scoped grants
+ # require future Duckgres authorization support.
+ if self.is_dynamic_managed_warehouse or self.is_managed_warehouse_ready:
return ManagedWarehouseSQLMode.BUILT_IN
if (
self.is_legacy_managed_warehouse
@@ -361,4 +392,4 @@ def is_managed_warehouse_connection_ready(team_id: int, connection_id: str | Non
.exclude(deleted=True)
.first()
)
- return source is not None and source.is_managed_warehouse_ready
+ return source is not None and source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_source.py b/products/warehouse_sources/backend/presentation/views/external_data_source.py
index c65f7d1bd135..6f34e212a06f 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -4720,7 +4720,10 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
"direct_query_enabled",
"job_inputs",
)
- managed_source = next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)
+ managed_source = next(
+ (source for source in managed_candidates if source.is_dynamic_managed_warehouse),
+ None,
+ ) or next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)
external_sources = connection_sources.exclude(prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX)
else:
canonical_source = _canonical_legacy_managed_warehouse_source(connection_sources)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
index e819cb0473c7..5ace4d3efb1f 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/source.py
@@ -926,6 +926,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
names: list[str] | None = None,
force_refresh: bool = False,
api_version: str | None = None,
+ require_ssl: bool = False,
) -> list[SourceSchema]:
schemas = []
@@ -938,6 +939,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
database=config.database,
schema=config.schema,
names=names,
+ require_ssl=require_ssl,
)
# Foreign keys are advisory metadata (they pre-populate relationship hints in the
# table picker). The discovery query joins three `information_schema` views, which
@@ -953,6 +955,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
database=config.database,
schema=config.schema,
names=names,
+ require_ssl=require_ssl,
)
except Exception as e:
structlog.get_logger().warning("Failed to detect foreign keys for Postgres schemas", exc_info=e)
@@ -967,6 +970,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
database=config.database,
schema=config.schema,
names=names,
+ require_ssl=require_ssl,
)
else:
row_counts = {}
@@ -999,6 +1003,7 @@ class PostgresSource(SQLSource[PostgresSourceConfig], SSHTunnelMixin, ValidateDa
user=config.user,
password=config.password,
database=config.database,
+ require_ssl=require_ssl,
) as conn:
# PK lookup powers `supports_cdc`. Wrap in try/except so a permissions
# quirk on `pg_catalog` (rare) only disables CDC advertising for this
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index d103f6fed899..2d1ce8c9a792 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -4299,6 +4299,40 @@ class TestPostgresSourceGetSchemasDegradesGracefully:
def _config(self):
return mock.MagicMock(user="u", password="p", database="db", schema="", ssh_tunnel=None)
+ def test_required_ssl_is_used_for_every_schema_discovery_connection(self, source):
+ tunnel_cm = mock.MagicMock()
+ tunnel_cm.__enter__.return_value = ("localhost", 5432)
+ tunnel_cm.__exit__.return_value = None
+ metadata_connection = mock.MagicMock()
+ metadata_connection.__enter__.return_value = mock.MagicMock()
+ metadata_connection.__exit__.return_value = None
+
+ with (
+ mock.patch.object(source, "with_ssh_tunnel", return_value=tunnel_cm),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.get_postgres_schemas",
+ return_value={},
+ ) as get_schemas,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.get_postgres_foreign_keys",
+ return_value={},
+ ) as get_foreign_keys,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.get_postgres_row_count",
+ return_value={},
+ ) as get_row_count,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.pg_connection",
+ return_value=metadata_connection,
+ ) as pg_connection,
+ ):
+ source.get_schemas(self._config(), team_id=1, with_counts=True, require_ssl=True)
+
+ assert get_schemas.call_args.kwargs["require_ssl"] is True
+ assert get_foreign_keys.call_args.kwargs["require_ssl"] is True
+ assert get_row_count.call_args.kwargs["require_ssl"] is True
+ assert pg_connection.call_args.kwargs["require_ssl"] is True
+
@pytest.mark.parametrize(
"exc",
[
diff --git a/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py b/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py
index bf8608ccd26c..ea6ce6ad2343 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py
@@ -385,6 +385,25 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
self.assertNotIn(str(external_source.id), returned_ids)
self.assertNotIn(str(pending_source.id), returned_ids)
+ def test_connections_prefers_dynamic_service_source_over_project_reader(self) -> None:
+ project_reader = self._create_managed_source()
+ dynamic = self._create_managed_source(
+ job_inputs={},
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ },
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual([item["id"] for item in response.json()], [str(dynamic.id)])
+ self.assertTrue(response.json()[0]["is_builtin_managed_warehouse"])
+ self.assertNotEqual(dynamic.id, project_reader.id)
+
@parameterized.expand(
[
("missing_system_managed", {"connection_metadata": {"engine": "duckdb"}}),
@@ -489,6 +508,15 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
) -> None:
legacy_source = self._create_legacy_managed_source()
ready_reader = self._create_managed_source()
+ dynamic_source = self._create_managed_source(
+ job_inputs={},
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": 1,
+ },
+ )
pending_reader = self._create_managed_source(
connection_metadata={
"engine": "duckdb",
@@ -532,6 +560,7 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
]
)
self.assertNotIn(str(ready_reader.id), [item["id"] for item in response.json()])
+ self.assertNotIn(str(dynamic_source.id), [item["id"] for item in response.json()])
self.assertNotIn(str(pending_reader.id), [item["id"] for item in response.json()])
self.assertNotIn(str(malformed_legacy.id), [item["id"] for item in response.json()])
self.assertNotIn(str(unknown_kind.id), [item["id"] for item in response.json()])