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(proxy): give the monitor checks time to finish their network calls (#83202)

Yasen5839c7d864a7
diff --git a/posthog/temporal/proxy_service/monitor.py b/posthog/temporal/proxy_service/monitor.py
index cb6b752d7574..d384c36294e6 100644
--- a/posthog/temporal/proxy_service/monitor.py
+++ b/posthog/temporal/proxy_service/monitor.py
@@ -47,7 +47,7 @@ LOGGER = get_logger(__name__)
# Timeout (seconds) for every network call in the live-proxy probe - the POST and the raw-socket
# cert fetch. The domain is attacker-controllable, so an unbounded call lets a malicious domain
# hang the activity until Temporal's start_to_close_timeout. 5.0 (vs the diagnostics probe's 3.0 in
-# proxy_record_diagnostics.py) leaves headroom under this activity's 10s start_to_close budget,
+# proxy_record_diagnostics.py) leaves headroom under this activity's start_to_close budget,
# where a single on-demand diagnostics run instead shares its tighter budget across several checks.
PROXY_LIVE_CHECK_TIMEOUT_S = 5.0
@@ -62,8 +62,21 @@ DNS_LOOKUP_FAILURES = (
dns.resolver.NoResolverConfiguration,
)
+# Stated rather than left to the resolver's own default, so the worst case below stays computable.
+DNS_LOOKUP_LIFETIME_S = 5.0
+
CLOUDFLARE_IPS_TIMEOUT_S = 3.0
+# Each check must outlast the network calls it makes, or Temporal kills it first and the run
+# reports an opaque timeout instead of the problem the check found. Worst cases:
+# check_dns two lookups plus the Cloudflare address list = 13s
+# check_proxy_is_live the POST plus the socket connect and TLS handshake = 10s
+# check_certificate_status one Cloudflare API call, or one call to the legacy provisioner = 8s
+CHECK_START_TO_CLOSE = dt.timedelta(seconds=30)
+
+# Two attempts at the budget above, plus the retry interval between them.
+CHECK_SCHEDULE_TO_CLOSE = dt.timedelta(seconds=90)
+
@dataclass
class MonitorManagedProxyInputs:
@@ -115,7 +128,7 @@ async def check_dns(inputs: CheckActivityInput) -> CheckActivityOutput:
def _resolve_dns(proxy_record: ProxyRecord) -> CheckActivityOutput:
try:
- cnames = dns.resolver.resolve(proxy_record.domain, "CNAME")
+ cnames = dns.resolver.resolve(proxy_record.domain, "CNAME", lifetime=DNS_LOOKUP_LIFETIME_S)
value = cnames[0].target.canonicalize().to_text()
if cnames[0].target == dns.name.from_text(proxy_record.target_cname):
return CheckActivityOutput(
@@ -135,7 +148,7 @@ def _resolve_dns(proxy_record: ProxyRecord) -> CheckActivityOutput:
# A likely reason for this is that they have set Cloudflare proxying on.
# Check for this explicitly to create a nice message for the user.
try:
- arecords = dns.resolver.resolve(proxy_record.domain, "A")
+ arecords = dns.resolver.resolve(proxy_record.domain, "A", lifetime=DNS_LOOKUP_LIFETIME_S)
except DNS_LOOKUP_FAILURES:
return CheckActivityOutput(
errors=["No CNAME or A record DNS records found"],
@@ -268,7 +281,12 @@ async def _check_legacy_certificate_status(proxy_record, logger) -> CheckActivit
if e.code() == grpc.StatusCode.INVALID_ARGUMENT:
raise NonRetriableException("invalid argument") from e
if e.code() == grpc.StatusCode.NOT_FOUND:
- raise NonRetriableException("not found") from e
+ # A missing certificate is the problem this check exists to report, so record it on
+ # the proxy rather than ending the run before it can write anything.
+ return CheckActivityOutput(
+ errors=["No TLS certificate found for this domain"],
+ warnings=[],
+ )
raise
@@ -469,8 +487,8 @@ class MonitorManagedProxyWorkflow(PostHogWorkflow):
check_dns_response = await temporalio.workflow.execute_activity(
check_dns,
CheckActivityInput(proxy_record_id=inputs.proxy_record_id),
- schedule_to_close_timeout=dt.timedelta(minutes=1),
- start_to_close_timeout=dt.timedelta(seconds=10),
+ schedule_to_close_timeout=CHECK_SCHEDULE_TO_CLOSE,
+ start_to_close_timeout=CHECK_START_TO_CLOSE,
retry_policy=temporalio.common.RetryPolicy(
backoff_coefficient=1.1,
initial_interval=dt.timedelta(seconds=3),
@@ -485,8 +503,8 @@ class MonitorManagedProxyWorkflow(PostHogWorkflow):
check_proxy_response = await temporalio.workflow.execute_activity(
check_proxy_is_live,
CheckActivityInput(proxy_record_id=inputs.proxy_record_id),
- schedule_to_close_timeout=dt.timedelta(minutes=1),
- start_to_close_timeout=dt.timedelta(seconds=10),
+ schedule_to_close_timeout=CHECK_SCHEDULE_TO_CLOSE,
+ start_to_close_timeout=CHECK_START_TO_CLOSE,
retry_policy=temporalio.common.RetryPolicy(
backoff_coefficient=1.1,
initial_interval=dt.timedelta(seconds=3),
@@ -501,8 +519,8 @@ class MonitorManagedProxyWorkflow(PostHogWorkflow):
check_certificate_response = await temporalio.workflow.execute_activity(
check_certificate_status,
CheckActivityInput(proxy_record_id=inputs.proxy_record_id),
- schedule_to_close_timeout=dt.timedelta(minutes=1),
- start_to_close_timeout=dt.timedelta(seconds=10),
+ schedule_to_close_timeout=CHECK_SCHEDULE_TO_CLOSE,
+ start_to_close_timeout=CHECK_START_TO_CLOSE,
retry_policy=temporalio.common.RetryPolicy(
backoff_coefficient=1.1,
initial_interval=dt.timedelta(seconds=3),
diff --git a/posthog/temporal/proxy_service/test/dns_test.py b/posthog/temporal/proxy_service/test/dns_test.py
index 361a126baccc..bad285a9d904 100644
--- a/posthog/temporal/proxy_service/test/dns_test.py
+++ b/posthog/temporal/proxy_service/test/dns_test.py
@@ -2,15 +2,26 @@ import time
import uuid
import asyncio
-from unittest.mock import MagicMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
-from django.test import TestCase
+from django.test import SimpleTestCase
+import grpc.aio
import requests
import dns.resolver
from parameterized import parameterized
-from posthog.temporal.proxy_service.monitor import CheckActivityInput, check_dns, check_proxy_is_live
+from posthog.temporal.proxy_service.cloudflare import CLOUDFLARE_API_TIMEOUT_S
+from posthog.temporal.proxy_service.monitor import (
+ CHECK_START_TO_CLOSE,
+ CLOUDFLARE_IPS_TIMEOUT_S,
+ DNS_LOOKUP_LIFETIME_S,
+ PROXY_LIVE_CHECK_TIMEOUT_S,
+ CheckActivityInput,
+ check_certificate_status,
+ check_dns,
+ check_proxy_is_live,
+)
RECORD_ID = uuid.UUID("019d1de4-5a20-0000-9d77-91f1a96a9df0")
@@ -22,10 +33,10 @@ DNS_FAILURES = [
]
-def _record():
+def _record(target_cname="x.cf-prod-us-proxy.proxyhog.com."):
r = MagicMock()
r.domain = "p.example.com"
- r.target_cname = "x.cf-prod-us-proxy.proxyhog.com."
+ r.target_cname = target_cname
r.organization_id = "org"
r.id = RECORD_ID
return r
@@ -45,13 +56,13 @@ async def _time_a_co_tenant(during) -> tuple[float, float]:
return baseline, await task
-class TestProxyChecksDoNotFailOnHandledConditions(TestCase):
+class TestProxyChecksDoNotFailOnHandledConditions(SimpleTestCase):
@parameterized.expand(DNS_FAILURES)
@patch("posthog.temporal.proxy_service.monitor.get_record")
async def test_a_lookup_failure_is_reported_not_raised(self, _name, exc, mock_get_record):
mock_get_record.return_value = _record()
- def resolve(domain, rdtype):
+ def resolve(domain, rdtype, **kwargs):
if rdtype == "CNAME":
raise dns.resolver.NoAnswer()
raise exc
@@ -77,7 +88,7 @@ class TestProxyChecksDoNotFailOnHandledConditions(TestCase):
a_rec = MagicMock()
a_rec.to_text.return_value = "1.2.3.4"
- def resolve(domain, rdtype):
+ def resolve(domain, rdtype, **kwargs):
if rdtype == "CNAME":
raise dns.resolver.NoAnswer()
return [a_rec]
@@ -92,12 +103,12 @@ class TestProxyChecksDoNotFailOnHandledConditions(TestCase):
assert out.errors == ["DNS records not found"]
-class TestProxyChecksKeepTheEventLoopFree(TestCase):
+class TestProxyChecksKeepTheEventLoopFree(SimpleTestCase):
@patch("posthog.temporal.proxy_service.monitor.get_record")
async def test_check_dns_does_not_block(self, mock_get_record):
mock_get_record.return_value = _record()
- def slow(domain, rdtype):
+ def slow(domain, rdtype, **kwargs):
time.sleep(1.0)
raise dns.resolver.NXDOMAIN()
@@ -122,3 +133,37 @@ class TestProxyChecksKeepTheEventLoopFree(TestCase):
)
assert contended < baseline + 0.5, f"loop blocked: baseline={baseline:.2f}s contended={contended:.2f}s"
+
+
+class TestLegacyCertificateStatus(SimpleTestCase):
+ @patch("posthog.temporal.proxy_service.monitor.get_grpc_client")
+ @patch("posthog.temporal.proxy_service.monitor.get_record")
+ async def test_a_missing_certificate_is_reported_not_raised(self, mock_get_record, mock_get_client):
+ mock_get_record.return_value = _record(target_cname="proxy.example.com.")
+
+ client = MagicMock()
+ client.Status = AsyncMock(
+ side_effect=grpc.aio.AioRpcError(
+ code=grpc.StatusCode.NOT_FOUND,
+ initial_metadata=grpc.aio.Metadata(),
+ trailing_metadata=grpc.aio.Metadata(),
+ details="certificate not found",
+ )
+ )
+ mock_get_client.return_value = client
+
+ out = await check_certificate_status(CheckActivityInput(proxy_record_id=RECORD_ID))
+
+ assert out.errors == ["No TLS certificate found for this domain"]
+
+
+class TestActivityBudgetsCoverTheirNetworkCalls(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("check_dns", 2 * DNS_LOOKUP_LIFETIME_S + CLOUDFLARE_IPS_TIMEOUT_S),
+ ("check_proxy_is_live", 2 * PROXY_LIVE_CHECK_TIMEOUT_S),
+ ("check_certificate_status", CLOUDFLARE_API_TIMEOUT_S),
+ ]
+ )
+ def test_the_worst_case_fits_inside_the_budget(self, _name, worst_case_seconds):
+ assert worst_case_seconds < CHECK_START_TO_CLOSE.total_seconds()