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.

fix(managed-warehouse): make dynamic SQL auth the default (#86483)

Benjamin Knofe-Videre49869925a54
diff --git a/docs/internal/managed-warehouse-sql-editor.md b/docs/internal/managed-warehouse-sql-editor.md
index e927c8f10005..c1f36bcfc518 100644
--- a/docs/internal/managed-warehouse-sql-editor.md
+++ b/docs/internal/managed-warehouse-sql-editor.md
@@ -1,12 +1,10 @@
# Managed warehouse connections in the SQL editor
-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.
+The `data-warehouse-scene` feature flag gates user access to managed warehouse provisioning. It does not select a SQL-editor authentication mode. Once a provision, onboarding, or generation-fenced recovery lifecycle action runs, a genuinely missing managed source is created unconditionally as a secretless `duckgres_service` source and presented as `PostHog (Managed warehouse)`.
-`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.
+A `duckgres_service` row persists no host, username, password, or credential ID. It persists only the non-secret lifecycle generation that created it. Dynamic raw queries use the native Duckgres pgwire adapter. At physical connection acquisition, PostHog mints a short-lived organization-root-shaped service credential for a principal containing the project ID and stable PostHog user ID. Email addresses are never used. Schema discovery uses a distinct project-scoped system principal, so background work never impersonates an interactive user. The connection must include `sslmode=require`, and there is no stored-root fallback.
-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.
-
-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.
+Existing live sources keep their stored authentication mode unless an actual warehouse lifecycle action requires replacement. A live dynamic source remains dynamic, a configured `project_reader` retains its stored project credential, and a static organization-login source retains its stored root credential and external-source access controls. The database chooser prefers a dynamic source, then a ready `project_reader`; when neither exists, it exposes the canonical valid legacy source as an ordinary external connection. Merely changing a product feature flag does not create, convert, or hide a source.
PostHog application-encrypts credentials in shared Redis. The cache key is a hash of the organization, principal, and lifecycle generation, and the entry expires one minute before the credential. A per-key Redis lock lets query-django and Celery workers share one mint without making unrelated principals wait. Refresh always mints an independent credential and never rotates a cached credential ID. A rapid deprovision and reprovision therefore cannot reuse a credential from the old generation.
@@ -14,32 +12,32 @@ Redis is the only credential cache. When Redis cannot be read, locked, or writte
The credential cache uses a dedicated Redis client with no command retries. `MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS` and `MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_READ_TIMEOUT_SECONDS` both default to 0.5 seconds. Timeout and retry query parameters in `REDIS_URL` are ignored for this client, while authentication, database, TLS, and other Redis options remain intact. These settings do not change the shared Redis client's longer timeout for blocking operations.
-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.
-
-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.
+An organization-scoped generation fence orders source work around remote provision and deprovision calls. A stale provision completion cannot revive a source after a later deprovision, and an old cleanup retry cannot delete a genuinely reprovisioned source. If cleanup failed before a genuine reprovision, static and `project_reader` sources from the deleted warehouse generation are tombstoned with their tables before setup creates dynamic authentication. An existing dynamic source instead advances its lifecycle generation. Credentials therefore cannot cross warehouse generations.
-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.
+Reconciliation treats dynamic, project-reader, and static sources as independent catalogs and introspects each with its own credential mode. A failure in one source does not block the others. Dynamic discovery requires TLS and uses its system principal. Reconciliation runs when warehouse status is read, coalesced to once a minute, and in a twice-hourly periodic sweep. For an active generation with a missing source, reconciliation creates dynamic authentication without reading `DuckgresServer`.
-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 native adapter sends one PostgreSQL-compatible statement unchanged, supports asynchronous cancellation, applies the existing connection deadline and statement timeout, and rejects results above 50,000 rows. Non-raw project-reader and static-source queries continue through their existing PostgreSQL/HogQL path; the PostgreSQL adapter is unchanged.
-Deprovision captures the active generation before the control-plane request and deactivates only that generation. A direct 404 is authoritative absence. If the request times out or returns 409, PostHog reads warehouse status. It converges local cleanup only when the warehouse is `deleting`, `deleted`, or absent. A ready warehouse remains active. 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.
+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.
## 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.
+1. Keep `MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=true` in the current web, admin, and Celery deployments throughout the rolling code deployment. Old workers use that setting, while new workers create dynamic sources unconditionally, so both versions agree.
+2. Deploy this code to every web, admin, and Celery process. New producers always emit generation-aware v2 cleanup and source-recovery tasks.
+3. Drain queued, reserved, scheduled, and retry source-recovery work after no old process remains.
+4. Remove `MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED` from the charts in a separate deployment. New code no longer reads it.
+
+Rolling back to old code requires restoring or retaining `MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=true` first. Removing the charts setting before the old fleet and its queues are drained would make old workers drop 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.
+The legacy cleanup task keeps its one-argument wire signature so new workers can consume messages queued before this deployment. Its handler takes the organization lock, cleans the current inactive generation, does nothing for an active lifecycle, and uses unconditional legacy behavior only when no lifecycle row exists. New producers emit only versioned generation-aware cleanup tasks. Cleanup is independent of credential mode and generation-fenced.
-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.
+Source setup, query authentication, schema discovery, and generation-fenced deprovision cleanup do not read `DuckgresServer`. The model remains for persistence of the one-time provision response, legacy consumers, and rotating root passwords on grandfathered 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.
+The historical query-status label prefix `managed-warehouse-sql-editor:` remains only as an in-flight wire identifier. It is not a feature flag. Renaming or removing it requires a later dual-read rollout and a drain of query statuses produced by old workers.
## 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 source setup fails after successful provision or onboarding, the versioned retry task uses the original team, organization, and generation. It is safe to retry and creates dynamic authentication when the source is still missing. If the warehouse was deprovisioned or reprovisioned, the generation check turns a stale 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/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index bbadcb65f955..e0c37fcaa37f 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -377,7 +377,6 @@ export const FEATURE_FLAGS = {
MANAGED_MIGRATIONS_IAM_ROLE_AUTH: 'managed-migrations-iam-role-auth', // owner: #team-ingestion, gates IAM role auth for S3 batch imports
MANAGED_MIGRATIONS_TRIAL_RUNS: 'managed-migrations-trial-runs', // owner: #team-ingestion, gates trial runs for managed migrations
MANAGED_VIEWSETS: 'managed-viewsets', // owner: @rafaeelaudibert #team-revenue-analytics
- MANAGED_WAREHOUSE_SQL_EDITOR: 'managed-warehouse-sql-editor', // owner: #team-managed-warehouse, gates managed warehouse connections in the SQL editor
MARKETING_ANALYTICS_AI: 'marketing-analytics-ai', // owner: @jabahamondes #team-web-analytics
MARKETING_ANALYTICS_ATTRIBUTION: 'marketing-analytics-attribution', // owner: @jabahamondes #team-web-analytics — gates the Attribution tab
MARKETING_ANALYTICS_COSTS_PRECOMPUTATION: 'marketing-analytics-costs-precomputation', // owner: @jabahamondes #team-web-analytics — gates reading the native cost precompute table
diff --git a/posthog/api/query.py b/posthog/api/query.py
index 21981dce3d1f..09a8ba645b32 100644
--- a/posthog/api/query.py
+++ b/posthog/api/query.py
@@ -73,7 +73,7 @@ from posthog.rate_limit import (
from posthog.rbac.user_access_control import UserAccessControlError
from posthog.schema_migrations.upgrade import upgrade
-from products.managed_warehouse.backend.facade import feature_flags as managed_warehouse_feature_flags
+from products.managed_warehouse.backend.facade import query_labels as managed_warehouse_query_labels
from products.warehouse_sources.backend.facade.models import is_managed_warehouse_connection_ready
from common.hogvm.python.utils import HogVMException
@@ -401,9 +401,9 @@ class QueryViewSet(QueryCoalescingMixin, TeamAndOrgViewSetMixin, PydanticModelMi
query_status = get_query_status(team_id=self.team.pk, query_id=pk, show_progress=show_progress)
managed_connection_id = next(
(
- label.removeprefix(managed_warehouse_feature_flags.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX)
+ label.removeprefix(managed_warehouse_query_labels.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX)
for label in query_status.labels or []
- if label.startswith(managed_warehouse_feature_flags.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX)
+ if label.startswith(managed_warehouse_query_labels.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX)
),
None,
)
diff --git a/posthog/api/test/test_query.py b/posthog/api/test/test_query.py
index c8920b85dd41..b0ec08bed153 100644
--- a/posthog/api/test/test_query.py
+++ b/posthog/api/test/test_query.py
@@ -51,7 +51,7 @@ from posthog.llm.completions import OpenAICompletion
from posthog.models.utils import UUIDT
from products.event_definitions.backend.models.property_definition import PropertyDefinition, PropertyType
-from products.managed_warehouse.backend.facade.feature_flags import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX
+from products.managed_warehouse.backend.facade.query_labels import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX
from products.product_analytics.backend.facade.models import InsightVariable
from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -1263,14 +1263,12 @@ class TestQueryRetrieve(APIBaseTest):
@parameterized.expand(
[
- ("enabled_ready", True, True, 200),
- ("disabled_ready", False, True, 200),
- ("enabled_revoked", True, False, 404),
- ("disabled_revoked", False, False, 404),
+ ("ready", True, 200),
+ ("revoked", False, 404),
]
)
- def test_managed_warehouse_query_status_checks_reader_readiness_without_flag_revocation(
- self, _name: str, flag_enabled: bool, reader_configured: bool, expected_status: int
+ def test_managed_warehouse_query_status_checks_reader_readiness_without_feature_flag_lookup(
+ self, _name: str, reader_configured: bool, expected_status: int
) -> None:
source = ExternalDataSource.objects.create(
source_id="managed-source",
@@ -1307,13 +1305,13 @@ class TestQueryRetrieve(APIBaseTest):
).encode()
with patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- return_value=flag_enabled,
- ) as managed_warehouse_sql_editor_flag:
+ "posthog.permissions.posthog_feature_flag_enabled",
+ side_effect=AssertionError("query-status authorization must not evaluate a product feature flag"),
+ ) as feature_flag_lookup:
response = self.client.get(f"/api/environments/{self.team.id}/query/{self.valid_query_id}/")
self.assertEqual(response.status_code, expected_status)
- managed_warehouse_sql_editor_flag.assert_not_called()
+ feature_flag_lookup.assert_not_called()
if not reader_configured:
self.assertEqual(response.json()["detail"], MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_MESSAGE)
self.assertEqual(response.json()["code"], MANAGED_WAREHOUSE_QUERY_UNAVAILABLE_CODE)
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.md
index 3dcc1f4476cc..51eb801ffe4b 100644
--- a/posthog/dags/README_DUCKLINGS.md
+++ b/posthog/dags/README_DUCKLINGS.md
@@ -145,12 +145,11 @@ class DucklingBackfillConfig:
2. Enable another team's backfill with the "Enable warehouse backfill for a team" admin
action or the managed warehouse onboarding API. This creates the control-plane team row
with backfill enabled. The discovery sensor will pick up the team on its next run.
- By default, the SQL editor exposes the auto-provisioned Duckgres source as an external connection
- backed by the stored server login. When the `managed-warehouse-sql-editor` flag is enabled, the chooser
- replaces it with the built-in connection only if a reserved source already contains a configured Duckgres
- `project_reader` credential. Reader provisioning and rotation are separate from this enablement flow.
- Background discovery for a ready reader exposes only the project namespaces allowed by Duckgres. If the
- flag is enabled without a valid reader, neither managed connection appears in the chooser.
+ A new managed SQL-editor source uses short-lived `duckgres_service` credentials and appears as the built-in
+ `PostHog (Managed warehouse)` connection. Existing static and `project_reader` sources keep their current
+ authentication mode. The chooser prefers dynamic authentication, then a ready reader, and otherwise exposes
+ the canonical valid static source as an external connection. Reader provisioning and rotation remain separate
+ from this enablement flow.
3. To trigger immediate historical backfill, reset the full backfill sensor cursor
diff --git a/posthog/hogql/test/test_direct_connection.py b/posthog/hogql/test/test_direct_connection.py
index c923b4d6b06a..81110b7569ab 100644
--- a/posthog/hogql/test/test_direct_connection.py
+++ b/posthog/hogql/test/test_direct_connection.py
@@ -28,17 +28,6 @@ from ee.models import AccessControl
class TestGetDirectConnectionSource(APIBaseTest):
- managed_warehouse_sql_editor_flag: MagicMock
-
- def setUp(self) -> None:
- super().setUp()
- flag_patcher = patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- return_value=True,
- )
- self.managed_warehouse_sql_editor_flag = flag_patcher.start()
- self.addCleanup(flag_patcher.stop)
-
def _create_source(self, *, access_method: str, direct_query_enabled: bool = True) -> ExternalDataSource:
return ExternalDataSource.objects.create(
team=self.team,
@@ -104,16 +93,13 @@ class TestGetDirectConnectionSource(APIBaseTest):
@parameterized.expand(
[
- ("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),
+ ("reader", "project_reader", True),
+ ("dynamic", "duckgres_service", True),
+ ("legacy", "org_root", False),
]
)
def test_managed_warehouse_access_control_follows_credential_kind(
- self, _name: str, credential_kind: str, flag_enabled: bool, expected_access: bool
+ self, _name: str, credential_kind: str, expected_access: bool
) -> None:
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
@@ -140,7 +126,6 @@ class TestGetDirectConnectionSource(APIBaseTest):
resource="external_data_source",
access_level="none",
)
- self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
self.assertIsNone(get_direct_connection_source(self.team, str(external_source.id), user=self.user))
resolved = get_direct_connection_source(self.team, str(managed_source.id), user=self.user)
@@ -148,10 +133,8 @@ class TestGetDirectConnectionSource(APIBaseTest):
if resolved is not None:
self.assertEqual(resolved.id, managed_source.id)
- @parameterized.expand([("flag_off", False), ("flag_on", True)])
- def test_ready_reader_resolution_does_not_depend_on_picker_flag(self, _name: str, flag_enabled: bool) -> None:
+ def test_ready_reader_resolution_is_available(self) -> None:
source = self._create_managed_source()
- self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
self.assertEqual(get_direct_connection_source(self.team, str(source.id)), source)
self.assertEqual(
@@ -159,10 +142,7 @@ class TestGetDirectConnectionSource(APIBaseTest):
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:
+ def test_saved_dynamic_connection_id_resolves(self) -> None:
source = self._create_managed_source(
job_inputs={},
connection_metadata={
@@ -172,8 +152,6 @@ class TestGetDirectConnectionSource(APIBaseTest):
"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)),
@@ -181,9 +159,7 @@ class TestGetDirectConnectionSource(APIBaseTest):
)
@parameterized.expand([("org_root", "org_root"), ("stored_server_login", "stored_server_login")])
- def test_legacy_managed_credentials_remain_available_when_picker_flag_changes(
- self, _name: str, credential_kind: str
- ) -> None:
+ def test_legacy_managed_credentials_remain_available(self, _name: str, credential_kind: str) -> None:
source = self._create_managed_source(
connection_metadata={
"engine": "duckdb",
@@ -192,15 +168,11 @@ class TestGetDirectConnectionSource(APIBaseTest):
}
)
- for flag_enabled in (False, True):
- self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
- self.assertEqual(get_direct_connection_source(self.team, str(source.id)), source)
- self.assertEqual(get_direct_external_data_source_for_connection(self.team.id, str(source.id)), source)
+ self.assertEqual(get_direct_connection_source(self.team, str(source.id)), source)
+ self.assertEqual(get_direct_external_data_source_for_connection(self.team.id, str(source.id)), source)
- @parameterized.expand([("flag_off", False), ("flag_on", True)])
- def test_malformed_reserved_source_fails_closed_in_both_modes(self, _name: str, flag_enabled: bool) -> None:
+ def test_malformed_reserved_source_fails_closed(self) -> None:
source = self._create_managed_source(connection_metadata={"engine": "duckdb"})
- self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))
self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))
@@ -250,10 +222,8 @@ class TestGetDirectConnectionSource(APIBaseTest):
) -> None:
source = self._create_managed_source(**overrides)
- for flag_enabled in (False, True):
- self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
- self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))
- self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))
+ self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))
+ self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))
@parameterized.expand(
[
@@ -272,10 +242,8 @@ class TestGetDirectConnectionSource(APIBaseTest):
job_inputs=job_inputs,
)
- for flag_enabled in (False, True):
- self.managed_warehouse_sql_editor_flag.return_value = flag_enabled
- self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))
- self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))
+ self.assertIsNone(get_direct_connection_source(self.team, str(source.id)))
+ self.assertIsNone(get_direct_external_data_source_for_connection(self.team.id, str(source.id)))
def test_managed_warehouse_resolution_rejects_deleted_and_cross_team_sources(self) -> None:
deleted_source = self._create_managed_source(deleted=True)
diff --git a/posthog/hogql/test/test_direct_duckgres_query.py b/posthog/hogql/test/test_direct_duckgres_query.py
index c5e997fcd8e5..c112b449ffd2 100644
--- a/posthog/hogql/test/test_direct_duckgres_query.py
+++ b/posthog/hogql/test/test_direct_duckgres_query.py
@@ -197,16 +197,8 @@ class TestDuckgresStreamingClientCursor(SimpleTestCase):
class TestDirectDuckgresQuery(APIBaseTest):
- managed_warehouse_sql_editor_flag: MagicMock
-
def setUp(self) -> None:
super().setUp()
- flag_patcher = patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- return_value=True,
- )
- self.managed_warehouse_sql_editor_flag = flag_patcher.start()
- self.addCleanup(flag_patcher.stop)
resolver_patcher = patch(
"posthog.hogql.direct_sql.duckgres_adapter.resolve_psycopg_hostaddr_with_timeout",
return_value=["203.0.113.10"],
@@ -553,7 +545,6 @@ class TestDirectDuckgresQuery(APIBaseTest):
def test_non_raw_managed_query_ignores_warehouse_object_access_control(self) -> None:
source = self._managed_source_with_denied_table()
- self.managed_warehouse_sql_editor_flag.return_value = False
with patch(
"posthog.hogql.database.database.feature_enabled_or_false",
@@ -577,8 +568,6 @@ class TestDirectDuckgresQuery(APIBaseTest):
"credential_kind": "org_root",
},
)
- self.managed_warehouse_sql_editor_flag.return_value = True
-
with (
patch(
"posthog.hogql.database.database.feature_enabled_or_false",
@@ -626,7 +615,6 @@ class TestDirectDuckgresQuery(APIBaseTest):
@patch("posthog.hogql.query.raw_query_denied_by_table_access", side_effect=AssertionError)
def test_managed_warehouse_raw_queries_skip_unconfigured_table_access(self, _denied, connect) -> None:
source = self._managed_source()
- self.managed_warehouse_sql_editor_flag.return_value = False
connection, _cursor = self._connection_with_result([(1,)])
connect.return_value.__enter__.return_value = connection
@@ -647,7 +635,6 @@ class TestDirectDuckgresQuery(APIBaseTest):
self, _name: str, credential_overrides: dict[str, object], connect
) -> None:
source = self._managed_source()
- self.managed_warehouse_sql_editor_flag.return_value = False
source.job_inputs = {**source.job_inputs, **credential_overrides}
source.save(update_fields=["job_inputs"])
@@ -672,8 +659,6 @@ class TestDirectDuckgresQuery(APIBaseTest):
"credential_kind": "org_root",
},
)
- self.managed_warehouse_sql_editor_flag.return_value = True
-
with self.assertRaisesMessage(ExposedHogQLError, "raw SQL is not allowed"):
HogQLQueryExecutor(
query="SELECT 1",
@@ -733,7 +718,6 @@ class TestDirectDuckgresQuery(APIBaseTest):
connection_metadata=connection_metadata,
direct_query_enabled=direct_query_enabled,
)
- self.managed_warehouse_sql_editor_flag.return_value = False
with self.assertRaises(ExposedHogQLError):
HogQLQueryExecutor(
diff --git a/posthog/hogql_queries/hogql_query_runner.py b/posthog/hogql_queries/hogql_query_runner.py
index 5d17c72d4860..c74a72c67388 100644
--- a/posthog/hogql_queries/hogql_query_runner.py
+++ b/posthog/hogql_queries/hogql_query_runner.py
@@ -33,7 +33,7 @@ from posthog.hogql_queries.insights.paginators import HogQLHasMorePaginator
from posthog.hogql_queries.query_runner import AnalyticsQueryRunner, ExecutionMode
from posthog.models import User
-from products.managed_warehouse.backend.facade import feature_flags as managed_warehouse_feature_flags
+from products.managed_warehouse.backend.facade import query_labels as managed_warehouse_query_labels
from products.warehouse_sources.backend.facade.types import ManagedWarehouseSQLMode
_INFORMATION_SCHEMA_PREFIX = "system.information_schema."
@@ -91,7 +91,7 @@ class HogQLQueryRunner(AnalyticsQueryRunner[HogQLQueryResponse]):
self._validate_direct_connection()
if self._managed_warehouse_sql_mode == ManagedWarehouseSQLMode.BUILT_IN:
return [
- f"{managed_warehouse_feature_flags.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX}{self.query.connectionId}"
+ f"{managed_warehouse_query_labels.MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX}{self.query.connectionId}"
]
return None
diff --git a/posthog/hogql_queries/test/test_hogql_query_runner.py b/posthog/hogql_queries/test/test_hogql_query_runner.py
index 85b791330a57..09a1938bb224 100644
--- a/posthog/hogql_queries/test/test_hogql_query_runner.py
+++ b/posthog/hogql_queries/test/test_hogql_query_runner.py
@@ -26,7 +26,7 @@ from posthog.hogql_queries.hogql_query_runner import HogQLQueryRunner
from posthog.hogql_queries.query_runner import ExecutionMode
from posthog.models.utils import UUIDT
-from products.managed_warehouse.backend.facade.feature_flags import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX
+from products.managed_warehouse.backend.facade.query_labels import MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX
from products.product_analytics.backend.facade.models import InsightVariable
from products.warehouse_sources.backend.facade.models import MANAGED_WAREHOUSE_SOURCE_PREFIX, ExternalDataSource
from products.warehouse_sources.backend.facade.types import ExternalDataSourceType
@@ -230,12 +230,12 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
runner.calculate()
@patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- return_value=True,
+ "posthog.permissions.posthog_feature_flag_enabled",
+ side_effect=AssertionError("managed warehouse query execution must not evaluate a product feature flag"),
)
@patch("posthog.hogql_queries.hogql_query_runner.execute_hogql_query")
- def test_managed_warehouse_cache_and_status_are_not_revoked_by_picker_flag(
- self, mock_execute_hogql_query: MagicMock, managed_warehouse_sql_editor_flag: MagicMock
+ def test_managed_warehouse_cache_and_status_do_not_evaluate_a_feature_flag(
+ self, mock_execute_hogql_query: MagicMock, feature_flag_lookup: MagicMock
) -> None:
source = ExternalDataSource.objects.create(
source_id="managed-source",
@@ -284,15 +284,14 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
expected_query_status_labels,
)
- managed_warehouse_sql_editor_flag.return_value = False
- flag_off_runner = self._create_runner(query)
- self.assertEqual(flag_off_runner.query_status_labels(), expected_query_status_labels)
- self.assertEqual(flag_off_runner.get_cache_key(), built_in_cache_key)
- flag_off_response = cast(
+ second_runner = self._create_runner(query)
+ self.assertEqual(second_runner.query_status_labels(), expected_query_status_labels)
+ self.assertEqual(second_runner.get_cache_key(), built_in_cache_key)
+ second_response = cast(
HogQLQueryResponse,
- flag_off_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS),
+ second_runner.run(execution_mode=ExecutionMode.CALCULATE_BLOCKING_ALWAYS),
)
- self.assertEqual(flag_off_response.results, [(1,)])
+ self.assertEqual(second_response.results, [(1,)])
assert isinstance(source.connection_metadata, dict)
source.connection_metadata["reader_configured"] = False
@@ -301,15 +300,9 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
self._create_runner(query).run()
self.assertEqual(mock_execute_hogql_query.call_count, 2)
- managed_warehouse_sql_editor_flag.assert_not_called()
+ feature_flag_lookup.assert_not_called()
- @patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- return_value=True,
- )
- def test_legacy_managed_cache_and_status_are_not_changed_by_picker_flag(
- self, managed_warehouse_sql_editor_flag: MagicMock
- ) -> None:
+ def test_legacy_managed_cache_and_status_are_stable(self) -> None:
source = ExternalDataSource.objects.create(
source_id="managed-source",
connection_id="managed-connection",
@@ -335,16 +328,14 @@ class TestHogQLQueryRunner(ClickhouseTestMixin, APIBaseTest):
)
query = HogQLQuery(query="select 1::int as value", connectionId=str(source.id), sendRawQuery=True)
- flag_on_runner = self._create_runner(query)
- self.assertIsNone(flag_on_runner.query_status_labels())
- self.assertNotIn("managed_warehouse_sql_mode", flag_on_runner.get_cache_payload())
- flag_on_cache_key = flag_on_runner.get_cache_key()
+ first_runner = self._create_runner(query)
+ self.assertIsNone(first_runner.query_status_labels())
+ self.assertNotIn("managed_warehouse_sql_mode", first_runner.get_cache_payload())
+ first_cache_key = first_runner.get_cache_key()
- managed_warehouse_sql_editor_flag.return_value = False
- flag_off_runner = self._create_runner(query)
- self.assertIsNone(flag_off_runner.query_status_labels())
- self.assertEqual(flag_off_runner.get_cache_key(), flag_on_cache_key)
- managed_warehouse_sql_editor_flag.assert_not_called()
+ second_runner = self._create_runner(query)
+ self.assertIsNone(second_runner.query_status_labels())
+ self.assertEqual(second_runner.get_cache_key(), first_cache_key)
@patch("posthog.hogql_queries.hogql_query_runner.execute_hogql_query")
def test_send_raw_query_uses_raw_query_string_for_direct_connections(self, mock_execute_hogql_query):
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.py
index f58ba0fa1ba2..dd942907904b 100644
--- a/posthog/settings/base_variables.py
+++ b/posthog/settings/base_variables.py
@@ -76,9 +76,6 @@ 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
-)
MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS: float = get_from_env(
"MANAGED_WAREHOUSE_CREDENTIAL_CACHE_REDIS_CONNECT_TIMEOUT_SECONDS", 0.5, type_cast=float
)
diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.py
index 65600191aa31..45a4d235af26 100644
--- a/products/data_warehouse/backend/tasks/tasks.py
+++ b/products/data_warehouse/backend/tasks/tasks.py
@@ -1,7 +1,5 @@
from uuid import UUID
-from django.conf import settings
-
import structlog
from celery import shared_task
from prometheus_client import Counter
@@ -96,9 +94,6 @@ def soft_delete_managed_warehouse_sources_task(organization_id: str) -> None:
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)
@@ -123,13 +118,10 @@ def soft_delete_managed_warehouse_sources_v2_task(organization_id: str, expected
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))
+ soft_delete_managed_warehouse_sources_v2_task.delay(
+ organization_id=str(organization_id),
+ expected_generation=expected_generation,
+ )
@shared_task(
@@ -146,8 +138,6 @@ def ensure_managed_warehouse_direct_source_v2_task(
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,
)
@@ -162,8 +152,6 @@ def ensure_managed_warehouse_direct_source_v2_task(
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),
diff --git a/products/managed_warehouse/backend/facade/feature_flags.py b/products/managed_warehouse/backend/facade/feature_flags.py
index 22d4ba230d95..35f67af6f102 100644
--- a/products/managed_warehouse/backend/facade/feature_flags.py
+++ b/products/managed_warehouse/backend/facade/feature_flags.py
@@ -1,27 +1 @@
-from typing import TYPE_CHECKING
-
-import structlog
-
-from posthog.permissions import posthog_feature_flag_enabled
-
-if TYPE_CHECKING:
- from posthog.models import Team
-
-logger = structlog.get_logger(__name__)
-
DATA_WAREHOUSE_SCENE_FLAG = "data-warehouse-scene"
-MANAGED_WAREHOUSE_SQL_EDITOR_FLAG = "managed-warehouse-sql-editor"
-MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX = f"{MANAGED_WAREHOUSE_SQL_EDITOR_FLAG}:"
-
-
-def is_managed_warehouse_sql_editor_enabled(team: "Team") -> bool:
- try:
- return posthog_feature_flag_enabled(
- MANAGED_WAREHOUSE_SQL_EDITOR_FLAG,
- str(team.uuid),
- organization_id=team.organization_id,
- team_id=team.id,
- )
- except Exception:
- logger.exception("managed_warehouse_sql_editor_feature_flag_check_failed", team_id=team.id)
- return False
diff --git a/products/managed_warehouse/backend/facade/query_labels.py b/products/managed_warehouse/backend/facade/query_labels.py
new file mode 100644
index 000000000000..a731da919034
--- /dev/null
+++ b/products/managed_warehouse/backend/facade/query_labels.py
@@ -0,0 +1,5 @@
+"""Stable query-status labels shared by managed warehouse producers and readers."""
+
+# Stable wire identifier shared by query-status producers and readers. Renaming requires
+# a dual-read rollout and a drain of in-flight query statuses.
+MANAGED_WAREHOUSE_QUERY_STATUS_LABEL_PREFIX = "managed-warehouse-sql-editor:"
diff --git a/products/managed_warehouse/backend/logic/connection.py b/products/managed_warehouse/backend/logic/connection.py
index 762680d3e944..94d7062fb169 100644
--- a/products/managed_warehouse/backend/logic/connection.py
+++ b/products/managed_warehouse/backend/logic/connection.py
@@ -24,7 +24,6 @@ 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
@@ -141,15 +140,19 @@ def _source_config(server: DuckgresServer) -> dict[str, object]:
).to_dict()
-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 = {
+def _dynamic_source_metadata(*, lifecycle_generation: int) -> dict[str, object]:
+ return {
"engine": "duckdb",
"system_managed": True,
"credential_kind": MANAGED_WAREHOUSE_SERVICE_CREDENTIAL_KIND,
"lifecycle_generation": lifecycle_generation,
}
+
+
+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 = _dynamic_source_metadata(lifecycle_generation=lifecycle_generation)
source.job_inputs = {}
source.deleted = False
source.deleted_at = None
@@ -185,13 +188,20 @@ def _ensure_managed_source_locked(
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:
+ if not source.deleted and (
+ _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS
+ or _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 live_dynamic.is_dynamic_managed_warehouse and live_dynamic.connection_metadata == _dynamic_source_metadata(
+ lifecycle_generation=lifecycle_generation
+ ):
+ return live_dynamic
return _set_dynamic_source_auth(live_dynamic, lifecycle_generation=lifecycle_generation)
live_reader = next(
@@ -208,7 +218,9 @@ def _ensure_managed_source_locked(
(
source
for source in sources
- if not source.deleted and _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS
+ if not source.deleted
+ and _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS
+ and source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.EXTERNAL
),
None,
)
@@ -221,6 +233,17 @@ def _ensure_managed_source_locked(
if live_reader is not None:
return live_reader
+ unusable_live_legacy = next(
+ (
+ source
+ for source in sources
+ if not source.deleted and _credential_kind(source) in MANAGED_WAREHOUSE_LEGACY_CREDENTIAL_KINDS
+ ),
+ None,
+ )
+ if unusable_live_legacy is not None:
+ return _set_dynamic_source_auth(unusable_live_legacy, lifecycle_generation=lifecycle_generation)
+
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)
@@ -245,86 +268,7 @@ def _ensure_managed_source_locked(
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,
- },
- )
-
-
-def _ensure_stored_login_source_locked(*, team_id: int, server: DuckgresServer) -> ExternalDataSource:
- existing = next(
- (
- source
- for source in _managed_source_queryset(team_id).select_for_update().order_by("deleted", "-created_at")
- if _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:
- now = timezone.now()
- DataWarehouseTable.raw_objects.filter(
- team_id=team_id,
- external_data_source_id=existing.id,
- deleted=False,
- ).update(deleted=True, deleted_at=now, updated_at=now)
- ExternalDataSchema.objects.filter(team_id=team_id, source_id=existing.id).delete()
- if existing.job_inputs != config:
- existing.job_inputs = config
- update_fields.append("job_inputs")
- if existing.access_method != ExternalDataSource.AccessMethod.DIRECT:
- existing.access_method = ExternalDataSource.AccessMethod.DIRECT
- update_fields.append("access_method")
- if not existing.direct_query_enabled:
- existing.direct_query_enabled = True
- update_fields.append("direct_query_enabled")
- if (
- connection_metadata.get("engine") != "duckdb"
- or connection_metadata.get("system_managed") is not True
- or connection_metadata.get("credential_kind") != "org_root"
- ):
- migrated = {
- **connection_metadata,
- "engine": "duckdb",
- "system_managed": True,
- "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:
- existing.deleted = False
- existing.deleted_at = None
- update_fields.extend(["deleted", "deleted_at"])
- if update_fields:
- existing.save(update_fields=[*update_fields, "updated_at"])
- return existing
-
- return ExternalDataSource.objects.create(
- source_id=str(uuid4()),
- connection_id=str(uuid4()),
- destination_id=str(uuid4()),
- team_id=team_id,
- status=ExternalDataSource.Status.RUNNING,
- source_type=ExternalDataSourceType.POSTGRES,
- job_inputs=config,
- prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
- description=MANAGED_WAREHOUSE_SOURCE_DESCRIPTION,
- access_method=ExternalDataSource.AccessMethod.DIRECT,
- created_via=ExternalDataSource.CreatedVia.WEB,
- direct_query_enabled=True,
- connection_metadata={
- "engine": "duckdb",
- "system_managed": True,
- "credential_kind": "org_root",
- },
+ connection_metadata=_dynamic_source_metadata(lifecycle_generation=lifecycle_generation),
)
@@ -387,34 +331,15 @@ 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."""
+ lifecycle_snapshot = _lifecycle_snapshot(organization_id)
+ if not lifecycle_snapshot.desired_active or lifecycle_snapshot.generation != expected_generation:
+ return None
+ Team.objects.only("id", "organization_id").get(id=team_id, organization_id=organization_id)
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)
- 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,
@@ -512,23 +437,17 @@ def _reconcile_managed_warehouse_source(*, team_id: int, organization_id: str |
def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | UUID) -> None:
"""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
+ lifecycle_snapshot = _lifecycle_snapshot(organization_id)
+ if not lifecycle_snapshot.desired_active:
+ return
+ if lifecycle_snapshot.generation is not None:
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):
+ ensure_managed_warehouse_direct_source(
+ team_id=team_id,
+ organization_id=organization_id,
+ expected_generation=lifecycle_snapshot.generation,
+ )
+ except Team.DoesNotExist:
return
candidates = _managed_source_queryset(team_id).filter(deleted=False).order_by("created_at")
@@ -543,35 +462,6 @@ def reconcile_managed_warehouse_tables(*, team_id: int, organization_id: str | U
)
-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]:
return ExternalDataSource._base_manager.filter(
team__organization_id=organization_id,
@@ -632,8 +522,6 @@ def soft_delete_managed_warehouse_sources(*, organization_id: str | UUID, expect
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()
diff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.py
index 67337d79c317..97ae5c32da86 100644
--- a/products/managed_warehouse/backend/presentation/views.py
+++ b/products/managed_warehouse/backend/presentation/views.py
@@ -367,8 +367,8 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int, sourc
duckgres creates the provisioning team's row from the provision request itself (and
`_complete_provisioning_team_row` pins its legacy table names), so nothing is written
- here. The team gets its auto-provisioned external SQL source and starts its
- earliest-event-date sync, matching the tail that `onboard_team` runs later.
+ here. The team gets its managed SQL-editor source and starts its earliest-event-date
+ sync, matching the tail that `onboard_team` runs later.
Best-effort, mirroring `_persist_duckgres_server`: a failure is logged, not raised, so
the one-time provision password is never lost to it.
@@ -439,19 +439,18 @@ def _ensure_direct_source(team_id: int, organization_id: UUID | str, source_gene
)
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)
+ 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:
diff --git a/products/managed_warehouse/backend/tests/api/test_presentation.py b/products/managed_warehouse/backend/tests/api/test_presentation.py
index 0b3d089ca6c3..3df2370bc7c9 100644
--- a/products/managed_warehouse/backend/tests/api/test_presentation.py
+++ b/products/managed_warehouse/backend/tests/api/test_presentation.py
@@ -350,7 +350,6 @@ def test_provision_succeeds_even_when_the_team_row_completion_fails(mock_request
@pytest.mark.django_db
-@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(
@@ -749,7 +748,6 @@ def test_onboard_team_creates_duckgres_row_with_legacy_names(
@pytest.mark.django_db
-@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")
diff --git a/products/managed_warehouse/backend/tests/test_connection.py b/products/managed_warehouse/backend/tests/test_connection.py
index 2882778f8d1f..0d583e132aa0 100644
--- a/products/managed_warehouse/backend/tests/test_connection.py
+++ b/products/managed_warehouse/backend/tests/test_connection.py
@@ -4,8 +4,9 @@ from typing import TypedDict
import pytest
from unittest.mock import MagicMock, patch
+from django.db import connection as django_connection
from django.db.models import OneToOneField
-from django.test import override_settings
+from django.test.utils import CaptureQueriesContext
from parameterized import parameterized
@@ -241,10 +242,6 @@ def _create_dynamic_source(team: Team, *, lifecycle_generation: int = 1) -> Exte
@pytest.mark.django_db
class TestEnsureManagedWarehouseDirectSource:
- @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)
@@ -441,30 +438,61 @@ class TestEnsureManagedWarehouseDirectSource:
@pytest.mark.django_db
-class TestDynamicSourceCreationGate:
- @override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False)
- def test_gate_off_preserves_the_static_stored_login_source(self) -> None:
+class TestDynamicSourceCompatibility:
+ def test_missing_source_creates_dynamic_auth_without_reading_the_stored_root_credential(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
+ current_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=current_generation,
+ )
+ assert generation is not None
- source = _ensure(team)
+ with CaptureQueriesContext(django_connection) as queries:
+ source = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=generation,
+ )
- 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"]
+ assert source is not None
+ assert source.is_dynamic_managed_warehouse
+ assert source.job_inputs == {}
+ server_table = DuckgresServer._meta.db_table.lower()
+ assert all(server_table not in query["sql"].lower() for query in queries.captured_queries)
+
+ def test_source_creation_does_not_evaluate_product_feature_flags(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ current_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=current_generation,
+ )
+ assert generation is not None
+
+ with patch(
+ "posthog.permissions.posthog_feature_flag_enabled",
+ side_effect=AssertionError("source auth must not evaluate the product feature flag"),
+ ):
+ source = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=generation,
+ )
+
+ assert source is not None
+ assert source.is_dynamic_managed_warehouse
+ assert source.job_inputs == {}
- def test_gate_off_preserves_an_existing_dynamic_source_without_persisting_the_root_secret(self) -> None:
+ def test_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 = _ensure(team)
source.refresh_from_db()
original_metadata = deepcopy(source.connection_metadata)
original_job_inputs = deepcopy(source.job_inputs)
@@ -472,7 +500,33 @@ class TestDynamicSourceCreationGate:
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_preserves_an_existing_static_source_without_reading_duckgres_server(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = _create_stored_login_source(team)
+ source.refresh_from_db()
+ original_job_inputs = deepcopy(source.job_inputs)
+ current_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=current_generation,
+ )
+ assert generation is not None
+
+ with CaptureQueriesContext(django_connection) as queries:
ensured = ensure_managed_warehouse_direct_source(
team_id=team.id,
organization_id=org.id,
@@ -482,16 +536,84 @@ class TestDynamicSourceCreationGate:
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
+ assert ensured.job_inputs == original_job_inputs
+ server_table = DuckgresServer._meta.db_table.lower()
+ assert all(server_table not in query["sql"].lower() for query in queries.captured_queries)
- def test_gate_off_genuine_reprovision_updates_dynamic_generation_and_tombstones_stale_reader(self) -> None:
+ @parameterized.expand(
+ [
+ ("org_root_empty", "org_root", {}),
+ ("org_root_malformed", "org_root", {"host": "", "port": "invalid"}),
+ ("stored_login_empty", "stored_server_login", {}),
+ ("stored_login_malformed", "stored_server_login", {"host": "", "port": "invalid"}),
+ ]
+ )
+ def test_converts_an_unusable_legacy_source_without_reading_duckgres_server(
+ self, _name: str, credential_kind: str, job_inputs: dict[str, object]
+ ) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = _create_stored_login_source(team)
+ source.connection_metadata = {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": credential_kind,
+ }
+ source.job_inputs = job_inputs
+ source.save(update_fields=["connection_metadata", "job_inputs"])
+ assert source.managed_warehouse_sql_mode == ManagedWarehouseSQLMode.UNAVAILABLE
+ generation = get_active_managed_warehouse_source_generation(organization_id=org.id)
+ assert generation is not None
+
+ with CaptureQueriesContext(django_connection) as queries:
+ 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.is_dynamic_managed_warehouse
+ assert ensured.job_inputs == {}
+ assert ensured.connection_metadata == {
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": "duckgres_service",
+ "lifecycle_generation": generation,
+ }
+ assert ExternalDataSource.objects.filter(team_id=team.id).count() == 1
+ server_table = DuckgresServer._meta.db_table.lower()
+ assert all(server_table not in query["sql"].lower() for query in queries.captured_queries)
+
+ def test_preserves_an_existing_project_reader(self) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ reader = _create_project_reader_source(team)
+ current_generation = get_managed_warehouse_source_generation(organization_id=org.id)
+ generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=current_generation,
+ )
+ assert generation is not None
+
+ 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 == reader.id
+ reader.refresh_from_db()
+ assert reader.deleted is False
+
+ def test_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)
+ dynamic = _ensure(team)
reader = _create_project_reader_source(team)
reader_table = DataWarehouseTable.objects.create(
team=team,
@@ -509,8 +631,7 @@ class TestDynamicSourceCreationGate:
)
assert inactive_generation is not None
- with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
- reprovisioned = _ensure(team)
+ reprovisioned = _ensure(team)
assert reprovisioned.id == dynamic.id
assert reprovisioned.is_dynamic_managed_warehouse
@@ -523,7 +644,7 @@ class TestDynamicSourceCreationGate:
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:
+ def test_genuine_reprovision_replaces_a_stale_reader_with_dynamic_auth(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
@@ -536,15 +657,67 @@ class TestDynamicSourceCreationGate:
)
assert inactive_generation is not None
- with override_settings(MANAGED_WAREHOUSE_DYNAMIC_SQL_EDITOR_AUTH_ENABLED=False):
- replacement = _ensure(team)
+ new_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=inactive_generation,
+ )
+ assert new_generation is not None
+ replacement = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=new_generation,
+ )
reader.refresh_from_db()
assert reader.deleted is True
+ assert replacement is not None
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"
+ assert replacement.is_dynamic_managed_warehouse
+ assert replacement.job_inputs == {}
+
+ def test_genuine_reprovision_replaces_stale_static_credentials_with_dynamic_auth_without_reading_root(
+ self,
+ ) -> None:
+ org = Organization.objects.create(name="Org")
+ team = Team.objects.create(organization=org)
+ source = _create_stored_login_source(team)
+ source_table = DataWarehouseTable.objects.create(
+ team=team,
+ name="static_table",
+ format=DataWarehouseTable.TableFormat.Parquet,
+ url_pattern=DIRECT_POSTGRES_URL_PATTERN,
+ external_data_source=source,
+ 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
+ new_generation = activate_managed_warehouse_source_lifecycle(
+ organization_id=org.id,
+ expected_generation=inactive_generation,
+ )
+ assert new_generation is not None
+
+ with CaptureQueriesContext(django_connection) as queries:
+ replacement = ensure_managed_warehouse_direct_source(
+ team_id=team.id,
+ organization_id=org.id,
+ expected_generation=new_generation,
+ )
+
+ source.refresh_from_db()
+ source_table.refresh_from_db()
+ assert replacement is not None
+ assert replacement.id == source.id
+ assert replacement.is_dynamic_managed_warehouse
+ assert replacement.job_inputs == {}
+ assert source_table.deleted is True
+ server_table = DuckgresServer._meta.db_table.lower()
+ assert all(server_table not in query["sql"].lower() for query in queries.captured_queries)
def _source_schema(table_name: str, source_schema: str = "posthog") -> SourceSchema:
@@ -560,10 +733,6 @@ 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)
@@ -671,19 +840,12 @@ class TestReconcileManagedWarehouseTables:
seen_users.append(config.user)
return [_source_schema("events")]
- with (
- patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- side_effect=AssertionError("lifecycle must not evaluate the SQL editor flag"),
- ) as feature_flag,
- patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
- side_effect=discover,
- ),
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
+ side_effect=discover,
):
reconcile_managed_warehouse_tables(team_id=team.id, organization_id=org.id)
- feature_flag.assert_not_called()
assert set(seen_users) == {_CONNECTION["username"], f"posthog_team_{team.id}"}
assert ExternalDataSchema.objects.filter(source=stored_login, name="posthog.events").exists()
assert ExternalDataSchema.objects.filter(source=reader, name="posthog.events").exists()
@@ -1001,8 +1163,7 @@ class TestReconcileManagedWarehouseTables:
).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
+ def test_periodic_reconcile_recovers_a_missing_dynamic_source_without_reading_root_credentials(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
@@ -1017,21 +1178,34 @@ class TestReconcileManagedWarehouseTables:
prefix=MANAGED_WAREHOUSE_SOURCE_PREFIX,
).exists()
- with patch(
- "products.warehouse_sources.backend.temporal.data_imports.sources.postgres.source.PostgresSource.get_schemas",
- return_value=[],
+ with (
+ CaptureQueriesContext(django_connection) as queries,
+ 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=[],
+ ) as get_schemas,
):
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"]
+ assert source.is_dynamic_managed_warehouse
+ assert source.job_inputs == {}
+ get_schemas.assert_called_once()
+ server_table = DuckgresServer._meta.db_table.lower()
+ assert all(server_table not in query["sql"].lower() for query in queries.captured_queries)
- 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
+ def test_periodic_reconcile_does_not_revive_an_unfenced_legacy_tombstone(self) -> None:
org = Organization.objects.create(name="Org")
team = Team.objects.create(organization=org)
_create_server(org)
@@ -1140,10 +1314,6 @@ 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)
@@ -1235,8 +1405,7 @@ class TestManagedWarehouseLifecycle:
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)
+ soft_delete_legacy_managed_warehouse_sources(organization_id=org.id)
reprovisioned.refresh_from_db()
assert reprovisioned.deleted is False
@@ -1255,8 +1424,7 @@ class TestManagedWarehouseLifecycle:
)
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)
+ soft_delete_legacy_managed_warehouse_sources(organization_id=org.id)
source.refresh_from_db()
assert source.deleted is True
@@ -1267,8 +1435,7 @@ class TestManagedWarehouseLifecycle:
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)
+ soft_delete_legacy_managed_warehouse_sources(organization_id=org.id)
source.refresh_from_db()
assert source.deleted is True
@@ -1490,7 +1657,6 @@ def test_ready_status_queues_table_discovery(mock_schedule: MagicMock) -> None:
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")
@@ -1498,15 +1664,6 @@ def test_old_one_argument_cleanup_message_runs_on_a_new_worker(mock_soft_delete:
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)
@@ -1514,8 +1671,7 @@ def test_v2_cleanup_task_carries_the_original_deprovision_generation(mock_soft_d
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:
+def test_source_cleanup_scheduler_uses_the_generation_fenced_task() -> None:
assert soft_delete_managed_warehouse_sources_task.name == (
"products.data_warehouse.backend.tasks.soft_delete_managed_warehouse_sources"
)
@@ -1523,21 +1679,15 @@ def test_source_cleanup_scheduler_uses_a_rolling_compatible_task(dynamic_auth_en
"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()
+ legacy_delay.assert_not_called()
+ v2_delay.assert_called_once_with(organization_id="org-1", expected_generation=7)
-@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)
@@ -1545,17 +1695,7 @@ def test_v2_source_recovery_task_rechecks_the_generation(mock_ensure: MagicMock)
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),
- ):
+def test_source_recovery_scheduler_always_emits_the_generation_fenced_task() -> None:
+ with patch.object(ensure_managed_warehouse_direct_source_v2_task, "delay") as delay:
schedule_managed_warehouse_direct_source_ensure(team_id=42, organization_id="org-1", expected_generation=7)
delay.assert_called_once_with(team_id=42, organization_id="org-1", expected_generation=7)
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 08012e63df1c..d6db13312ffc 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_source.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_source.py
@@ -100,7 +100,6 @@ from products.data_warehouse.backend.facade.api import (
unpause_cdc_extraction_schedule,
)
from products.data_warehouse.backend.facade.models import ExternalDataSourceRevenueAnalyticsConfig
-from products.managed_warehouse.backend.facade import feature_flags as managed_warehouse_feature_flags
from products.revenue_analytics.backend.facade.api import ensure_person_join, remove_person_join
from products.warehouse_sources.backend.facade.api import validate_source_prefix
from products.warehouse_sources.backend.facade.models import (
@@ -4831,24 +4830,22 @@ class ExternalDataSourceViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixi
)
.order_by(self.ordering)
)
- managed_warehouse_enabled = managed_warehouse_feature_flags.is_managed_warehouse_sql_editor_enabled(self.team)
- managed_source = None
- if managed_warehouse_enabled:
- managed_candidates = connection_sources.filter(ExternalDataSource.ready_managed_warehouse_q()).only(
- "id",
- "team_id",
- "prefix",
- "description",
- "connection_metadata",
- "source_type",
- "access_method",
- "direct_query_enabled",
- "job_inputs",
- )
- managed_source = next(
- (source for source in managed_candidates if source.is_dynamic_managed_warehouse),
- None,
- ) or next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)
+ managed_candidates = connection_sources.filter(ExternalDataSource.ready_managed_warehouse_q()).only(
+ "id",
+ "team_id",
+ "prefix",
+ "description",
+ "connection_metadata",
+ "source_type",
+ "access_method",
+ "direct_query_enabled",
+ "job_inputs",
+ )
+ managed_source = next(
+ (source for source in managed_candidates if source.is_dynamic_managed_warehouse),
+ None,
+ ) or next((source for source in managed_candidates if source.is_managed_warehouse_ready), None)
+ if managed_source is not 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/tests/api/test_external_data_source_access_control.py b/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py
index ec605e598068..b862905a5eca 100644
--- a/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py
+++ b/products/warehouse_sources/backend/tests/api/test_external_data_source_access_control.py
@@ -2,7 +2,6 @@ import uuid
import pytest
from posthog.test.base import APIBaseTest
-from unittest.mock import MagicMock, patch
from parameterized import parameterized
from rest_framework import status
@@ -28,18 +27,9 @@ except ImportError:
@pytest.mark.ee
class TestExternalDataSourceAccessControl(APIBaseTest):
- managed_warehouse_sql_editor_flag: MagicMock
-
def setUp(self) -> None:
super().setUp()
- flag_patcher = patch(
- "products.managed_warehouse.backend.facade.feature_flags.posthog_feature_flag_enabled",
- return_value=True,
- )
- self.managed_warehouse_sql_editor_flag = flag_patcher.start()
- self.addCleanup(flag_patcher.stop)
-
# Enable access control features
self.organization.available_product_features = [
{
@@ -427,28 +417,6 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
}
},
),
- (
- "legacy_org_root",
- {
- "connection_metadata": {
- "engine": "duckdb",
- "system_managed": True,
- "credential_kind": "org_root",
- "reader_configured": True,
- }
- },
- ),
- (
- "stored_server_login",
- {
- "connection_metadata": {
- "engine": "duckdb",
- "system_managed": True,
- "credential_kind": "stored_server_login",
- "reader_configured": True,
- }
- },
- ),
(
"spoofed_root_username",
{
@@ -483,15 +451,7 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertNotIn(str(source.id), [item["id"] for item in response.json()])
- @parameterized.expand(
- [
- ("disabled", False),
- ("evaluation_error", RuntimeError("feature flag unavailable")),
- ]
- )
- def test_connections_flag_off_preserves_legacy_managed_source_as_external(
- self, _name: str, flag_result: bool | Exception
- ) -> None:
+ def test_connections_prefers_dynamic_auth_over_reader_and_legacy_sources(self) -> None:
legacy_source = self._create_legacy_managed_source()
ready_reader = self._create_managed_source()
dynamic_source = self._create_managed_source(
@@ -528,30 +488,25 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
access_method=ExternalDataSource.AccessMethod.DIRECT,
created_by=self.user,
)
- if isinstance(flag_result, Exception):
- self.managed_warehouse_sql_editor_flag.side_effect = flag_result
- else:
- self.managed_warehouse_sql_editor_flag.return_value = flag_result
-
response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
[item["id"] for item in response.json()],
- [str(external_source.id), str(legacy_source.id)],
+ [str(dynamic_source.id), str(external_source.id)],
)
- self.assertFalse(
- next(item for item in response.json() if item["id"] == str(legacy_source.id))[
+ self.assertTrue(
+ next(item for item in response.json() if item["id"] == str(dynamic_source.id))[
"is_builtin_managed_warehouse"
]
)
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(legacy_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()])
- def test_connections_flag_on_hides_legacy_source_and_marks_ready_reader_as_built_in(self) -> None:
+ def test_connections_hides_legacy_source_and_marks_ready_reader_as_built_in(self) -> None:
ready_reader = self._create_managed_source()
legacy_source = self._create_legacy_managed_source()
external_source = ExternalDataSource.objects.create(
@@ -573,9 +528,8 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
)
self.assertNotIn(str(legacy_source.id), [item["id"] for item in response.json()])
- def test_connections_flag_off_applies_external_source_access_control_to_legacy_source(self) -> None:
+ def test_connections_applies_external_source_access_control_to_canonical_legacy_source(self) -> None:
legacy_source = self._create_legacy_managed_source()
- self.managed_warehouse_sql_editor_flag.return_value = False
self._create_access_control(self.viewer_user, access_level="none")
self.client.force_login(self.viewer_user)
@@ -597,10 +551,27 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
[(str(legacy_source.id), False)],
)
- def test_connections_flag_off_does_not_fall_back_to_an_older_accessible_legacy_source(self) -> None:
+ @parameterized.expand([("org_root",), ("stored_server_login",)])
+ def test_connections_exposes_a_valid_grandfathered_legacy_source(self, credential_kind: str) -> None:
+ legacy_source = self._create_legacy_managed_source(
+ connection_metadata={
+ "engine": "duckdb",
+ "system_managed": True,
+ "credential_kind": credential_kind,
+ }
+ )
+
+ response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/connections/")
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(
+ [(item["id"], item["is_builtin_managed_warehouse"]) for item in response.json()],
+ [(str(legacy_source.id), False)],
+ )
+
+ def test_connections_does_not_fall_back_to_an_older_accessible_legacy_source(self) -> None:
older_source = self._create_legacy_managed_source()
self._create_legacy_managed_source()
- self.managed_warehouse_sql_editor_flag.return_value = False
self._create_access_control(self.viewer_user, access_level="none")
self._create_access_control(
self.viewer_user,
@@ -682,7 +653,7 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/{source.id}/")
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
- def test_flag_off_preserves_legacy_managed_source_as_read_only_external_resource(self) -> None:
+ def test_preserves_legacy_managed_source_as_read_only_external_resource(self) -> None:
legacy_source = self._create_legacy_managed_source()
ready_reader = self._create_managed_source()
pending_reader = self._create_managed_source(
@@ -703,8 +674,6 @@ class TestExternalDataSourceAccessControl(APIBaseTest):
)
other_team = Team.objects.create(organization=self.organization, name="Other project")
cross_team_legacy = self._create_legacy_managed_source(team=other_team)
- self.managed_warehouse_sql_editor_flag.return_value = False
-
response = self.client.get(f"/api/environments/{self.team.pk}/external_data_sources/")
self.assertEqual(response.status_code, status.HTTP_200_OK)