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): skip backfills for non-ready warehouses (#83653)

Benjamin Knofe-Viderad68db0dc762
diff --git a/posthog/dags/README_DUCKLINGS.md b/posthog/dags/README_DUCKLINGS.md
index da3f0880fe22..4e6899186038 100644
--- a/posthog/dags/README_DUCKLINGS.md
+++ b/posthog/dags/README_DUCKLINGS.md
@@ -190,6 +190,10 @@ If multiple partitions for the same team run concurrently, they may race to crea
- **DuckgresServer model**: `products/managed_warehouse/backend/models.py`
- **Control-plane team state**: `products/managed_warehouse/backend/cp_teams.py` and `products/managed_warehouse/backend/team_state.py`
+Backfill sensors only schedule teams with backfills enabled in a managed warehouse that reports `state: ready`.
+The sensor skips provisioning, failed, deleting, deleted, and resharding warehouses.
+If either control-plane listing is unavailable, the sensor tick schedules no new work and retries on its next tick.
+
## S3 Path Structure
Each export fans a partition out across many right-sized Parquet files (one per
diff --git a/products/managed_warehouse/backend/cp_teams.py b/products/managed_warehouse/backend/cp_teams.py
index b38d38264778..b710d56ecb35 100644
--- a/products/managed_warehouse/backend/cp_teams.py
+++ b/products/managed_warehouse/backend/cp_teams.py
@@ -232,6 +232,68 @@ def _fetch_all_rows() -> list[dict] | None:
return _fetch_rows(organization_id=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(
+ "GET",
+ f"{base_url.rstrip('/')}/api/v1/warehouses",
+ json=None,
+ params=None,
+ headers=headers,
+ timeout=30,
+ )
+ except http_requests.Timeout:
+ logger.warning("cp_teams_list_request_timed_out (resource=warehouses)")
+ return None
+ except http_requests.ConnectionError:
+ logger.warning("cp_teams_list_request_unreachable (resource=warehouses)")
+ return None
+ except Exception:
+ logger.exception("cp_teams_list_request_failed (resource=warehouses)")
+ return None
+
+ if not 200 <= response.status_code < 300:
+ logger.warning(
+ "cp_teams_list_request_error (resource=warehouses, status_code=%s, response_body=%s)",
+ response.status_code,
+ response.text[:500],
+ )
+ return None
+ try:
+ data = response.json()
+ except ValueError:
+ return None
+ if not isinstance(data, dict) or not isinstance(data.get("warehouses"), list):
+ return None
+ return [row for row in data["warehouses"] if isinstance(row, dict) and row.get("state") == "ready"]
+
+
+def _ready_warehouse_org_ids() -> set[str] | None:
+ rows = _cached_rows(("ready_warehouses",), _fetch_ready_warehouse_rows)
+ if rows is None:
+ return None
+
+ organization_ids: set[str] = set()
+ for row in rows:
+ organization_id = row.get("org_id")
+ if isinstance(organization_id, str) and organization_id:
+ organization_ids.add(organization_id)
+ else:
+ logger.warning("cp_teams_ready_warehouse_missing_org_id")
+ return organization_ids
+
+
def list_org_teams(organization_id: str, *, use_cache: bool = True) -> list[CPTeam] | None:
"""All CP team rows of an org, or None when the control plane can't answer."""
org_id = str(organization_id)
@@ -265,8 +327,15 @@ def list_member_teams(*, use_cache: bool = True) -> list[CPTeam] | None:
def list_enabled_backfills() -> list[CPTeam] | None:
- """Every CP team row with backfill_enabled, across all orgs, or None when unreachable."""
+ """Backfill-enabled teams whose warehouses are ready, or None when either read is unavailable."""
teams = list_member_teams()
if teams is None:
return None
- return [team for team in teams if team.backfill_enabled]
+ enabled_teams = [team for team in teams if team.backfill_enabled]
+ if not enabled_teams:
+ return []
+
+ ready_organization_ids = _ready_warehouse_org_ids()
+ if ready_organization_ids is None:
+ return None
+ return [team for team in enabled_teams if team.organization_id in ready_organization_ids]
diff --git a/products/managed_warehouse/backend/team_state.py b/products/managed_warehouse/backend/team_state.py
index 0e6463063739..5adba5025715 100644
--- a/products/managed_warehouse/backend/team_state.py
+++ b/products/managed_warehouse/backend/team_state.py
@@ -158,10 +158,10 @@ def backfill_row_exists(team_id: int, organization_id: str) -> bool:
def list_enabled_backfill_rows(call_site: str) -> list[ManagedWarehouseTeamMembership]:
- """Every team with warehouse backfills enabled, for sensor enumeration.
+ """Every backfill-enabled team in a ready warehouse, for sensor enumeration.
- Failure posture: an unreachable control plane yields an empty enumeration (the
- sensor tick becomes a no-op and the next tick retries) — it must never raise.
+ Failure posture: an unavailable team or warehouse listing yields an empty enumeration.
+ The sensor tick becomes a no-op and the next tick retries; it must never raise.
"""
cp_rows = cp_teams.list_enabled_backfills()
if cp_rows is None:
diff --git a/products/managed_warehouse/backend/tests/test_cp_teams.py b/products/managed_warehouse/backend/tests/test_cp_teams.py
index 8de7afb8ef25..520d98ff7e4d 100644
--- a/products/managed_warehouse/backend/tests/test_cp_teams.py
+++ b/products/managed_warehouse/backend/tests/test_cp_teams.py
@@ -200,12 +200,19 @@ class TestTTLCache:
cp_teams.list_org_teams("org-1")
assert mock_fetch.call_count == 2
- def test_list_enabled_backfills_filters_disabled_rows(self) -> None:
+ def test_list_enabled_backfills_filters_disabled_and_non_ready_rows(self) -> None:
rows = [
_row(team_id=1, backfill_enabled=True),
_row(team_id=2, schema_name="two", backfill_enabled=False),
+ _row(org_id="org-2", team_id=3, schema_name="three", backfill_enabled=True),
]
- with patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=rows):
+ with (
+ patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=rows),
+ patch(
+ "products.managed_warehouse.backend.cp_teams._fetch_ready_warehouse_rows",
+ return_value=[{"org_id": "org-1", "state": "ready"}],
+ ),
+ ):
teams = cp_teams.list_enabled_backfills()
assert teams is not None
assert [team.team_id for team in teams] == [1]
@@ -257,6 +264,31 @@ class TestControlPlaneTransport:
timeout=30,
)
+ @override_settings(DUCKGRES_API_URL="https://duckgres.example/", DUCKGRES_INTERNAL_SECRET="secret")
+ def test_ready_warehouse_read_filters_non_ready_states(self) -> None:
+ response = MagicMock(status_code=200, text="ok")
+ response.json.return_value = {
+ "warehouses": [
+ {"org_id": "org-1", "state": "ready", "writable": True},
+ {"org_id": "org-2", "state": "resharding", "writable": False},
+ ]
+ }
+
+ with patch(
+ "products.managed_warehouse.backend.cp_teams.internal_requests.request",
+ return_value=response,
+ ) as request:
+ assert cp_teams._fetch_ready_warehouse_rows() == [{"org_id": "org-1", "state": "ready", "writable": True}]
+
+ request.assert_called_once_with(
+ "GET",
+ "https://duckgres.example/api/v1/warehouses",
+ json=None,
+ params=None,
+ headers={"X-Duckgres-Internal-Secret": "secret"},
+ timeout=30,
+ )
+
@override_settings(DUCKGRES_API_URL="https://duckgres.example/", DUCKGRES_INTERNAL_SECRET="secret")
def test_unusable_response_falls_back_to_none(self, caplog) -> None:
caplog.set_level(logging.WARNING, logger="products.managed_warehouse.backend.cp_teams")
diff --git a/products/managed_warehouse/backend/tests/test_team_state.py b/products/managed_warehouse/backend/tests/test_team_state.py
index 340abd924441..907cb4914cda 100644
--- a/products/managed_warehouse/backend/tests/test_team_state.py
+++ b/products/managed_warehouse/backend/tests/test_team_state.py
@@ -184,7 +184,13 @@ class TestListEnabledBackfillRows:
def test_returns_frozen_membership_contract(self) -> None:
org, team = _team()
cp_rows = [_cp_row(team, "cp_schema", earliest_event_date="2020-06-15")]
- with patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=cp_rows):
+ with (
+ patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=cp_rows),
+ patch(
+ "products.managed_warehouse.backend.cp_teams._fetch_ready_warehouse_rows",
+ return_value=[{"org_id": str(org.id), "state": "ready"}],
+ ),
+ ):
rows = team_state.list_enabled_backfill_rows("test")
assert len(rows) == 1
row = rows[0]
@@ -205,9 +211,32 @@ class TestListEnabledBackfillRows:
def test_excludes_rows_with_backfill_disabled(self) -> None:
org, team = _team()
cp_rows = [_cp_row(team, "cp_schema", backfill_enabled=False)]
- with patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=cp_rows):
+ with (
+ patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=cp_rows),
+ patch(
+ "products.managed_warehouse.backend.cp_teams._fetch_ready_warehouse_rows",
+ return_value=[{"org_id": str(org.id), "state": "ready"}],
+ ),
+ ):
assert team_state.list_enabled_backfill_rows("test") == []
- def test_returns_empty_without_raising_when_cp_down(self) -> None:
- with patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=None):
+ @parameterized.expand(
+ [
+ ("team_list_unavailable", False, True),
+ ("warehouse_list_unavailable", True, False),
+ ]
+ )
+ def test_returns_empty_without_raising_when_cp_down(
+ self, _name: str, team_list_available: bool, warehouse_list_available: bool
+ ) -> None:
+ org, team = _team()
+ cp_rows = [_cp_row(team, "cp_schema")] if team_list_available else None
+ warehouse_rows = [{"org_id": str(org.id), "state": "ready"}] if warehouse_list_available else None
+ with (
+ patch("products.managed_warehouse.backend.cp_teams._fetch_all_rows", return_value=cp_rows),
+ patch(
+ "products.managed_warehouse.backend.cp_teams._fetch_ready_warehouse_rows",
+ return_value=warehouse_rows,
+ ),
+ ):
assert team_state.list_enabled_backfill_rows("test") == []