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.

feat: Add Browserless rendering backend for image exports (#60793)

Jordan Mryyan5bff6fccf7ec
diff --git a/.env.example b/.env.example
index 69c5e107b9fa..780bba799fae 100644
--- a/.env.example
+++ b/.env.example
@@ -41,3 +41,9 @@ HEATMAP_BROWSERLESS_TOKEN=
# HEATMAP_BROWSERLESS_BLOCK_ADS=false
# HEATMAP_BROWSERLESS_BLOCK_CONSENT_MODALS=true
# In prod, also enable the "heatmap-browserless-cloud" feature flag to ramp rollout (DEBUG bypasses it).
+
+# BROWSERLESS_CDP_URL=
+# BROWSERLESS_TOKEN=
+# BROWSERLESS_SESSION_TIMEOUT_MS=180000
+# BROWSERLESS_CONNECT_TIMEOUT_MS=30000
+# In prod, also enable the "image-exporter-use-browserless" feature flag to ramp rollout.
diff --git a/posthog/settings/__init__.py b/posthog/settings/__init__.py
index 99e556bb9ebe..e31a51d65236 100644
--- a/posthog/settings/__init__.py
+++ b/posthog/settings/__init__.py
@@ -49,6 +49,7 @@ from posthog.settings.integrations import *
from posthog.settings.payments import *
from posthog.settings.personhog import *
from posthog.settings.ses import *
+from posthog.settings.exports import *
from posthog.settings.utils import get_from_env, str_to_bool
diff --git a/posthog/settings/exports.py b/posthog/settings/exports.py
new file mode 100644
index 000000000000..e77a05a2e3ee
--- /dev/null
+++ b/posthog/settings/exports.py
@@ -0,0 +1,6 @@
+from posthog.settings.utils import get_from_env
+
+BROWSERLESS_CDP_URL: str = get_from_env("BROWSERLESS_CDP_URL", "")
+BROWSERLESS_TOKEN: str = get_from_env("BROWSERLESS_TOKEN", "")
+BROWSERLESS_SESSION_TIMEOUT_MS: int = get_from_env("BROWSERLESS_SESSION_TIMEOUT_MS", 180000, type_cast=int)
+BROWSERLESS_CONNECT_TIMEOUT_MS: int = get_from_env("BROWSERLESS_CONNECT_TIMEOUT_MS", 30000, type_cast=int)
diff --git a/posthog/tasks/exports/failure_handler.py b/posthog/tasks/exports/failure_handler.py
index 23e26f96e26c..ff8541673808 100644
--- a/posthog/tasks/exports/failure_handler.py
+++ b/posthog/tasks/exports/failure_handler.py
@@ -4,6 +4,7 @@ from django.db import OperationalError
from billiard.exceptions import SoftTimeLimitExceeded
from clickhouse_driver.errors import SocketTimeoutError
+from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
from selenium.common import TimeoutException
from urllib3.exceptions import MaxRetryError, ProtocolError, ReadTimeoutError
@@ -62,6 +63,12 @@ class ExportCancelled(Exception):
pass
+class BrowserlessUnavailable(Exception):
+ """Raised when the browserless.io render backend is unreachable or drops the connection."""
+
+ pass
+
+
class ExcelColumnLimitExceeded(Exception):
"""Raised when export data exceeds openpyxl's 18,278 column limit (ZZZ)."""
@@ -82,6 +89,7 @@ EXCEPTIONS_TO_RETRY = (
ClickHouseAtCapacity,
SocketTimeoutError,
SSLError,
+ BrowserlessUnavailable,
)
USER_QUERY_ERRORS = (
@@ -111,6 +119,7 @@ TIMEOUT_ERRORS = (
SoftTimeLimitExceeded,
TimeoutError,
TimeoutException,
+ PlaywrightTimeoutError,
ExportCancelled,
)
diff --git a/posthog/tasks/exports/image_exporter.py b/posthog/tasks/exports/image_exporter.py
index 88df9861ba1a..9d5f34f44936 100644
--- a/posthog/tasks/exports/image_exporter.py
+++ b/posthog/tasks/exports/image_exporter.py
@@ -3,14 +3,21 @@ import json
import time
import uuid
import tempfile
+from collections.abc import Callable
from datetime import timedelta
from typing import Any, Literal, Optional, cast
-from urllib.parse import quote
+from urllib.parse import parse_qsl, quote, quote_plus, urlencode, urlparse, urlunparse
from django.conf import settings
import structlog
import posthoganalytics
+from playwright.sync_api import (
+ Error as PlaywrightError,
+ TimeoutError as PlaywrightTimeoutError,
+ sync_playwright,
+)
+from prometheus_client import Counter, Histogram
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
@@ -31,6 +38,7 @@ from posthog.schema_migrations.upgrade_manager import upgrade_query
from posthog.security.url_validation import is_url_allowed
from posthog.tasks.exporter import EXPORT_TIMER
from posthog.tasks.exports.exporter_utils import log_error_if_site_url_not_reachable
+from posthog.tasks.exports.failure_handler import BrowserlessUnavailable, classify_failure_type
from posthog.utils import absolute_uri
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -39,6 +47,23 @@ from products.product_analytics.backend.models.insight_variable import InsightVa
logger = structlog.get_logger(__name__)
+IMAGE_EXPORT_BACKEND_COUNTER = Counter(
+ "image_export_backend_total",
+ "Image exports by rendering backend (browserless vs selenium)",
+ labelnames=["backend"],
+)
+IMAGE_EXPORT_RENDER_DURATION = Histogram(
+ "image_export_render_duration_seconds",
+ "Image export render time (browser navigate + wait + screenshot), by backend and outcome",
+ labelnames=["backend", "outcome"],
+ buckets=(0.5, 1, 2, 5, 10, 20, 30, 45, 60, 90, 120, float("inf")),
+)
+IMAGE_EXPORT_RENDER_FAILURE_COUNTER = Counter(
+ "image_export_render_failure_total",
+ "Image export render failures by backend and classified failure type",
+ labelnames=["backend", "failure_type"],
+)
+
def _build_cache_keys_param(insight_cache_keys: Optional[dict[int, str]]) -> str:
if not insight_cache_keys:
@@ -68,6 +93,49 @@ MEASURE_CONTENT_HEIGHT_JS = """
return document.body.scrollHeight;
"""
+MEASURE_CONTENT_WIDTH_JS = f"""
+ // Check for heatmap exporter first — its width is set explicitly
+ const heatmapElement = document.querySelector('.heatmap-exporter');
+ if (heatmapElement) {{
+ return heatmapElement.offsetWidth;
+ }}
+
+ // Check for replay player
+ const replayElement = document.querySelector('.replayer-wrapper');
+ if (replayElement) {{
+ return replayElement.offsetWidth;
+ }}
+
+ // Check for left-to-right funnel (FunnelBarVertical)
+ // Top-to-bottom funnels use FunnelBarHorizontal and don't need width expansion
+ const funnelElement = document.querySelector('.FunnelBarVertical');
+ if (funnelElement) {{
+ // Force funnel to shrink to content size
+ funnelElement.style.width = 'fit-content';
+ funnelElement.style.maxWidth = 'fit-content';
+
+ const table = funnelElement.querySelector('table');
+ if (table) {{
+ table.style.width = 'fit-content';
+ table.style.maxWidth = 'fit-content';
+ }}
+
+ // Force a reflow
+ void funnelElement.offsetWidth;
+
+ // Now measure the actual content width
+ return funnelElement.offsetWidth + {CONTENT_PADDING};
+ }}
+
+ // Fall back to table width for insights
+ const tableElement = document.querySelector('table');
+ if (tableElement) {{
+ return tableElement.offsetWidth * 1.5;
+ }}
+
+ return null;
+ """
+
ScreenWidth = Literal[800, 1920, 1400, 4000]
CSSSelector = Literal[".InsightCard", ".ExportedInsight", ".replayer-wrapper", ".heatmap-exporter"]
@@ -234,14 +302,37 @@ def _export_to_png(
logger.info("exporting_asset", asset_id=exported_asset.id, render_url=url_to_render)
- _screenshot_asset(
- image_path,
- url_to_render,
- screenshot_width,
- wait_for_css_selector,
- screenshot_height,
- max_height_pixels,
- page_load_timeout,
+ use_browserless = _should_use_browserless(exported_asset)
+
+ backend = "browserless" if use_browserless else "selenium"
+ logger.info(
+ "image_exporter.backend_selected",
+ backend=backend,
+ asset_id=exported_asset.id,
+ team_id=exported_asset.team_id,
+ )
+ IMAGE_EXPORT_BACKEND_COUNTER.labels(backend=backend).inc()
+
+ render_start = time.perf_counter()
+ try:
+ _screenshot_asset(
+ image_path,
+ url_to_render,
+ screenshot_width,
+ wait_for_css_selector,
+ screenshot_height,
+ max_height_pixels,
+ page_load_timeout,
+ use_browserless=use_browserless,
+ )
+ except Exception as e:
+ IMAGE_EXPORT_RENDER_DURATION.labels(backend=backend, outcome="failure").observe(
+ time.perf_counter() - render_start
+ )
+ IMAGE_EXPORT_RENDER_FAILURE_COUNTER.labels(backend=backend, failure_type=classify_failure_type(e)).inc()
+ raise
+ IMAGE_EXPORT_RENDER_DURATION.labels(backend=backend, outcome="success").observe(
+ time.perf_counter() - render_start
)
with open(image_path, "rb") as image_file:
@@ -261,6 +352,40 @@ def _export_to_png(
raise
+def _build_cdp_endpoint(cdp_url: str, token: str, session_timeout_ms: int) -> str:
+ parsed = urlparse(cdp_url)
+ query = {
+ key: value for key, value in parse_qsl(parsed.query, keep_blank_values=True) if key not in ("token", "timeout")
+ }
+ if token:
+ query["token"] = token
+ query["timeout"] = str(session_timeout_ms)
+ return urlunparse(parsed._replace(query=urlencode(query)))
+
+
+def _redact_browserless_token(message: str) -> str:
+ token = settings.BROWSERLESS_TOKEN
+ if not token:
+ return message
+ return message.replace(token, "***").replace(quote_plus(token), "***")
+
+
+def _should_use_browserless(exported_asset: ExportedAsset) -> bool:
+ if not settings.BROWSERLESS_CDP_URL:
+ return False
+ team = exported_asset.team
+ distinct_id = (exported_asset.created_by.distinct_id if exported_asset.created_by else None) or str(team.uuid)
+ return bool(
+ posthoganalytics.feature_enabled(
+ "image-exporter-use-browserless",
+ distinct_id,
+ groups={"organization": str(team.organization_id), "project": str(team.id)},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+
+
def _screenshot_asset(
image_path: str,
url_to_render: str,
@@ -269,6 +394,76 @@ def _screenshot_asset(
screenshot_height: int = 600,
max_height_pixels: Optional[int] = None,
page_load_timeout: int = 40,
+ use_browserless: bool = False,
+) -> None:
+ if use_browserless:
+ _screenshot_asset_browserless(
+ image_path,
+ url_to_render,
+ screenshot_width,
+ wait_for_css_selector,
+ screenshot_height,
+ max_height_pixels,
+ page_load_timeout,
+ )
+ else:
+ _screenshot_asset_selenium(
+ image_path,
+ url_to_render,
+ screenshot_width,
+ wait_for_css_selector,
+ screenshot_height,
+ max_height_pixels,
+ page_load_timeout,
+ )
+
+
+def _effective_max_height(max_height_pixels: Optional[int]) -> int:
+ return min(max_height_pixels, MAX_HEIGHT_PIXELS) if max_height_pixels else MAX_HEIGHT_PIXELS
+
+
+def _cap_height(raw_height: int, effective_max: int, url: str, *, final: bool = False) -> int:
+ if raw_height <= effective_max:
+ return raw_height
+ if final:
+ logger.warning(
+ "screenshot_final_height_capped",
+ original_final_height=raw_height,
+ capped_height=effective_max,
+ url=url,
+ )
+ else:
+ logger.warning(
+ "screenshot_height_capped",
+ original_height=raw_height,
+ capped_height=effective_max,
+ url=url,
+ )
+ return effective_max
+
+
+def _resolve_width(raw_width: object, screenshot_width: int, url: str) -> int:
+ if not isinstance(raw_width, (int, float)):
+ return screenshot_width
+ calculated_width = raw_width or screenshot_width
+ if calculated_width > MAX_WIDTH_PIXELS:
+ logger.warning(
+ "screenshot_width_capped",
+ original_width=calculated_width,
+ capped_width=MAX_WIDTH_PIXELS,
+ url=url,
+ )
+ return min(MAX_WIDTH_PIXELS, int(calculated_width))
+
+
+def _screenshot_asset_selenium(
+ image_path: str,
+ url_to_render: str,
+ screenshot_width: ScreenWidth,
+ wait_for_css_selector: CSSSelector,
+ screenshot_height: int = 600,
+ max_height_pixels: Optional[int] = None,
+ page_load_timeout: int = 40,
) -> None:
driver: Optional[webdriver.Chrome] = None
try:
@@ -291,7 +486,7 @@ def _screenshot_asset(
pass
capture_exception(e)
- raise TimeoutException(f"Timeout while waiting for the page to load")
+ raise TimeoutException("Timeout while waiting for the page to load") from e
try:
# Also wait until nothing is loading
@@ -306,76 +501,9 @@ def _screenshot_asset(
pass
capture_exception(e)
- height = int(driver.execute_script(MEASURE_CONTENT_HEIGHT_JS))
-
- effective_max = min(max_height_pixels, MAX_HEIGHT_PIXELS) if max_height_pixels else MAX_HEIGHT_PIXELS
- if height > effective_max:
- logger.warning(
- "screenshot_height_capped",
- original_height=height,
- capped_height=effective_max,
- url=url_to_render,
- )
- height = effective_max
-
- # Calculate width for replay players and non-funnel tables
- # Funnels are handled separately with fit-content measurement below
- width = driver.execute_script(
- f"""
- // Check for heatmap exporter first — its width is set explicitly
- const heatmapElement = document.querySelector('.heatmap-exporter');
- if (heatmapElement) {{
- return heatmapElement.offsetWidth;
- }}
-
- // Check for replay player
- const replayElement = document.querySelector('.replayer-wrapper');
- if (replayElement) {{
- return replayElement.offsetWidth;
- }}
-
- // Check for left-to-right funnel (FunnelBarVertical)
- // Top-to-bottom funnels use FunnelBarHorizontal and don't need width expansion
- const funnelElement = document.querySelector('.FunnelBarVertical');
- if (funnelElement) {{
- // Force funnel to shrink to content size
- funnelElement.style.width = 'fit-content';
- funnelElement.style.maxWidth = 'fit-content';
-
- const table = funnelElement.querySelector('table');
- if (table) {{
- table.style.width = 'fit-content';
- table.style.maxWidth = 'fit-content';
- }}
-
- // Force a reflow
- void funnelElement.offsetWidth;
-
- // Now measure the actual content width
- return funnelElement.offsetWidth + {CONTENT_PADDING};
- }}
-
- // Fall back to table width for insights
- const tableElement = document.querySelector('table');
- if (tableElement) {{
- return tableElement.offsetWidth * 1.5;
- }}
-
- return null;
- """
- )
- if isinstance(width, (int, float)):
- calculated_width = width or screenshot_width
- if calculated_width > MAX_WIDTH_PIXELS:
- logger.warning(
- "screenshot_width_capped",
- original_width=calculated_width,
- capped_width=MAX_WIDTH_PIXELS,
- url=url_to_render,
- )
- width = min(MAX_WIDTH_PIXELS, int(calculated_width))
- else:
- width = screenshot_width
+ effective_max = _effective_max_height(max_height_pixels)
+ height = _cap_height(int(driver.execute_script(MEASURE_CONTENT_HEIGHT_JS)), effective_max, url_to_render)
+ width = _resolve_width(driver.execute_script(MEASURE_CONTENT_WIDTH_JS), screenshot_width, url_to_render)
# Set window size with the calculated dimensions
driver.set_window_size(width, height + HEIGHT_OFFSET)
@@ -383,16 +511,9 @@ def _screenshot_asset(
# Allow a moment for any dynamic resizing
driver.execute_script("return new Promise(resolve => setTimeout(resolve, 500))")
- final_height = int(driver.execute_script(MEASURE_CONTENT_HEIGHT_JS))
-
- if final_height > effective_max:
- logger.warning(
- "screenshot_final_height_capped",
- original_final_height=final_height,
- capped_height=effective_max,
- url=url_to_render,
- )
- final_height = effective_max
+ final_height = _cap_height(
+ int(driver.execute_script(MEASURE_CONTENT_HEIGHT_JS)), effective_max, url_to_render, final=True
+ )
# Set final window size
driver.set_window_size(width, final_height + HEIGHT_OFFSET)
@@ -416,6 +537,127 @@ def _screenshot_asset(
driver.quit()
+_BROWSERLESS_CONNECTION_ERROR_INDICATORS = (
+ "target closed",
+ "has been closed",
+ "connection closed",
+ "websocket",
+ "disconnected",
+ "econnrefused",
+)
+
+
+def _is_browserless_connection_error(error: Exception) -> bool:
+ message = str(error).lower()
+ return any(indicator in message for indicator in _BROWSERLESS_CONNECTION_ERROR_INDICATORS)
+
+
+def _save_debug_screenshot(take_screenshot: Callable[[str], object], image_path: str) -> None:
+ try:
+ take_screenshot(image_path)
+ posthoganalytics.tag("image_path", image_path)
+ except Exception:
+ pass
+
+
+def _screenshot_asset_browserless(
+ image_path: str,
+ url_to_render: str,
+ screenshot_width: ScreenWidth,
+ wait_for_css_selector: CSSSelector,
+ screenshot_height: int = 600,
+ max_height_pixels: Optional[int] = None,
+ page_load_timeout: int = 40,
+) -> None:
+ endpoint = _build_cdp_endpoint(
+ settings.BROWSERLESS_CDP_URL, settings.BROWSERLESS_TOKEN, settings.BROWSERLESS_SESSION_TIMEOUT_MS
+ )
+
+ with sync_playwright() as p:
+ try:
+ browser = p.chromium.connect_over_cdp(endpoint, timeout=settings.BROWSERLESS_CONNECT_TIMEOUT_MS)
+ except (PlaywrightError, PlaywrightTimeoutError) as e:
+ raise BrowserlessUnavailable(
+ f"Failed to connect to browserless: {_redact_browserless_token(str(e))}"
+ ) from None
+
+ disconnected = [False]
+ browser.on("disconnected", lambda *_: disconnected.__setitem__(0, True))
+
+ context = None
+ page = None
+ try:
+ context = browser.new_context(
+ device_scale_factor=2,
+ viewport={"width": screenshot_width, "height": screenshot_height},
+ )
+ page = context.new_page()
+ posthoganalytics.tag("url_to_render", url_to_render)
+
+ try:
+ page.goto(url_to_render, wait_until="domcontentloaded", timeout=page_load_timeout * 1000)
+ page.wait_for_selector(wait_for_css_selector, state="attached", timeout=page_load_timeout * 1000)
+ except PlaywrightTimeoutError as e:
+ with posthoganalytics.new_context():
+ posthoganalytics.tag("stage", "image_exporter.page_load_timeout")
+ _save_debug_screenshot(lambda p: page.screenshot(path=p), image_path)
+ capture_exception(e)
+
+ raise PlaywrightTimeoutError("Timeout while waiting for the page to load") from e
+
+ try:
+ page.wait_for_selector(".Spinner", state="detached", timeout=20000)
+ except PlaywrightTimeoutError as e:
+ with posthoganalytics.new_context():
+ posthoganalytics.tag("stage", "image_exporter.wait_for_spinner_timeout")
+ _save_debug_screenshot(lambda p: page.screenshot(path=p), image_path)
+ capture_exception(e)
+
+ effective_max = _effective_max_height(max_height_pixels)
+ height = _cap_height(
+ int(page.evaluate(f"() => {{ {MEASURE_CONTENT_HEIGHT_JS} }}")), effective_max, url_to_render
+ )
+ width = _resolve_width(
+ page.evaluate(f"() => {{ {MEASURE_CONTENT_WIDTH_JS} }}"), screenshot_width, url_to_render
+ )
+
+ page.set_viewport_size({"width": width, "height": height})
+
+ page.wait_for_timeout(500)
+
+ final_height = _cap_height(
+ int(page.evaluate(f"() => {{ {MEASURE_CONTENT_HEIGHT_JS} }}")), effective_max, url_to_render, final=True
+ )
+
+ page.set_viewport_size({"width": width, "height": final_height})
+ page.screenshot(path=image_path)
+ except BrowserlessUnavailable:
+ raise
+ except PlaywrightTimeoutError:
+ raise
+ except PlaywrightError as e:
+ if disconnected[0] or _is_browserless_connection_error(e):
+ raise BrowserlessUnavailable(_redact_browserless_token(str(e))) from None
+
+ with posthoganalytics.new_context():
+ posthoganalytics.tag("url_to_render", url_to_render)
+ if page:
+ _save_debug_screenshot(lambda p: page.screenshot(path=p), image_path)
+ capture_exception(e)
+
+ raise
+ finally:
+ if context:
+ try:
+ context.close()
+ except Exception:
+ pass
+ try:
+ browser.close()
+ except Exception:
+ pass
+
+
def export_image(
exported_asset: ExportedAsset, max_height_pixels: Optional[int] = None, source: Optional[EventSource] = None
) -> None:
diff --git a/posthog/tasks/exports/test/test_image_exporter.py b/posthog/tasks/exports/test/test_image_exporter.py
index ffa819ffc387..3284ca5d047c 100644
--- a/posthog/tasks/exports/test/test_image_exporter.py
+++ b/posthog/tasks/exports/test/test_image_exporter.py
@@ -1,12 +1,25 @@
+import uuid
from datetime import datetime
-from typing import Any
+from types import SimpleNamespace
+from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
from posthog.test.base import APIBaseTest, ClickhouseTestMixin, _create_event, flush_persons_and_events
-from unittest.mock import mock_open, patch
+from unittest.mock import MagicMock, mock_open, patch
+
+from django.conf import settings
+from django.test import SimpleTestCase
from boto3 import resource
from botocore.client import Config
from parameterized import parameterized
+from playwright.sync_api import (
+ Error as PlaywrightError,
+ TimeoutError as PlaywrightTimeoutError,
+)
+from prometheus_client import REGISTRY
+
+from posthog.hogql.errors import QueryError
from posthog.caching.fetch_from_cache import InsightResult
from posthog.hogql_queries.query_runner import ExecutionMode
@@ -20,6 +33,7 @@ from posthog.settings import (
from posthog.storage import object_storage
from posthog.storage.object_storage import ObjectStorageError
from posthog.tasks.exports import image_exporter
+from posthog.tasks.exports.failure_handler import BrowserlessUnavailable
from products.dashboards.backend.models.dashboard import Dashboard
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -521,7 +535,6 @@ class TestHeatmapExportURLEncoding(APIBaseTest):
url_to_render = mock_screenshot_asset.call_args[0][1]
# Verify URL parsing recovers the full values (same as browser URL parsing)
- from urllib.parse import parse_qs, urlparse
parsed = urlparse(url_to_render)
params = parse_qs(parsed.query)
@@ -539,7 +552,6 @@ class TestHeatmapExportURLEncoding(APIBaseTest):
# Data URLs with multiple query params (e.g. `?width=1024&format=jpeg`)
# contain `&` which, without encoding, splits into separate top-level params
# and truncates the dataURL value the exporter receives.
- from urllib.parse import parse_qs, urlparse
data_url = "/api/environments/1/heatmap_screenshots/abc/content/?width=1024&format=jpeg"
unencoded = f"https://example.com/exporter?token=fake&pageURL=https://example.com&dataURL={data_url}"
@@ -623,3 +635,320 @@ class TestImageExporterQueryOverrideE2E(ClickhouseTestMixin, APIBaseTest):
assert "cache_keys=" in url_default
assert "cache_keys=" in url_override
assert url_default != url_override
+
+
+class TestBuildCdpEndpoint(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("plain_wss", "wss://chrome.browserless.io", "tok123", 180000, "wss", "chrome.browserless.io", "tok123"),
+ (
+ "existing_query_param",
+ "wss://chrome.browserless.io?launch=stealth",
+ "tok123",
+ 90000,
+ "wss",
+ "chrome.browserless.io",
+ "tok123",
+ ),
+ ("empty_token", "wss://chrome.browserless.io", "", 60000, "wss", "chrome.browserless.io", None),
+ ("wss_scheme_preserved", "wss://example.org/cdp", "abc", 120000, "wss", "example.org", "abc"),
+ ]
+ )
+ def test_build_cdp_endpoint(
+ self,
+ _name: str,
+ cdp_url: str,
+ token: str,
+ session_timeout_ms: int,
+ expected_scheme: str,
+ expected_host: str,
+ expected_token: str | None,
+ ) -> None:
+ result = image_exporter._build_cdp_endpoint(cdp_url, token, session_timeout_ms)
+
+ parsed = urlparse(result)
+ params = parse_qs(parsed.query)
+
+ assert parsed.scheme == expected_scheme
+ assert parsed.netloc == expected_host
+ assert params["timeout"] == [str(session_timeout_ms)]
+
+ if expected_token is None:
+ assert "token" not in params
+ else:
+ assert params["token"] == [expected_token]
+
+ def test_build_cdp_endpoint_preserves_path_and_existing_param(self) -> None:
+ result = image_exporter._build_cdp_endpoint("wss://example.org/cdp?launch=stealth", "tok", 1000)
+
+ parsed = urlparse(result)
+ params = parse_qs(parsed.query)
+
+ assert parsed.path == "/cdp"
+ assert params["launch"] == ["stealth"]
+ assert params["token"] == ["tok"]
+ assert params["timeout"] == ["1000"]
+
+
+class TestShouldUseBrowserless(SimpleTestCase):
+ @staticmethod
+ def _make_asset(created_by: Any) -> ExportedAsset:
+ team = SimpleNamespace(uuid=uuid.uuid4(), id=42, organization_id="org-99")
+ return cast(ExportedAsset, SimpleNamespace(team=team, created_by=created_by))
+
+ def test_returns_false_when_cdp_url_empty(self) -> None:
+ asset = self._make_asset(created_by=SimpleNamespace(distinct_id="user-1"))
+ with patch.object(settings, "BROWSERLESS_CDP_URL", ""):
+ with patch("posthog.tasks.exports.image_exporter.posthoganalytics.feature_enabled") as mock_flag:
+ assert image_exporter._should_use_browserless(asset) is False
+ mock_flag.assert_not_called()
+
+ @parameterized.expand([("enabled", True), ("disabled", False)])
+ def test_returns_flag_value_and_calls_with_expected_args(self, _name: str, flag_value: bool) -> None:
+ created_by = SimpleNamespace(distinct_id="user-1")
+ asset = self._make_asset(created_by=created_by)
+
+ with (
+ patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),
+ patch(
+ "posthog.tasks.exports.image_exporter.posthoganalytics.feature_enabled",
+ return_value=flag_value,
+ ) as mock_flag,
+ ):
+ assert image_exporter._should_use_browserless(asset) is flag_value
+
+ mock_flag.assert_called_once()
+ call_args, call_kwargs = mock_flag.call_args
+ assert call_args[0] == "image-exporter-use-browserless"
+ assert call_args[1] == "user-1"
+ assert call_kwargs["groups"]["organization"] == "org-99"
+ assert call_kwargs["groups"]["project"] == "42"
+
+ def test_falls_back_to_team_uuid_when_no_created_by(self) -> None:
+ asset = self._make_asset(created_by=None)
+
+ with (
+ patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),
+ patch(
+ "posthog.tasks.exports.image_exporter.posthoganalytics.feature_enabled",
+ return_value=True,
+ ) as mock_flag,
+ ):
+ assert image_exporter._should_use_browserless(asset) is True
+
+ call_args = mock_flag.call_args[0]
+ assert call_args[1] == str(asset.team.uuid)
+
+
+class TestScreenshotAssetDispatcher(SimpleTestCase):
+ @patch("posthog.tasks.exports.image_exporter._screenshot_asset_browserless")
+ @patch("posthog.tasks.exports.image_exporter._screenshot_asset_selenium")
+ def test_routes_to_browserless_when_flag_on(self, mock_selenium: Any, mock_browserless: Any) -> None:
+ image_exporter._screenshot_asset("p", "u", 800, ".ExportedInsight", use_browserless=True)
+
+ mock_browserless.assert_called_once()
+ mock_selenium.assert_not_called()
+
+ @patch("posthog.tasks.exports.image_exporter._screenshot_asset_browserless")
+ @patch("posthog.tasks.exports.image_exporter._screenshot_asset_selenium")
+ def test_routes_to_selenium_by_default(self, mock_selenium: Any, mock_browserless: Any) -> None:
+ image_exporter._screenshot_asset("p", "u", 800, ".ExportedInsight", use_browserless=False)
+
+ mock_selenium.assert_called_once()
+ mock_browserless.assert_not_called()
+
+
+class TestScreenshotAssetBrowserless(SimpleTestCase):
+ def test_connect_error_is_wrapped_as_browserless_unavailable(self) -> None:
+ playwright_obj = MagicMock()
+ playwright_obj.chromium.connect_over_cdp.side_effect = PlaywrightError("ECONNREFUSED")
+
+ # Mock the `with sync_playwright() as p:` shape: the context manager's
+ # __enter__ returns the playwright object whose .chromium.connect_over_cdp raises.
+ sync_playwright_cm = MagicMock()
+ sync_playwright_cm.__enter__.return_value = playwright_obj
+
+ with patch(
+ "posthog.tasks.exports.image_exporter.sync_playwright",
+ return_value=sync_playwright_cm,
+ ):
+ with patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"):
+ with self.assertRaises(BrowserlessUnavailable):
+ image_exporter._screenshot_asset_browserless("p", "u", 800, ".ExportedInsight")
+
+ def test_connect_error_redacts_token_and_breaks_chain(self) -> None:
+ token = "super-secret-token"
+ leaked = (
+ f"connect_over_cdp: WebSocket error connecting to wss://chrome.browserless.io/?token={token}&timeout=180000"
+ )
+ playwright_obj = MagicMock()
+ playwright_obj.chromium.connect_over_cdp.side_effect = PlaywrightError(leaked)
+ sync_playwright_cm = MagicMock()
+ sync_playwright_cm.__enter__.return_value = playwright_obj
+
+ with (
+ patch("posthog.tasks.exports.image_exporter.sync_playwright", return_value=sync_playwright_cm),
+ patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),
+ patch.object(settings, "BROWSERLESS_TOKEN", token),
+ ):
+ with self.assertRaises(BrowserlessUnavailable) as ctx:
+ image_exporter._screenshot_asset_browserless("p", "u", 800, ".ExportedInsight")
+
+ message = str(ctx.exception)
+ assert token not in message
+ assert "***" in message
+ assert ctx.exception.__cause__ is None
+ assert ctx.exception.__suppress_context__ is True
+
+ def test_goto_timeout_is_captured_and_reraised(self) -> None:
+ # Connect succeeds, but navigation times out — the debug-capture path must run
+ # for a goto (navigation) timeout, not just a selector timeout.
+ page = MagicMock()
+ page.goto.side_effect = PlaywrightTimeoutError("Timeout 30000ms exceeded")
+ context = MagicMock()
+ context.new_page.return_value = page
+ browser = MagicMock()
+ browser.new_context.return_value = context
+ playwright_obj = MagicMock()
+ playwright_obj.chromium.connect_over_cdp.return_value = browser
+ sync_playwright_cm = MagicMock()
+ sync_playwright_cm.__enter__.return_value = playwright_obj
+
+ with (
+ patch(
+ "posthog.tasks.exports.image_exporter.sync_playwright",
+ return_value=sync_playwright_cm,
+ ),
+ patch.object(settings, "BROWSERLESS_CDP_URL", "wss://chrome.browserless.io"),
+ patch("posthog.tasks.exports.image_exporter.capture_exception") as mock_capture,
+ ):
+ with self.assertRaises(PlaywrightTimeoutError) as ctx:
+ image_exporter._screenshot_asset_browserless("p", "u", 800, ".ExportedInsight")
+
+ mock_capture.assert_called_once()
+ # The re-raise preserves the original timeout as its cause (the message carries no secret, so chaining is safe).
+ assert isinstance(ctx.exception.__cause__, PlaywrightTimeoutError)
+ assert "Timeout 30000ms exceeded" in str(ctx.exception.__cause__)
+
+
+class TestDimensionHelpers(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("int_within_bounds", 1200, 800, 1200),
+ ("float_truncated", 1200.9, 800, 1200),
+ ("none_falls_back", None, 800, 800),
+ ("zero_falls_back", 0, 800, 800),
+ ("non_numeric_str_falls_back", "not-a-number", 800, 800),
+ ("above_max_capped", image_exporter.MAX_WIDTH_PIXELS + 1000, 800, image_exporter.MAX_WIDTH_PIXELS),
+ ]
+ )
+ def test_resolve_width(self, _name: str, raw_width: Any, screenshot_width: int, expected: int) -> None:
+ assert image_exporter._resolve_width(raw_width, screenshot_width, "https://example.com") == expected
+
+ @parameterized.expand(
+ [
+ ("none_uses_max", None, image_exporter.MAX_HEIGHT_PIXELS),
+ ("zero_uses_max", 0, image_exporter.MAX_HEIGHT_PIXELS),
+ ("below_max_uses_value", image_exporter.MAX_HEIGHT_PIXELS - 1000, image_exporter.MAX_HEIGHT_PIXELS - 1000),
+ ("above_max_uses_max", image_exporter.MAX_HEIGHT_PIXELS + 1000, image_exporter.MAX_HEIGHT_PIXELS),
+ ]
+ )
+ def test_effective_max_height(self, _name: str, max_height_pixels: Any, expected: int) -> None:
+ assert image_exporter._effective_max_height(max_height_pixels) == expected
+
+ @parameterized.expand(
+ [
+ ("at_or_below_max_unchanged", 3000, 5000, False, 3000),
+ ("above_max_capped", 6000, 5000, False, 5000),
+ ("final_above_max_capped", 6000, 5000, True, 5000),
+ ]
+ )
+ def test_cap_height(self, _name: str, raw_height: int, effective_max: int, final: bool, expected: int) -> None:
+ assert image_exporter._cap_height(raw_height, effective_max, "https://example.com", final=final) == expected
+
+
+class TestIsBrowserlessConnectionError(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("target_closed", "Target closed", True),
+ ("has_been_closed", "Browser has been closed", True),
+ ("connection_closed", "Connection closed while reading", True),
+ ("websocket", "WebSocket error: connection lost", True),
+ ("disconnected", "Browser disconnected unexpectedly", True),
+ ("econnrefused", "connect ECONNREFUSED 1.2.3.4:443", True),
+ ("http_503", "Server returned 503 Service Unavailable", False),
+ ("http_429", "Rejected with 429", False),
+ ("too_many_requests", "Too Many Requests", False),
+ (
+ "render_error_url_with_timestamp",
+ "page.goto: net::ERR_ABORTED at https://app.posthog.com/exporter?t=1700000000503",
+ False,
+ ),
+ ("render_bug", "TypeError: cannot read property of undefined", False),
+ ("selector_missing", "No node found for selector .ExportedInsight", False),
+ ("empty", "", False),
+ ]
+ )
+ def test_is_browserless_connection_error(self, _name: str, message: str, expected: bool) -> None:
+ assert image_exporter._is_browserless_connection_error(Exception(message)) is expected
+
+
+class TestImageExportRenderMetrics(APIBaseTest):
+ exported_asset: ExportedAsset
+
+ def setup_method(self, method: Any) -> None:
+ insight = Insight.objects.create(
+ team=self.team,
+ query={
+ "kind": "DataVisualizationNode",
+ "source": {"kind": "HogQLQuery", "query": "SELECT 1 as value"},
+ },
+ )
+ self.exported_asset = ExportedAsset.objects.create(
+ team=self.team,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ insight=insight,
+ )
+
+ @staticmethod
+ def _sample(name: str, labels: dict[str, str]) -> float:
+ # REGISTRY is global; treat a not-yet-emitted series (None) as 0 so assertions are deltas.
+ return REGISTRY.get_sample_value(name, labels) or 0.0
+
+ @patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")
+ @patch("os.remove")
+ @patch("posthog.tasks.exports.image_exporter._screenshot_asset")
+ def test_render_duration_success_counter_increments_for_selenium(
+ self, mock_screenshot_asset: Any, *args: Any
+ ) -> None:
+ success_labels = {"backend": "selenium", "outcome": "success"}
+ before = self._sample("image_export_render_duration_seconds_count", success_labels)
+
+ # Empty CDP URL makes _should_use_browserless return False (selenium) without evaluating the flag.
+ with self.settings(OBJECT_STORAGE_ENABLED=False, BROWSERLESS_CDP_URL=""):
+ image_exporter.export_image(self.exported_asset)
+
+ after = self._sample("image_export_render_duration_seconds_count", success_labels)
+ assert after - before == 1
+ assert mock_screenshot_asset.called
+
+ @patch("posthog.tasks.exports.image_exporter.open", new_callable=mock_open, read_data=b"image_data")
+ @patch("os.remove")
+ @patch("posthog.tasks.exports.image_exporter._screenshot_asset")
+ def test_render_failure_counters_increment_for_selenium(self, mock_screenshot_asset: Any, *args: Any) -> None:
+ # QueryError classifies as "user" via classify_failure_type.
+ mock_screenshot_asset.side_effect = QueryError("bad query")
+
+ failure_labels = {"backend": "selenium", "failure_type": "user"}
+ duration_labels = {"backend": "selenium", "outcome": "failure"}
+ failure_before = self._sample("image_export_render_failure_total", failure_labels)
+ duration_before = self._sample("image_export_render_duration_seconds_count", duration_labels)
+
+ with self.settings(OBJECT_STORAGE_ENABLED=False, BROWSERLESS_CDP_URL=""):
+ with self.assertRaises(QueryError):
+ image_exporter.export_image(self.exported_asset)
+
+ failure_after = self._sample("image_export_render_failure_total", failure_labels)
+ duration_after = self._sample("image_export_render_duration_seconds_count", duration_labels)
+ assert failure_after - failure_before == 1
+ assert duration_after - duration_before == 1