:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(managed-warehouse): hogtower adapter behind HOGTOWER_API_URL (#112911)
Benjamin Knofe-Vider9252cd03ee5c
diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex ec7d6ac8e3c5..1dbe9dfb416a 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -79,6 +79,10 @@ PERSONAL_SPEND_CROSS_REGION_SECRET: str = get_from_env("PERSONAL_SPEND_CROSS_REGDUCKGRES_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)+# Hogtower - URL and internal secret for the managed warehouse management plane. When+# HOGTOWER_API_URL is set, control-plane calls go to hogtower's /api/v2 instead of duckgres.+HOGTOWER_API_URL: str | None = get_from_env("HOGTOWER_API_URL", optional=True)+HOGTOWER_INTERNAL_SECRET: str | None = get_from_env("HOGTOWER_INTERNAL_SECRET", optional=True)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/managed_warehouse/backend/cp_teams.py b/products/managed_warehouse/backend/cp_teams.pyindex b710d56ecb35..590126b690fc 100644--- a/products/managed_warehouse/backend/cp_teams.py+++ b/products/managed_warehouse/backend/cp_teams.py@@ -1,4 +1,8 @@-"""Read-side client for the duckgres control-plane org-teams API.+"""Read-side client for the managed-warehouse control-plane org-teams API.++The control plane is duckgres (``DUCKGRES_API_URL``) unless ``HOGTOWER_API_URL`` is set,+in which case :mod:`products.managed_warehouse.backend.presentation.hogtower` serves the same reads+from hogtower's /api/v2 in the duckgres response shape.The control plane is the source of truth for per-team managed-warehouse state.This module exposes the CP rows as :class:`CPTeam` values plus a small process-local@@ -29,6 +33,7 @@ import threadingfrom collections.abc import Callablefrom dataclasses import dataclassfrom datetime import date+from functools import partialfrom django.conf import settings@@ -36,6 +41,8 @@ import requests as http_requestsfrom posthog.security.outbound_proxy import internal_requests+from products.managed_warehouse.backend.presentation import hogtower+logger = logging.getLogger(__name__)# TTL for the process-local cache below. Monkeypatchable in tests; sized so sensor@@ -156,7 +163,7 @@ def _cached_rows(return rows-def _rows_from_response(response: http_requests.Response) -> list[dict] | None:+def _rows_from_response(response: http_requests.Response | hogtower.TranslatedResponse) -> list[dict] | None:"""Extract the control-plane team payload without importing DRF presentation code."""status_code = response.status_codeif not 200 <= status_code < 300:@@ -187,23 +194,32 @@ def _fetch_rows(*, organization_id: str | None) -> list[dict] | None:fallback behavior, but returns only its private read-side payload rather than aDRF ``Response``. The caller's cache remains responsible for retry behavior."""- base_url = getattr(settings, "DUCKGRES_API_URL", None)- if not base_url:- logger.warning("cp_teams_request_rejected_api_not_configured (organization_id=%s)", organization_id)- return None-- if organization_id is None:- url = f"{base_url.rstrip('/')}/api/v1/teams"+ send: Callable[[], http_requests.Response | hogtower.TranslatedResponse]+ if hogtower.is_configured():+ if organization_id is None:+ send = partial(hogtower.request, "GET", "", "teams", timeout=30)+ else:+ send = partial(hogtower.request, "GET", organization_id, "/teams", timeout=30)else:- url = f"{base_url.rstrip('/')}/api/v1/orgs/{organization_id}/teams"+ base_url = getattr(settings, "DUCKGRES_API_URL", None)+ if not base_url:+ logger.warning("cp_teams_request_rejected_api_not_configured (organization_id=%s)", organization_id)+ return None++ if organization_id is None:+ url = f"{base_url.rstrip('/')}/api/v1/teams"+ else:+ url = f"{base_url.rstrip('/')}/api/v1/orgs/{organization_id}/teams"++ headers: dict[str, str] = {}+ token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)+ if token:+ headers["X-Duckgres-Internal-Secret"] = token- headers: dict[str, str] = {}- token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)- if token:- headers["X-Duckgres-Internal-Secret"] = token+ send = partial(internal_requests.request, "GET", url, json=None, params=None, headers=headers, timeout=30)try:- response = internal_requests.request("GET", url, json=None, params=None, headers=headers, timeout=30)+ response = send()except http_requests.Timeout:logger.warning("cp_teams_list_request_timed_out (organization_id=%s)", organization_id)return None@@ -234,18 +250,22 @@ def _fetch_all_rows() -> list[dict] | None:def _fetch_ready_warehouse_rows() -> list[dict] | None:"""Read warehouses that can accept backfill connections from the discovery API."""- base_url = getattr(settings, "DUCKGRES_API_URL", None)- if not base_url:- logger.warning("cp_teams_request_rejected_api_not_configured (resource=warehouses)")- return None-- headers: dict[str, str] = {}- token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)- if token:- headers["X-Duckgres-Internal-Secret"] = token-- try:- response = internal_requests.request(+ send: Callable[[], http_requests.Response | hogtower.TranslatedResponse]+ if hogtower.is_configured():+ send = partial(hogtower.request, "GET", "", "warehouses", timeout=30)+ else:+ base_url = getattr(settings, "DUCKGRES_API_URL", None)+ if not base_url:+ logger.warning("cp_teams_request_rejected_api_not_configured (resource=warehouses)")+ return None++ headers: dict[str, str] = {}+ token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)+ if token:+ headers["X-Duckgres-Internal-Secret"] = token++ send = partial(+ internal_requests.request,"GET",f"{base_url.rstrip('/')}/api/v1/warehouses",json=None,@@ -253,6 +273,9 @@ def _fetch_ready_warehouse_rows() -> list[dict] | None:headers=headers,timeout=30,)++ try:+ response = send()except http_requests.Timeout:logger.warning("cp_teams_list_request_timed_out (resource=warehouses)")return Nonediff --git a/products/managed_warehouse/backend/presentation/hogtower.py b/products/managed_warehouse/backend/presentation/hogtower.pynew file mode 100644index 000000000000..f416029a6471--- /dev/null+++ b/products/managed_warehouse/backend/presentation/hogtower.py@@ -0,0 +1,445 @@+"""Hogtower adapter for the managed-warehouse control plane.++Hogtower is the management plane that replaces duckgres' control plane. When+``HOGTOWER_API_URL`` is set, every control-plane call PostHog makes goes to hogtower's+canonical ``/api/v2`` routes instead of duckgres' ``/api/v1`` routes; when it is unset+nothing here runs and the duckgres client is unchanged. Flipping the env var is the+switch.++Callers keep speaking the duckgres v1 vocabulary (``_request("POST", org, "/provision")``+and friends). :func:`request` maps each of those calls onto its v2 route and translates+the v2 response back into the exact v1 body the callers and the UI already parse, so no+caller needs to know which control plane answered.++The return value quacks like a ``requests.Response`` (``status_code``, ``json()``,+``text``) so both transports share the callers' error handling. Transport errors+(``requests.Timeout``, ``requests.ConnectionError``, ...) propagate unchanged.++Deliberately free of DRF: ``cp_teams`` uses this from the data-import sink hot path.+"""++from __future__ import annotations++import re+import json+from collections.abc import Callable+from typing import Any+from urllib.parse import quote++from django.conf import settings++import structlog++from posthog.dataclasses import frozen+from posthog.security.outbound_proxy import internal_requests++logger = structlog.get_logger(__name__)++INTERNAL_SECRET_HEADER = "X-Hogtower-Internal-Secret"++# duckgres' message for DELETE /orgs/:id while the warehouse still exists.+_WAREHOUSE_STILL_EXISTS = (+ "warehouse still exists — deprovision it and wait for teardown to complete before deleting the org"+)++_TEAM_PATH = re.compile(r"/teams/(?P<team_id>[^/]+)")+++def is_configured() -> bool:+ """Whether control-plane calls go to hogtower (``HOGTOWER_API_URL`` is set)."""+ return bool(getattr(settings, "HOGTOWER_API_URL", None))+++@frozen(kw_only=False)+class TranslatedResponse:+ """A control-plane answer in duckgres v1 shape, duck-typed like ``requests.Response``."""++ status_code: int+ body: Any++ def json(self) -> Any:+ return self.body++ @property+ def text(self) -> str:+ return json.dumps(self.body, default=str)++ @property+ def ok(self) -> bool:+ return 200 <= self.status_code < 300+++def _send(+ method: str,+ path: str,+ *,+ json_body: dict | None = None,+ params: dict | None = None,+ timeout: int | float,+) -> TranslatedResponse:+ """One raw call to ``{HOGTOWER_API_URL}/api/v2{path}``."""+ base_url = str(getattr(settings, "HOGTOWER_API_URL", "") or "").rstrip("/")+ token = getattr(settings, "HOGTOWER_INTERNAL_SECRET", None)+ headers: dict[str, str] = {}+ if token:+ headers[INTERNAL_SECRET_HEADER] = token+ resp = internal_requests.request(+ method, f"{base_url}/api/v2{path}", json=json_body, params=params, headers=headers, timeout=timeout+ )+ try:+ body = resp.json()+ except ValueError:+ body = {"error": resp.text[:500]}+ return TranslatedResponse(resp.status_code, body)+++@frozen(kw_only=False)+class _Call:+ """One v1-vocabulary call being translated."""++ org_id: str+ json_body: dict | None+ params: dict | None+ timeout: int | float++ @property+ def warehouse(self) -> str:+ return f"/warehouses/{quote(self.org_id, safe='')}"++ def send(self, method: str, path: str, json_body: dict | None = None, params: dict | None = None):+ return _send(method, path, json_body=json_body, params=params, timeout=self.timeout)+++def _bad_request(message: str) -> TranslatedResponse:+ return TranslatedResponse(400, {"error": message})+++def _dict(value: object) -> dict:+ return value if isinstance(value, dict) else {}+++# --- warehouses -------------------------------------------------------------------------+++def _provision(call: _Call) -> TranslatedResponse:+ """v1 POST /orgs/:id/provision -> v2 POST /warehouses (202; root password returned once)."""+ body = call.json_body or {}+ team: dict[str, Any] = {"id": body.get("team_id") or body.get("default_team_id")}+ if body.get("schema_name"):+ team["schema_name"] = body["schema_name"]+ v2_body: dict[str, Any] = {"id": call.org_id, "database_name": body.get("database_name"), "team": team}+ # ducklake.enabled is implied by v2 (always DuckLake).+ for key in ("metadata_store", "data_store", "trino"):+ if body.get(key) is not None:+ v2_body[key] = body[key]+ resp = call.send("POST", "/warehouses", json_body=v2_body)+ if not resp.ok or not isinstance(resp.body, dict):+ return resp+ root = _dict(resp.body.get("root"))+ out: dict[str, Any] = {+ "status": "provisioning started",+ "org": call.org_id,+ "username": root.get("username") or "root",+ "password": root.get("password", ""),+ }+ bucket = _dict(_dict(resp.body.get("warehouse")).get("data_store")).get("bucket_name")+ if bucket:+ out["bucket"] = bucket+ return TranslatedResponse(resp.status_code, out)+++def _deprovision(call: _Call) -> TranslatedResponse:+ """v1 POST /orgs/:id/deprovision -> v2 DELETE /warehouses/:id (202)."""+ resp = call.send("DELETE", call.warehouse)+ if not resp.ok or not isinstance(resp.body, dict):+ return resp+ return TranslatedResponse(+ resp.status_code, {"status": resp.body.get("status") or "deprovisioning started", "org": call.org_id}+ )+++def _status(call: _Call) -> TranslatedResponse:+ """v1 GET /orgs/:id/warehouse/status -> v2 GET /warehouses/:id (detail)."""+ resp = call.send("GET", call.warehouse)+ if not resp.ok or not isinstance(resp.body, dict):+ return resp+ warehouse = _dict(resp.body.get("warehouse"))+ out: dict[str, Any] = {+ key: warehouse.get(key, "")+ for key in (+ "org_id",+ "state",+ "status_message",+ "s3_state",+ "metadata_store_state",+ "identity_state",+ "secrets_state",+ )+ }+ for key in ("ready_at", "failed_at"):+ if warehouse.get(key) is not None:+ out[key] = warehouse[key]+ if warehouse.get("state") == "ready":+ connection = _dict(resp.body.get("connection"))+ out["connection"] = {+ "host": connection.get("host", ""),+ "port": connection.get("port", 0),+ "database": connection.get("database") or warehouse.get("database_name", ""),+ "username": connection.get("username") or "root",+ }+ bucket = _dict(warehouse.get("data_store")).get("bucket_name")+ if bucket:+ out["bucket"] = bucket+ return TranslatedResponse(resp.status_code, out)+++def _delete_org(call: _Call) -> TranslatedResponse:+ """v1 DELETE /orgs/:id: drop a torn-down warehouse's record so its name can be reused.++ hogtower has no separate record to drop: a warehouse whose teardown finished is+ soft-deleted (its name is free and v2 answers 404 for it). v2 DELETE /warehouses/:id+ is deprovision, which this must never trigger, so the duckgres semantics are+ reproduced from the detail read: gone -> deleted, still live -> 409.+ """+ resp = call.send("GET", call.warehouse)+ if resp.status_code == 404:+ return TranslatedResponse(200, {"deleted": call.org_id})+ if not resp.ok or not isinstance(resp.body, dict):+ return resp+ if _dict(resp.body.get("warehouse")).get("state") == "deleted":+ return TranslatedResponse(200, {"deleted": call.org_id})+ return TranslatedResponse(409, {"error": _WAREHOUSE_STILL_EXISTS})+++def _reset_password(call: _Call) -> TranslatedResponse:+ """v1 POST /orgs/:id/reset-password -> v2 POST /warehouses/:id/root-password (same body)."""+ return call.send("POST", f"{call.warehouse}/root-password")+++def _check_name(call: _Call) -> TranslatedResponse:+ """v1 GET /database-name/check?name= -> v2 GET /database-names/:name."""+ name = (call.params or {}).get("name")+ if not name:+ return _bad_request("name query parameter is required")+ resp = call.send("GET", f"/database-names/{quote(str(name), safe='')}")+ if resp.ok and isinstance(resp.body, dict) and not resp.body.get("reason"):+ # v1 omits an empty reason.+ resp.body.pop("reason", None)+ return resp+++# --- teams ------------------------------------------------------------------------------+++def _list_teams(call: _Call) -> TranslatedResponse:+ """v1 GET /orgs/:id/teams -> v2 GET /warehouses/:id/teams.++ v1 also carries the warehouse's data_imports_table_naming_version; when the v2 teams+ body does not, it is read from the warehouse detail.+ """+ resp = call.send("GET", f"{call.warehouse}/teams")+ if not resp.ok or not isinstance(resp.body, dict):+ return resp+ out = {"teams": resp.body.get("teams") or []}+ naming_version = resp.body.get("data_imports_table_naming_version")+ if not naming_version:+ detail = call.send("GET", call.warehouse)+ if not detail.ok or not isinstance(detail.body, dict):+ return detail+ naming_version = _dict(detail.body.get("warehouse")).get("data_imports_table_naming_version")+ out["data_imports_table_naming_version"] = naming_version or ""+ return TranslatedResponse(resp.status_code, out)+++def _list_all_teams(call: _Call) -> TranslatedResponse:+ """v1 GET /teams (every warehouse) -> v2 GET /teams."""+ resp = call.send("GET", "/teams")+ if not resp.ok or not isinstance(resp.body, dict) or not isinstance(resp.body.get("teams"), list):+ return resp+ teams = [+ {**row, "org_id": row.get("org_id") or row.get("warehouse_id")} if isinstance(row, dict) else row+ for row in resp.body["teams"]+ ]+ return TranslatedResponse(resp.status_code, {"teams": teams})+++def _unwrap_team(resp: TranslatedResponse) -> TranslatedResponse:+ """v2 answers team writes with {"team": row}; v1 answered with the row itself."""+ if resp.ok and isinstance(resp.body, dict) and isinstance(resp.body.get("team"), dict):+ return TranslatedResponse(resp.status_code, resp.body["team"])+ return resp+++def _upsert_team(call: _Call) -> TranslatedResponse:+ """v1 POST /orgs/:id/teams (upsert, team_id in body) -> v2 PUT /warehouses/:id/teams/:team_id."""+ body = call.json_body or {}+ team_id = body.get("team_id")+ if not team_id:+ return _bad_request("team_id is required (a positive PostHog team id)")+ return _unwrap_team(call.send("PUT", f"{call.warehouse}/teams/{quote(str(team_id), safe='')}", json_body=body))+++def _update_team(call: _Call, team_id: str) -> TranslatedResponse:+ """v1 PUT /orgs/:id/teams/:team_id (presence-aware partial update) -> v2 PUT upsert.++ The v2 upsert requires schema_name; absent fields are preserved. So the team's current+ schema_name is read first and sent alongside exactly the fields the caller passed.+ A team the warehouse does not have is a 404, as in v1 (never created by an update).+ """+ listed = call.send("GET", f"{call.warehouse}/teams")+ if not listed.ok or not isinstance(listed.body, dict):+ return listed+ existing = next(+ (+ row+ for row in listed.body.get("teams") or []+ if isinstance(row, dict) and str(row.get("team_id")) == str(team_id)+ ),+ None,+ )+ if existing is None:+ return TranslatedResponse(404, {"error": "team not found"})+ body = {"schema_name": existing.get("schema_name"), **(call.json_body or {})}+ return _unwrap_team(call.send("PUT", f"{call.warehouse}/teams/{quote(team_id, safe='')}", json_body=body))+++def _delete_team(call: _Call, team_id: str) -> TranslatedResponse:+ """v1 DELETE /orgs/:id/teams/:team_id -> v2 DELETE /warehouses/:id/teams/:team_id."""+ resp = call.send("DELETE", f"{call.warehouse}/teams/{quote(team_id, safe='')}")+ if resp.ok and isinstance(resp.body, dict):+ return TranslatedResponse(resp.status_code, {**resp.body, "org": call.org_id})+ return resp+++# --- Trino ------------------------------------------------------------------------------+++def _trino(call: _Call) -> TranslatedResponse:+ """v1 GET /orgs/:id/trino -> v2 GET /warehouses/:id/trino.++ v2 returns {"trino": <tenancy row>, "live": <org detail>}; ``live`` is the duckgres v1+ body (enabled + status with catalog and connection) and is returned as-is. Without+ ``live`` only the tenancy row is known: it is projected onto the v1 shape with no+ catalog or connection, which every caller treats as "Trino not ready".+ """+ resp = call.send("GET", f"{call.warehouse}/trino")+ if not resp.ok or not isinstance(resp.body, dict):+ return resp+ live = resp.body.get("live")+ if isinstance(live, dict) and isinstance(live.get("enabled"), bool):+ return TranslatedResponse(resp.status_code, live)+ tenancy = resp.body.get("trino")+ if not isinstance(tenancy, dict) or tenancy.get("enabled") is not True:+ out: dict[str, Any] = {"enabled": False}+ if isinstance(tenancy, dict) and tenancy.get("backend"):+ out["backend"] = tenancy["backend"]+ return TranslatedResponse(resp.status_code, out)+ trino_status: dict[str, Any] = {+ "org": tenancy.get("org_id") or call.org_id,+ "backend": tenancy.get("backend", ""),+ "tier": tenancy.get("tier", ""),+ "state": tenancy.get("state") or "pending",+ "status_message": tenancy.get("status_message", ""),+ }+ for key in ("ready_at", "failed_at"):+ if tenancy.get(key) is not None:+ trino_status[key] = tenancy[key]+ return TranslatedResponse(+ resp.status_code,+ {"enabled": True, "backend": tenancy.get("backend", ""), "status": trino_status},+ )+++# --- service credentials ----------------------------------------------------------------+++def _mint_credential(call: _Call) -> TranslatedResponse:+ """v1 POST /orgs/:id/service-credentials -> v2 POST /warehouses/:id/service-credentials (same body)."""+ return call.send("POST", f"{call.warehouse}/service-credentials", json_body=call.json_body)+++def _refresh_credential(call: _Call) -> TranslatedResponse:+ """v1 POST /orgs/:id/service-credentials/refresh -> v2 POST .../service-credentials/:cid/refresh."""+ body = dict(call.json_body or {})+ credential_id = body.pop("credential_id", None)+ if not credential_id:+ return _bad_request("credential_id is required")+ return call.send(+ "POST",+ f"{call.warehouse}/service-credentials/{quote(str(credential_id), safe='')}/refresh",+ json_body=body,+ )+++# --- passthroughs -----------------------------------------------------------------------+++def _org_passthrough(suffix: str) -> Callable[[_Call], TranslatedResponse]:+ def handle(call: _Call) -> TranslatedResponse:+ return call.send("GET", f"{call.warehouse}{suffix}", params=call.params)++ return handle+++def _discovery_warehouses(call: _Call) -> TranslatedResponse:+ """v1 GET /warehouses (discovery) -> v2 GET /discovery/warehouses (same body)."""+ return call.send("GET", "/discovery/warehouses")+++# Org-scoped v1 paths ("/..." under /api/v1/orgs/:id) keyed by (method, path).+_ORG_ROUTES: dict[tuple[str, str], Callable[[_Call], TranslatedResponse]] = {+ ("POST", "/provision"): _provision,+ ("POST", "/deprovision"): _deprovision,+ ("GET", "/warehouse/status"): _status,+ ("POST", "/reset-password"): _reset_password,+ ("GET", "/teams"): _list_teams,+ ("POST", "/teams"): _upsert_team,+ ("GET", "/trino"): _trino,+ ("POST", "/service-credentials"): _mint_credential,+ ("POST", "/service-credentials/refresh"): _refresh_credential,+ ("GET", "/monitoring/snapshot"): _org_passthrough("/monitoring/snapshot"),+ ("GET", "/monitoring/series"): _org_passthrough("/monitoring/series"),+}++# Global v1 paths (under /api/v1) keyed by (method, path).+_GLOBAL_ROUTES: dict[tuple[str, str], Callable[[_Call], TranslatedResponse]] = {+ ("GET", "teams"): _list_all_teams,+ ("GET", "database-name/check"): _check_name,+ ("GET", "warehouses"): _discovery_warehouses,+}+++def request(+ method: str,+ organization_id: object,+ path: str,+ *,+ json_body: dict | None = None,+ params: dict | None = None,+ timeout: int | float = 30,+) -> TranslatedResponse:+ """Serve one duckgres-v1-vocabulary control-plane call from hogtower's v2 API.++ ``path`` follows ``presentation.views._request``: "" is the org resource itself,+ "/..." is org-scoped, anything else is a global path.+ """+ method = method.upper()+ call = _Call(org_id=str(organization_id), json_body=json_body, params=params, timeout=timeout)+ handler: Callable[[_Call], TranslatedResponse] | None+ if path == "":+ handler = _delete_org if method == "DELETE" else None+ elif path.startswith("/"):+ handler = _ORG_ROUTES.get((method, path))+ team = _TEAM_PATH.fullmatch(path)+ if handler is None and team is not None:+ team_id = team.group("team_id")+ if method == "PUT":+ return _update_team(call, team_id)+ if method == "DELETE":+ return _delete_team(call, team_id)+ else:+ handler = _GLOBAL_ROUTES.get((method, path))+ if handler is None:+ logger.error("hogtower_adapter_unmapped_route", method=method, path=path)+ return TranslatedResponse(500, {"error": f"No hogtower mapping for {method} {path or '/'}"})+ return handler(call)diff --git a/products/managed_warehouse/backend/presentation/views.py b/products/managed_warehouse/backend/presentation/views.pyindex 3433e0b52051..db733a86617b 100644--- a/products/managed_warehouse/backend/presentation/views.py+++ b/products/managed_warehouse/backend/presentation/views.py@@ -11,7 +11,9 @@ per organization (not per team)."""import re+from collections.abc import Callablefrom datetime import date+from functools import partialfrom typing import Literal, TypedDictfrom uuid import UUID@@ -26,6 +28,7 @@ from rest_framework.response import Responsefrom posthog.security.outbound_proxy import internal_requestsfrom products.managed_warehouse.backend.facade.feature_flags import DATA_WAREHOUSE_SCENE_FLAG+from products.managed_warehouse.backend.presentation import hogtowerlogger = structlog.get_logger(__name__)@@ -135,7 +138,11 @@ def _request(timeout: int = 30,require_enabled: bool = True,) -> Response:- """Proxy a request to the duckgres provisioning API, gated on the org's feature flag.+ """Proxy a request to the managed-warehouse control plane, gated on the org's feature flag.++ The control plane is duckgres (`DUCKGRES_API_URL`, /api/v1) unless `HOGTOWER_API_URL`+ is set, in which case the same call is served by hogtower's /api/v2 through+ `products.managed_warehouse.backend.presentation.hogtower`, which returns the duckgres v1 body.An empty path targets the org resource itself (`/api/v1/orgs/{org}`, e.g. to delete it);paths starting with "/" are org-scoped (`/api/v1/orgs/{org}{path}`); others are global@@ -150,30 +157,40 @@ def _request(if require_enabled and not is_enabled(organization_id):return Response({"error": "This feature is not enabled"}, status=status.HTTP_403_FORBIDDEN)- base_url = getattr(settings, "DUCKGRES_API_URL", None)- token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)org_id = str(organization_id)+ send: Callable[[], http_requests.Response | hogtower.TranslatedResponse]+ if hogtower.is_configured():+ # hogtower serves the same calls from its /api/v2 routes, translated back to the+ # duckgres v1 bodies below.+ send = partial(hogtower.request, method, org_id, path, json_body=json_body, params=params, timeout=timeout)+ else:+ base_url = getattr(settings, "DUCKGRES_API_URL", None)+ token = getattr(settings, "DUCKGRES_INTERNAL_SECRET", None)- if not base_url:- logger.warning("Provisioning request rejected: DUCKGRES_API_URL not configured", organization_id=org_id)- return Response(- {"error": "Managed warehouse provisioning is not configured"},- status=status.HTTP_501_NOT_IMPLEMENTED,- )+ if not base_url:+ logger.warning("Provisioning request rejected: DUCKGRES_API_URL not configured", organization_id=org_id)+ return Response(+ {"error": "Managed warehouse provisioning is not configured"},+ status=status.HTTP_501_NOT_IMPLEMENTED,+ )- if path == "":- url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}"- elif path.startswith("/"):- url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}{path}"- else:- url = f"{base_url.rstrip('/')}/api/v1/{path}"+ if path == "":+ url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}"+ elif path.startswith("/"):+ url = f"{base_url.rstrip('/')}/api/v1/orgs/{org_id}{path}"+ else:+ url = f"{base_url.rstrip('/')}/api/v1/{path}"- headers = {}- if token:- headers["X-Duckgres-Internal-Secret"] = token+ headers = {}+ if token:+ headers["X-Duckgres-Internal-Secret"] = token++ send = partial(+ internal_requests.request, method, url, json=json_body, params=params, headers=headers, timeout=timeout+ )try:- resp = internal_requests.request(method, url, json=json_body, params=params, headers=headers, timeout=timeout)+ resp = send()except http_requests.Timeout:logger.warning("Provisioning API timeout", method=method, path=path, organization_id=org_id)return Response({"error": "Provisioning service timed out"}, status=status.HTTP_504_GATEWAY_TIMEOUT)@@ -980,8 +997,8 @@ def deprovision_for_org_deletion(organization_id: UUID | str) -> None:)returnif resp.status_code == status.HTTP_501_NOT_IMPLEMENTED:- # DUCKGRES_API_URL is not configured (e.g. a dev/env-var-backed DuckgresServer- # row): there is no control plane to deprovision against.+ # Neither HOGTOWER_API_URL nor DUCKGRES_API_URL is configured (e.g. a+ # dev/env-var-backed DuckgresServer row): there is no control plane to deprovision against.logger.warning("Managed warehouse deprovisioning skipped: provisioning API not configured",organization_id=org_id,diff --git a/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_form.html b/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_form.htmlindex 74c9f624a8ef..9bd7df00c6d6 100644--- a/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_form.html+++ b/products/managed_warehouse/backend/templates/admin/managed_warehouse/duckgres_server/provision_form.html@@ -10,7 +10,8 @@</p><p><strong>This makes a real control-plane call.</strong> In environments where- <code>DUCKGRES_API_URL</code> is unset, it returns "not configured" and persists nothing.+ neither <code>HOGTOWER_API_URL</code> nor <code>DUCKGRES_API_URL</code> is set, it returns "not configured"+ and persists nothing.</p><form method="post">{% csrf_token %}diff --git a/products/managed_warehouse/backend/tests/test_hogtower.py b/products/managed_warehouse/backend/tests/test_hogtower.pynew file mode 100644index 000000000000..5a43bc9a5da8--- /dev/null+++ b/products/managed_warehouse/backend/tests/test_hogtower.py@@ -0,0 +1,529 @@+from datetime import date+from uuid import uuid4++import pytest+from unittest.mock import MagicMock, patch++from django.test import override_settings++import requests++from products.managed_warehouse.backend import cp_teams+from products.managed_warehouse.backend.presentation import (+ hogtower,+ views as managed_warehouse,+)+from products.managed_warehouse.backend.service_credentials import (+ mint_service_credential,+ refresh_service_credential,+ renew_service_credential,+)+from products.managed_warehouse.backend.trino_compiler import get_ready_trino_catalog_name+from products.managed_warehouse.backend.trino_target import get_ready_trino_connection_target++BASE = "http://hogtower.invalid"+ORG = "0194d640-5db4-0000-6cde-48d6114c0f99"+PRINCIPAL = "user:test"++# Never a real secret.+_FAKE_SECRET = "test-plaintext-sentinel-not-a-real-grant"++HOGTOWER = override_settings(+ HOGTOWER_API_URL=f"{BASE}/",+ HOGTOWER_INTERNAL_SECRET="ht-secret",+ # Set too, to prove hogtower wins when both are configured.+ DUCKGRES_API_URL="http://duckgres.invalid",+ DUCKGRES_INTERNAL_SECRET="dg-secret",+)+++def _http(status_code: int, body: object) -> MagicMock:+ resp = MagicMock(status_code=status_code, text=str(body))+ resp.json.return_value = body+ return resp+++class FakeHogtower:+ """Answers hogtower v2 calls from a (method, path) table and records every call."""++ def __init__(self, routes: dict[tuple[str, str], tuple[int, object]]) -> None:+ self.routes = routes+ self.calls: list[dict] = []++ def __call__(self, method: str, url: str, *, json=None, params=None, headers=None, timeout=None) -> MagicMock:+ assert url.startswith(f"{BASE}/api/v2/"), url+ path = url.removeprefix(f"{BASE}/api/v2")+ self.calls.append(+ {"method": method, "path": path, "json": json, "params": params, "headers": headers, "timeout": timeout}+ )+ if (method, path) not in self.routes:+ return _http(404, {"error": "not found"})+ return _http(*self.routes[(method, path)])++ @property+ def paths(self) -> list[tuple[str, str]]:+ return [(call["method"], call["path"]) for call in self.calls]+++def fake(request):+ routes = getattr(request, "param", {})+ fake = FakeHogtower(routes)+ with (+ HOGTOWER,+ patch("products.managed_warehouse.backend.presentation.hogtower.internal_requests.request", side_effect=fake),+ ):+ yield fake+++def _routes(routes: dict[tuple[str, str], tuple[int, object]]):+ return pytest.mark.parametrize("fake", [routes], indirect=True)+++W = f"/warehouses/{ORG}"++_WAREHOUSE = {+ "org_id": ORG,+ "database_name": "acme",+ "data_imports_table_naming_version": "copy_v1",+ "data_store": {"kind": "s3bucket", "bucket_name": "posthog-duckling-acme"},+ "state": "ready",+ "status_message": "Ready",+ "metadata_store_state": "ready",+ "s3_state": "ready",+ "identity_state": "ready",+ "secrets_state": "ready",+ "provisioning_started_at": "2026-10-01T00:00:00Z",+ "ready_at": "2026-10-01T00:05:00Z",+ "failed_at": None,+}++_TEAM = {+ "org_id": ORG,+ "team_id": 7,+ "schema_name": "acme_prod",+ "enabled": True,+ "backfill_enabled": True,+ "events_table_name": "events_acme_prod",+ "earliest_event_date": None,+}+++def _detail(**warehouse_overrides: object) -> tuple[int, dict]:+ warehouse = {**_WAREHOUSE, **warehouse_overrides}+ connection = (+ {"host": "acme.dw.us.postwh.com", "port": 5432, "database": "acme", "username": "root"}+ if warehouse["state"] == "ready"+ else None+ )+ body: dict = {"warehouse": warehouse, "teams": [_TEAM], "users": []}+ if connection:+ body["connection"] = connection+ return 200, body+++def _mapped(method: str, path: str, **kwargs) -> hogtower.TranslatedResponse:+ return hogtower.request(method, ORG, path, **kwargs)+++class TestTransport:+ @_routes({("GET", f"{W}/teams"): (200, {"teams": [], "data_imports_table_naming_version": "copy_v1"})})+ def test_sends_the_hogtower_secret_header_and_timeout(self, fake: FakeHogtower) -> None:+ _mapped("GET", "/teams", timeout=12)++ assert fake.calls[0]["headers"] == {"X-Hogtower-Internal-Secret": "ht-secret"}+ assert fake.calls[0]["timeout"] == 12++ def test_non_json_body_becomes_an_error_body(self) -> None:+ resp = MagicMock(status_code=502, text="<html>bad gateway</html>")+ resp.json.side_effect = ValueError+ with (+ HOGTOWER,+ patch(+ "products.managed_warehouse.backend.presentation.hogtower.internal_requests.request", return_value=resp+ ),+ ):+ out = _mapped("POST", "/reset-password")++ assert (out.status_code, out.json()) == (502, {"error": "<html>bad gateway</html>"})++ def test_unmapped_route_fails_without_calling_hogtower(self, fake: FakeHogtower) -> None:+ out = _mapped("PATCH", "/teams")++ assert out.status_code == 500+ assert fake.calls == []++ def test_is_configured_follows_the_setting(self) -> None:+ with override_settings(HOGTOWER_API_URL=None):+ assert not hogtower.is_configured()+ with override_settings(HOGTOWER_API_URL=BASE):+ assert hogtower.is_configured()+++class TestWarehouseRoutes:+ @_routes(+ {+ ("POST", "/warehouses"): (+ 202,+ {+ "warehouse": {**_WAREHOUSE, "state": "pending"},+ "root": {"username": "root", "password": _FAKE_SECRET, "database": "acme"},+ },+ )+ }+ )+ def test_provision_posts_warehouse_and_returns_the_v1_body(self, fake: FakeHogtower) -> None:+ out = _mapped(+ "POST",+ "/provision",+ json_body={+ "database_name": "acme",+ "team_id": 7,+ "schema_name": "acme_prod",+ "ducklake": {"enabled": True},+ "metadata_store": {"type": "cnpg-shard"},+ "data_store": {"type": "s3bucket"},+ "trino": {"enabled": True},+ },+ )++ assert fake.calls[0]["json"] == {+ "id": ORG,+ "database_name": "acme",+ "team": {"id": 7, "schema_name": "acme_prod"},+ "metadata_store": {"type": "cnpg-shard"},+ "data_store": {"type": "s3bucket"},+ "trino": {"enabled": True},+ }+ assert (out.status_code, out.json()) == (+ 202,+ {+ "status": "provisioning started",+ "org": ORG,+ "username": "root",+ "password": _FAKE_SECRET,+ "bucket": "posthog-duckling-acme",+ },+ )++ @_routes({("POST", "/warehouses"): (409, {"error": "warehouse already exists in non-terminal state"})})+ def test_provision_passes_errors_through(self, fake: FakeHogtower) -> None:+ out = _mapped("POST", "/provision", json_body={"database_name": "acme", "team_id": 7})++ assert (out.status_code, out.json()) == (409, {"error": "warehouse already exists in non-terminal state"})++ @_routes({("DELETE", W): (202, {"status": "deprovisioning started", "id": ORG})})+ def test_deprovision_deletes_the_warehouse(self, fake: FakeHogtower) -> None:+ out = _mapped("POST", "/deprovision")++ assert fake.paths == [("DELETE", W)]+ assert (out.status_code, out.json()) == (202, {"status": "deprovisioning started", "org": ORG})++ @_routes({("GET", W): _detail()})+ def test_status_projects_the_detail_onto_the_v1_status(self, fake: FakeHogtower) -> None:+ out = _mapped("GET", "/warehouse/status")++ assert (out.status_code, out.json()) == (+ 200,+ {+ "org_id": ORG,+ "state": "ready",+ "status_message": "Ready",+ "s3_state": "ready",+ "metadata_store_state": "ready",+ "identity_state": "ready",+ "secrets_state": "ready",+ "ready_at": "2026-10-01T00:05:00Z",+ "connection": {"host": "acme.dw.us.postwh.com", "port": 5432, "database": "acme", "username": "root"},+ "bucket": "posthog-duckling-acme",+ },+ )++ @_routes({("GET", W): _detail(state="provisioning", ready_at=None, data_store={"kind": "external"})})+ def test_status_omits_connection_and_bucket_until_known(self, fake: FakeHogtower) -> None:+ body = _mapped("GET", "/warehouse/status").json()++ assert body["state"] == "provisioning"+ assert "connection" not in body+ assert "bucket" not in body+ assert "ready_at" not in body++ @_routes({("POST", f"{W}/root-password"): (200, {"username": "root", "password": _FAKE_SECRET})})+ def test_reset_password_rotates_root(self, fake: FakeHogtower) -> None:+ out = _mapped("POST", "/reset-password")++ assert (out.status_code, out.json()) == (200, {"username": "root", "password": _FAKE_SECRET})++ @pytest.mark.parametrize(+ "fake, expected",+ [+ ({}, (200, {"deleted": ORG})),+ ({("GET", W): _detail(state="deleted")}, (200, {"deleted": ORG})),+ ({("GET", W): _detail(state="deleting")}, (409, {"error": hogtower._WAREHOUSE_STILL_EXISTS})),+ ({("GET", W): (500, {"error": "db down"})}, (500, {"error": "db down"})),+ ],+ indirect=["fake"],+ )+ def test_delete_org_never_deprovisions(self, fake: FakeHogtower, expected: tuple[int, dict]) -> None:+ out = _mapped("DELETE", "")++ assert (out.status_code, out.json()) == expected+ assert fake.paths == [("GET", W)]++ @_routes({("GET", "/database-names/acme"): (200, {"name": "acme", "available": True, "reason": ""})})+ def test_check_name_drops_an_empty_reason(self, fake: FakeHogtower) -> None:+ out = hogtower.request("GET", ORG, "database-name/check", params={"name": "acme"})++ assert (out.status_code, out.json()) == (200, {"name": "acme", "available": True})++ @_routes(+ {+ ("GET", f"{W}/monitoring/snapshot"): (200, {"sessions": 1}),+ ("GET", f"{W}/monitoring/series"): (200, {"points": []}),+ }+ )+ def test_monitoring_is_passed_through(self, fake: FakeHogtower) -> None:+ assert _mapped("GET", "/monitoring/snapshot").json() == {"sessions": 1}+ params = {"metric": "query_rate", "window": "1h"}+ assert _mapped("GET", "/monitoring/series", params=params).json() == {"points": []}+ assert fake.calls[1]["params"] == params+++class TestTeamRoutes:+ @_routes({("GET", f"{W}/teams"): (200, {"teams": [_TEAM]}), ("GET", W): _detail()})+ def test_list_teams_carries_the_naming_version_from_the_warehouse(self, fake: FakeHogtower) -> None:+ out = _mapped("GET", "/teams")++ assert out.json() == {"teams": [_TEAM], "data_imports_table_naming_version": "copy_v1"}++ @_routes({("GET", f"{W}/teams"): (200, {"teams": [_TEAM], "data_imports_table_naming_version": "copy_v1"})})+ def test_list_teams_uses_one_call_when_v2_carries_the_naming_version(self, fake: FakeHogtower) -> None:+ assert _mapped("GET", "/teams").json()["data_imports_table_naming_version"] == "copy_v1"+ assert fake.paths == [("GET", f"{W}/teams")]++ @_routes({("GET", "/teams"): (200, {"teams": [{**_TEAM, "org_id": "", "warehouse_id": ORG}]})})+ def test_list_all_teams_keys_rows_by_org(self, fake: FakeHogtower) -> None:+ out = hogtower.request("GET", "", "teams")++ assert out.json()["teams"][0]["org_id"] == ORG++ @_routes({("PUT", f"{W}/teams/7"): (200, {"team": _TEAM})})+ def test_upsert_puts_the_team_and_unwraps_it(self, fake: FakeHogtower) -> None:+ body = {"team_id": 7, "schema_name": "acme_prod", "events_table_name": "events_acme_prod"}+ out = _mapped("POST", "/teams", json_body=body)++ assert fake.calls[0]["json"] == body+ assert (out.status_code, out.json()) == (200, _TEAM)++ @_routes({("GET", f"{W}/teams"): (200, {"teams": [_TEAM]}), ("PUT", f"{W}/teams/7"): (200, {"team": _TEAM})})+ def test_update_sends_only_the_given_fields_plus_the_current_schema(self, fake: FakeHogtower) -> None:+ out = _mapped("PUT", "/teams/7", json_body={"earliest_event_date": "2024-01-02"})++ assert out.status_code == 200+ assert fake.calls[1]["json"] == {"schema_name": "acme_prod", "earliest_event_date": "2024-01-02"}++ @_routes({("GET", f"{W}/teams"): (200, {"teams": [_TEAM]})})+ def test_update_of_an_unknown_team_is_a_404_and_creates_nothing(self, fake: FakeHogtower) -> None:+ out = _mapped("PUT", "/teams/8", json_body={"earliest_event_date": "2024-01-02"})++ assert out.status_code == 404+ assert fake.paths == [("GET", f"{W}/teams")]++ @_routes({("DELETE", f"{W}/teams/7"): (200, {"deleted": 7})})+ def test_delete_team(self, fake: FakeHogtower) -> None:+ out = _mapped("DELETE", "/teams/7")++ assert (out.status_code, out.json()) == (200, {"deleted": 7, "org": ORG})++ @_routes({("DELETE", f"{W}/teams/7"): (409, {"error": "cannot delete the warehouse's last team"})})+ def test_delete_last_team_conflict_is_preserved(self, fake: FakeHogtower) -> None:+ assert _mapped("DELETE", "/teams/7").status_code == 409+++_TRINO_LIVE = {+ "enabled": True,+ "backend": "hoglake",+ "status": {+ "org": ORG,+ "state": "ready",+ "trino_catalog_name": "acme_catalog",+ "connection": {"host": "acme.trino.example", "port": 443, "username": "root"},+ },+}+++class TestTrinoRoute:+ @_routes({("GET", f"{W}/trino"): (200, {"trino": {"org_id": ORG, "enabled": True}, "live": _TRINO_LIVE})})+ def test_live_detail_is_the_v1_body(self, fake: FakeHogtower) -> None:+ assert _mapped("GET", "/trino").json() == _TRINO_LIVE++ @_routes({("GET", f"{W}/trino"): (200, {"trino": None})})+ def test_no_tenancy_is_disabled(self, fake: FakeHogtower) -> None:+ assert _mapped("GET", "/trino").json() == {"enabled": False}++ @_routes(+ {+ ("GET", f"{W}/trino"): (+ 200,+ {"trino": {"org_id": ORG, "enabled": True, "backend": "hoglake", "tier": "", "state": "ready"}},+ )+ }+ )+ def test_tenancy_without_live_detail_is_never_ready_for_queries(self, fake: FakeHogtower) -> None:+ body = _mapped("GET", "/trino").json()++ assert body["enabled"] is True+ assert body["status"]["state"] == "ready"+ assert "connection" not in body["status"]+ assert get_ready_trino_catalog_name(ORG) is None+ assert get_ready_trino_connection_target(ORG) is None++ @_routes({("GET", f"{W}/trino"): (200, {"trino": {"org_id": ORG, "enabled": True}, "live": _TRINO_LIVE})})+ def test_trino_callers_read_the_ready_target(self, fake: FakeHogtower) -> None:+ assert get_ready_trino_catalog_name(ORG) == "acme_catalog"+ target = get_ready_trino_connection_target(ORG)+ assert target is not None+ assert (target.host, target.port, target.catalog, target.username) == (+ "acme.trino.example",+ 443,+ "acme_catalog",+ "root",+ )+++_CID = "svc_a1b2c3d4e5f60718293a4b5c"+_CREDENTIAL = {+ "credential_id": _CID,+ "credential_secret": _FAKE_SECRET,+ "secret_rotated": True,+ "expires_at": "2026-08-11T13:00:00Z",+ "connect": {"host": "acme.dw.us.postwh.com", "port": 5432, "database": "ducklake", "sslmode": "require"},+}+++class TestServiceCredentials:+ @_routes({("POST", f"{W}/service-credentials"): (200, _CREDENTIAL)})+ def test_mint(self, fake: FakeHogtower) -> None:+ credential = mint_service_credential(ORG, 7, principal="dagster:events-backfill", ttl_seconds=900)++ assert credential.credential_id == _CID+ assert fake.calls[0]["json"] == {"principal": "dagster:events-backfill", "ttl_seconds": 900}++ @_routes({("POST", f"{W}/service-credentials/{_CID}/refresh"): (200, _CREDENTIAL)})+ def test_refresh_addresses_the_credential_in_the_path(self, fake: FakeHogtower) -> None:+ credential = refresh_service_credential(ORG, _CID, ttl_seconds=900)++ assert credential.credential_secret == _FAKE_SECRET+ assert fake.calls[0]["json"] == {"ttl_seconds": 900}++ @_routes(+ {+ ("POST", f"{W}/service-credentials/{_CID}/refresh"): (+ 200,+ {**_CREDENTIAL, "credential_secret": "", "secret_rotated": False},+ )+ }+ )+ def test_renew_keeps_the_secret(self, fake: FakeHogtower) -> None:+ credential = renew_service_credential(ORG, _CID, credential_secret=_FAKE_SECRET, ttl_seconds=900)++ assert credential.credential_secret == _FAKE_SECRET+ assert fake.calls[0]["json"] == {"ttl_seconds": 900, "rotate_secret": False}+++@patch("products.managed_warehouse.backend.presentation.views.is_enabled", return_value=True)+class TestViewsUseHogtower:+ @_routes({("GET", W): _detail(state="deleting")})+ def test_request_never_touches_duckgres(self, _enabled: MagicMock, fake: FakeHogtower) -> None:+ with patch("products.managed_warehouse.backend.presentation.views.internal_requests") as duckgres:+ resp = managed_warehouse.delete_org(ORG, triggered_by=PRINCIPAL)++ duckgres.request.assert_not_called()+ assert resp.status_code == 409++ def test_transport_errors_map_like_duckgres(self, _enabled: MagicMock) -> None:+ with (+ HOGTOWER,+ patch(+ "products.managed_warehouse.backend.presentation.hogtower.internal_requests.request",+ side_effect=requests.Timeout,+ ),+ ):+ resp = managed_warehouse.list_teams(ORG)++ assert (resp.status_code, resp.data) == (504, {"error": "Provisioning service timed out"})++ @_routes({("GET", "/database-names/acme"): (200, {"name": "acme", "available": False, "reason": ""})})+ def test_check_name(self, _enabled: MagicMock, fake: FakeHogtower) -> None:+ resp = managed_warehouse.check_name(ORG, "acme")++ assert (resp.status_code, resp.data) == (200, {"name": "acme", "available": False})++ @_routes(+ {+ ("GET", f"{W}/teams"): (200, {"teams": [_TEAM], "data_imports_table_naming_version": "copy_v1"}),+ ("PUT", f"{W}/teams/7"): (200, {"team": _TEAM}),+ }+ )+ def test_push_earliest_event_date(self, _enabled: MagicMock, fake: FakeHogtower) -> None:+ assert managed_warehouse.push_team_earliest_event_date(ORG, 7, date(2024, 1, 2)) is True+ assert fake.calls[-1]["json"] == {"schema_name": "acme_prod", "earliest_event_date": "2024-01-02"}++ @override_settings(CLOUD_DEPLOYMENT="US")+ @_routes({("GET", W): _detail(data_store={"kind": "external"})})+ def test_status_for_presents_the_connection(self, _enabled: MagicMock, fake: FakeHogtower) -> None:+ resp = managed_warehouse.status_for(ORG)++ assert resp.status_code == 200+ assert resp.data["connection"]["host"] == "acme.dw.us.postwh.com"+ assert resp.data["connection"]["database"] == "ducklake"+++class TestCPTeamsUseHogtower:+ @pytest.fixture(autouse=True)+ def _clear_cache(self):+ cp_teams.clear_cache()+ yield+ cp_teams.clear_cache()++ @_routes({("GET", f"{W}/teams"): (200, {"teams": [_TEAM], "data_imports_table_naming_version": "copy_v1"})})+ def test_org_rows(self, fake: FakeHogtower) -> None:+ teams = cp_teams.list_org_teams(ORG)++ assert teams is not None+ assert [(t.team_id, t.data_imports_table_naming_version) for t in teams] == [(7, "copy_v1")]++ @_routes(+ {+ ("GET", "/teams"): (200, {"teams": [{**_TEAM, "warehouse_id": ORG}]}),+ ("GET", "/discovery/warehouses"): (+ 200,+ {+ "warehouses": [+ {"org_id": ORG, "state": "ready"},+ {"org_id": str(uuid4()), "state": "resharding"},+ ]+ },+ ),+ }+ )+ def test_enabled_backfills_use_teams_and_discovery(self, fake: FakeHogtower) -> None:+ teams = cp_teams.list_enabled_backfills()++ assert teams is not None+ assert [t.team_id for t in teams] == [7]+ assert set(fake.paths) == {("GET", "/teams"), ("GET", "/discovery/warehouses")}++ @_routes({("GET", f"{W}/teams"): (503, {"error": "unavailable"})})+ def test_unusable_answer_is_none(self, fake: FakeHogtower) -> None:+ assert cp_teams.list_org_teams(ORG) is None++ def test_transport_error_is_none(self) -> None:+ with (+ HOGTOWER,+ patch(+ "products.managed_warehouse.backend.presentation.hogtower.internal_requests.request",+ side_effect=requests.ConnectionError,+ ),+ ):+ assert cp_teams.list_org_teams(ORG) is None