: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
chore(toolbox): scope pod selector with component label in per-app namespace (#58988)
Sven Langea711ab2b76ac
diff --git a/tools/infra-scripts/clitools/test_toolbox.py b/tools/infra-scripts/clitools/test_toolbox.pyindex e26ba68ea8cb..c954d9e30c98 100644--- a/tools/infra-scripts/clitools/test_toolbox.py+++ b/tools/infra-scripts/clitools/test_toolbox.py@@ -275,6 +275,54 @@ class TestToolbox(unittest.TestCase):check=True,)+ @patch("subprocess.run")+ def test_get_toolbox_pod_extra_selector(self, mock_run):+ """extra_selector= is ANDed onto the base name= selector passed to kubectl."""+ mock_response = MagicMock()+ mock_response.stdout = json.dumps(+ {+ "items": [+ {+ "metadata": {+ "name": "toolbox-pod-1",+ "resourceVersion": "12345",+ "labels": {+ "app.kubernetes.io/name": "posthog-toolbox-django",+ "app.kubernetes.io/component": "app",+ },+ "deletionTimestamp": None,+ },+ "status": {"phase": "Running"},+ }+ ]+ }+ )+ mock_run.return_value = mock_response++ get_toolbox_pod(+ "michael.k_at_posthog.com",+ app_label="posthog-toolbox-django",+ claimed_label_key="toolbox-claimed",+ namespace="posthog-toolbox-django",+ extra_selector="app.kubernetes.io/component=app",+ )+ mock_run.assert_called_once_with(+ [+ "kubectl",+ "get",+ "pods",+ "-n",+ "posthog-toolbox-django",+ "-l",+ "app.kubernetes.io/name=posthog-toolbox-django,app.kubernetes.io/component=app",+ "-o",+ "json",+ ],+ capture_output=True,+ text=True,+ check=True,+ )+@patch("subprocess.run")def test_get_toolbox_pod_returns_existing_claim_with_rv(self, mock_run):"""An already-claimed pod returns is_claimed=True and the observed resourceVersion."""@@ -807,7 +855,13 @@ class TestToolbox(unittest.TestCase):"""POOLS contains both pools with the expected app and claim labels."""self.assertEqual(toolbox_script.POOLS["toolbox-django"],- {"app_label": "posthog-toolbox-django", "claimed_label_key": "toolbox-claimed"},+ {+ "app_label": "posthog-toolbox-django",+ "claimed_label_key": "toolbox-claimed",+ "extra_selectors_by_namespace": {+ "posthog-toolbox-django": "app.kubernetes.io/component=app",+ },+ },)self.assertEqual(toolbox_script.POOLS["flags-cache-jumphost"],@@ -1137,6 +1191,7 @@ class TestToolbox(unittest.TestCase):claimed_label_key="flags-jumphost-claimed",namespace="posthog",context="posthog-dev",+ extra_selector=None,)# claim_pod gets namespace, context, and resource_version from get_toolbox_pod's return.self.assertEqual(@@ -1145,32 +1200,48 @@ class TestToolbox(unittest.TestCase):)def test_main_default_pool_dispatches_toolbox_django_kwargs(self):- """No --pool argument defaults to toolbox-django and threads its labels."""- patches = self._patch_main_collaborators()-- with (- patches["get_current_user"],- patches["get_toolbox_pod"] as m_get_pod,- patches["claim_pod"],- patches["connect_to_pod"],- patches["delete_pod"],- patches["select_context"],- patches["validate_context"],- patch.object(toolbox_script.sys, "argv", ["toolbox.py"]),- patch.dict(os.environ, {}, clear=False),- ):- self._clean_env()- with self.assertRaises(SystemExit):- toolbox_script.main()+ """--pool toolbox-django (the default) threads the right kwargs per active namespace.- m_get_pod.assert_called_once_with(- "user_at_posthog.com",- check_claimed=True,- app_label="posthog-toolbox-django",- claimed_label_key="toolbox-claimed",- namespace="posthog",- context="posthog-dev",- )+ The legacy `posthog` namespace gets no `extra_selector`. The golden-chart per-app+ namespace `posthog-toolbox-django` adds `app.kubernetes.io/component=app` so the+ wrapper can't claim a pgbouncer pod (the chart's pgbouncers share+ `app.kubernetes.io/name=posthog-toolbox-django` with the toolbox itself).+ """+ cases = [+ ("posthog", None), # legacy default — KUBE_NAMESPACE unset+ ("posthog-toolbox-django", "app.kubernetes.io/component=app"),+ ]+ for namespace, expected_extra in cases:+ with self.subTest(namespace=namespace):+ patches = self._patch_main_collaborators()+ env_override = {"KUBE_NAMESPACE": namespace} if namespace != "posthog" else {}+ with (+ patches["get_current_user"],+ patches["get_toolbox_pod"] as m_get_pod,+ patches["claim_pod"],+ patches["connect_to_pod"],+ patches["delete_pod"],+ patches["select_context"],+ patches["validate_context"],+ patch.object(toolbox_script.sys, "argv", ["toolbox.py"]),+ patch.dict(os.environ, env_override, clear=False),+ ):+ os.environ.pop("KUBE_CONTEXT", None)+ os.environ.pop("FLOX_ENV", None)+ if namespace == "posthog":+ os.environ.pop("KUBE_NAMESPACE", None)+ with self.assertRaises(SystemExit):+ toolbox_script.main()++ m_get_pod.assert_called_once_with(+ "user_at_posthog.com",+ check_claimed=True,+ app_label="posthog-toolbox-django",+ claimed_label_key="toolbox-claimed",+ namespace=namespace,+ context="posthog-dev",+ extra_selector=expected_extra,+ )def test_main_kube_context_env_validates_without_switching(self):"""When KUBE_CONTEXT is set, main() validates it and threads it as --context, never calling switch_context."""diff --git a/tools/infra-scripts/clitools/toolbox.py b/tools/infra-scripts/clitools/toolbox.pyindex f477898d591c..fe5ddc87f31c 100755--- a/tools/infra-scripts/clitools/toolbox.py+++ b/tools/infra-scripts/clitools/toolbox.py@@ -18,10 +18,20 @@ from toolbox.kubernetes import select_context, validate_contextfrom toolbox.pod import ClaimRaceError, claim_pod, connect_to_pod, delete_pod, get_toolbox_podfrom toolbox.user import get_current_user+# Extra label selectors ANDed onto the base `app.kubernetes.io/name=<app_label>`+# selector. Keyed by namespace because the legacy and golden-chart deployments+# share the same `app_label` but live in different namespaces with different+# co-tenants (pgbouncer pods in the golden chart's per-app namespace also carry+# `app.kubernetes.io/name=posthog-toolbox-django`, so we need `component=app` to+# pick out only the main pool). The legacy `posthog` namespace doesn't need a+# discriminator because its pgbouncers have a different `name` label.POOLS = {"toolbox-django": {"app_label": "posthog-toolbox-django","claimed_label_key": "toolbox-claimed",+ "extra_selectors_by_namespace": {+ "posthog-toolbox-django": "app.kubernetes.io/component=app",+ },},"flags-cache-jumphost": {"app_label": "flags-cache-jumphost",@@ -83,6 +93,12 @@ def main():app_label = pool["app_label"]claimed_label_key = pool["claimed_label_key"]namespace = os.environ.get("KUBE_NAMESPACE", "posthog")+ # The base selector is `app.kubernetes.io/name=<app_label>`. Some+ # namespaces also host other workloads that share that label (e.g. the+ # golden chart deploys a per-app pgbouncer under the same name in the+ # `posthog-toolbox-django` namespace), so we may need a further+ # discriminator to pick only the main pool pods.+ extra_selector = pool.get("extra_selectors_by_namespace", {}).get(namespace)print(f"🛠️ Connecting to {args.pool} pool in namespace {namespace}...") # noqa: T201@@ -110,6 +126,7 @@ def main():claimed_label_key=claimed_label_key,namespace=namespace,context=selected_context,+ extra_selector=extra_selector,)print(f"🎯 Found pod: {pod_name}") # noqa: T201@@ -177,6 +194,7 @@ def main():claimed_label_key=claimed_label_key,namespace=namespace,context=selected_context,+ extra_selector=extra_selector,)if is_already_claimed:# Either we won an earlier race attempt (whose ack we missed) ordiff --git a/tools/infra-scripts/clitools/toolbox/pod.py b/tools/infra-scripts/clitools/toolbox/pod.pyindex c8fc42770c6d..eb5bb5798eb4 100644--- a/tools/infra-scripts/clitools/toolbox/pod.py+++ b/tools/infra-scripts/clitools/toolbox/pod.py@@ -33,6 +33,7 @@ def get_toolbox_pod(claimed_label_key: str,namespace: str,context: str | None = None,+ extra_selector: str | None = None,) -> tuple[str, bool, str]:"""Get an available toolbox pod name and the resourceVersion observed.@@ -43,12 +44,21 @@ def get_toolbox_pod(claimed_label_key: Label key the wrapper sets on a claimed pod.namespace: Kubernetes namespace the pool lives in.context: Optional kubernetes context to scope the kubectl call to.+ extra_selector: Optional additional label selector ANDed onto+ ``app.kubernetes.io/name=<app_label>``. Used when other resources+ in the namespace share the same name label (e.g. the golden chart+ puts the toolbox's own pgbouncer pods under the same name) so we+ need a second key like ``app.kubernetes.io/component=app`` to+ pick out only the main pool.Returns:Tuple of (pod_name, is_already_claimed, resource_version). Theresource_version reflects the pod state at observation time and isused by ``claim_pod`` for optimistic concurrency control."""+ label_selector = f"app.kubernetes.io/name={app_label}"+ if extra_selector:+ label_selector = f"{label_selector},{extra_selector}"wait_start = datetime.now()max_wait = timedelta(minutes=5)update_interval = timedelta(seconds=30)@@ -63,7 +73,7 @@ def get_toolbox_pod("-n",namespace,"-l",- f"app.kubernetes.io/name={app_label}",+ label_selector,"-o","json",context=context,