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(migrations): publish outcomes directly and retain phase during retries (#116076)

Sven Langef7feec6d913f
diff --git a/bin/migrate b/bin/migrate
index 1e4ab14a0c43..250d2665617b 100755
--- a/bin/migrate
+++ b/bin/migrate
@@ -44,8 +44,6 @@ report_outcome() {
fi
}
trap report_outcome EXIT
-# Clear the prior pod's result before a retry can stop without running the exit handler.
-publish_outcome unknown
# NOTE when running in docker, rust might not exist so we need to check for it
if [ -d "$SCRIPT_DIR/../rust/bin" ] && [ "${DEPLOYMENT:-}" != "hobby" ]; then
diff --git a/bin/report-migration-outcome b/bin/report-migration-outcome
index 43afbe6ced1e..35effffb5501 100644
--- a/bin/report-migration-outcome
+++ b/bin/report-migration-outcome
@@ -2,10 +2,26 @@
import os
import sys
import logging
+from collections.abc import Callable
+from urllib.request import ProxyHandler, Request, build_opener
from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
+def _direct_handler(
+ url: str, method: str, timeout: float | None, headers: list[tuple[str, str]], data: bytes
+) -> Callable[[], None]:
+ def send() -> None:
+ request = Request(url, data=data, method=method)
+ for name, value in headers:
+ request.add_header(name, value)
+ # Only this Pushgateway request bypasses the egress proxy.
+ with build_opener(ProxyHandler({})).open(request, timeout=timeout):
+ pass
+
+ return send
+
+
def main() -> None:
address = os.environ.get("PROM_PUSHGATEWAY_ADDRESS")
job_name = os.environ.get("MIGRATION_JOB_NAME")
@@ -17,7 +33,7 @@ def main() -> None:
registry = CollectorRegistry()
outcome = Gauge(
"django_migration_outcome",
- "Latest migration pod outcome (1 = failed or not yet complete)",
+ "Latest migration job outcome (1 = failed)",
["phase", "job_name", "namespace"],
registry=registry,
)
@@ -30,6 +46,7 @@ def main() -> None:
grouping_key={"instance": "posthog"},
registry=registry,
timeout=5,
+ handler=_direct_handler,
)
except Exception as exc:
logging.exception("Failed to push migration outcome: %s", exc)
diff --git a/bin/test/test_report_migration_outcome.py b/bin/test/test_report_migration_outcome.py
new file mode 100644
index 000000000000..b27a11c594c7
--- /dev/null
+++ b/bin/test/test_report_migration_outcome.py
@@ -0,0 +1,74 @@
+import os
+import sys
+import threading
+import subprocess
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+import unittest
+
+PUBLISHER = Path(__file__).resolve().parents[1] / "report-migration-outcome"
+
+
+class TestMigrationOutcomePublisher(unittest.TestCase):
+ def test_pushgateway_request_bypasses_egress_proxy(self) -> None:
+ pushes: list[tuple[str, str]] = []
+ proxy_requests: list[str] = []
+
+ class Gateway(BaseHTTPRequestHandler):
+ def do_PUT(self) -> None:
+ pushes.append((self.path, self.rfile.read(int(self.headers["Content-Length"])).decode()))
+ self.send_response(202)
+ self.end_headers()
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ class Proxy(BaseHTTPRequestHandler):
+ def do_PUT(self) -> None:
+ proxy_requests.append(self.path)
+ self.send_error(407, "Deny: Private Range")
+
+ def log_message(self, *args: object) -> None:
+ pass
+
+ with (
+ ThreadingHTTPServer(("127.0.0.1", 0), Gateway) as gateway,
+ ThreadingHTTPServer(("127.0.0.1", 0), Proxy) as proxy,
+ ):
+ threads = [threading.Thread(target=server.serve_forever) for server in (gateway, proxy)]
+ for thread in threads:
+ thread.start()
+ try:
+ env = {key: value for key, value in os.environ.items() if not key.lower().endswith("_proxy")}
+ env.pop("REQUEST_METHOD", None)
+ env.update(
+ HTTP_PROXY=f"http://127.0.0.1:{proxy.server_port}",
+ NO_PROXY="pyroscope-distributor.pyroscope.svc,sts.us-east-1.amazonaws.com",
+ PROM_PUSHGATEWAY_ADDRESS=f"127.0.0.1:{gateway.server_port}",
+ MIGRATION_JOB_NAME="migration-sync-test",
+ MIGRATION_NAMESPACE="posthog-web-django",
+ )
+ result = subprocess.run(
+ [sys.executable, str(PUBLISHER), "clickhouse"],
+ env=env,
+ capture_output=True,
+ text=True,
+ timeout=10,
+ check=True,
+ )
+ finally:
+ for server in (gateway, proxy):
+ server.shutdown()
+ for thread in threads:
+ thread.join()
+
+ self.assertEqual(result.stderr, "")
+ self.assertEqual(proxy_requests, [])
+ self.assertEqual(len(pushes), 1)
+ path, body = pushes[0]
+ self.assertEqual(path, "/metrics/job/django_migrate_outcome/instance/posthog")
+ self.assertIn('job_name="migration-sync-test"', body)
+ self.assertIn('phase="clickhouse"', body)
+ self.assertIn("django_migration_outcome{", body)
+ self.assertIn("} 1.0", body)