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(exports): render PNG image exports from ad-hoc queries without a saved insight (#70829)

Sam Pennington79a83c33d53a
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 80f65a199e9d..d523fc46ad38 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -2256,6 +2256,14 @@ snapshots:
hash: v1.k794b7964.c47193f52f4bee5394b5366fe7f77e3ce8686c4d54691538f8b977a9137cc916.2DnCcDgPakh32tzyI1rUrw1HuPsVdemKnwQbCtr71Vs
exporter-interview--shared-link--wide--light:
hash: v1.k794b7964.939486068c7a4e78a11e5935353c3ec3053409ffd0748a8791ca53b09354e9b1.n75MvjKUHChadX4HGhCUI67Z20X8Luv8IwFAez8je9U
+ exporter-other--adhoc-query-export--dark:
+ hash: v1.k794b7964.65aacbd6eb834b689ee6f07df03f0c16e81f279cc947adf3937e332d236f3bbb.uGoBlMm6Q-qAO5X2fXsqzJWWO47pHBvuRSLLbXd1KMQ
+ exporter-other--adhoc-query-export--light:
+ hash: v1.k794b7964.0a466b43158cfb24975196be7f97faed138d5dc68b6b3ca22b35f6465e6a65da.AfbtQH3MFWP7Ffo9iuZ24GGF4c2TOfmGPa_SfX1HjBE
+ exporter-other--adhoc-query-export-with-legend--dark:
+ hash: v1.k794b7964.48f1141d1c6ae35e845e5cdef0df00b6b98c8eba93ab7a93ece32785a441e9a3.KfvlvXhs2Y8nD-vrUaBafwNAzcTEX4ERYtJ4-L3lCvk
+ exporter-other--adhoc-query-export-with-legend--light:
+ hash: v1.k794b7964.545d1e6a388a3d45948309b410f23bb2ff1672a75449e30478bee7ee38964faf.LXP7c7jgg0WWhgdAMxCG7oAD1eET6kQinvPwn_HeFLA
exporter-other--event-table-insight--dark:
hash: v1.k794b7964.b49f709fd4150d9aa62e5e72280c1a01d36b8ce9a73151d49cdc903394406476.HroHAic6d-U6xImox3yNijT04GTbLpTRTwvaxN46Frg
exporter-other--event-table-insight--light:
diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsx
index 70068274b226..746e81763f4c 100644
--- a/frontend/src/exporter/Exporter.tsx
+++ b/frontend/src/exporter/Exporter.tsx
@@ -29,6 +29,7 @@ const LazyInsightScene = lazyWithRetry(() => import('./scenes/ExporterInsightSce
const LazyNotebookScene = lazyWithRetry(() => import('./scenes/ExporterNotebookScene'))
const LazyRecordingScene = lazyWithRetry(() => import('./scenes/ExporterRecordingScene'))
const LazyInterviewScene = lazyWithRetry(() => import('./scenes/ExporterInterviewScene'))
+const LazyQueryScene = lazyWithRetry(() => import('./scenes/ExporterQueryScene'))
function ExportedSceneSkeleton(): JSX.Element {
return (
@@ -80,6 +81,8 @@ export function Exporter(props: ExportedData): JSX.Element {
notebook,
insights,
inline_query_results: inlineQueryResults,
+ query,
+ query_results: queryResults,
themes,
accessToken,
exportToken,
@@ -91,12 +94,15 @@ export function Exporter(props: ExportedData): JSX.Element {
// A metric insight sizes to a compact card rather than filling the viewport, so drop the 100vh floor
// that would otherwise leave empty space below it (see Exporter.scss and ExportedInsight.scss).
+ // Applies to both saved insights and ad-hoc query exports — the image exporter narrows
+ // the screenshot viewport for both.
+ const metricQuery = insight?.query ?? query
const metric =
- insight &&
- isInsightVizNode(insight.query) &&
- isTrendsQuery(insight.query.source) &&
- insight.query.source.trendsFilter?.display === ChartDisplayType.Metric
- ? insight
+ metricQuery &&
+ isInsightVizNode(metricQuery) &&
+ isTrendsQuery(metricQuery.source) &&
+ metricQuery.source.trendsFilter?.display === ChartDisplayType.Metric
+ ? metricQuery
: undefined
const { currentTeam } = useValues(teamLogic)
@@ -215,6 +221,15 @@ export function Exporter(props: ExportedData): JSX.Element {
<Suspense fallback={<ExportedSceneSkeleton />}>
<LazyInsightScene insight={insight} themes={themes!} exportOptions={exportOptions} />
</Suspense>
+ ) : query ? (
+ <Suspense fallback={<ExportedSceneSkeleton />}>
+ <LazyQueryScene
+ query={query}
+ queryResults={queryResults}
+ themes={themes!}
+ exportOptions={exportOptions}
+ />
+ </Suspense>
) : dashboard ? (
<Suspense fallback={<ExportedSceneSkeleton />}>
<LazyDashboardScene dashboard={dashboard} type={type} themes={themes} />
diff --git a/frontend/src/exporter/scenes/ExporterQueryScene.test.tsx b/frontend/src/exporter/scenes/ExporterQueryScene.test.tsx
new file mode 100644
index 000000000000..d9ea6341f81a
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterQueryScene.test.tsx
@@ -0,0 +1,65 @@
+import { MOCK_DATA_COLOR_THEMES } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { cleanup, waitFor } from '@testing-library/react'
+
+import { setupJsdom, setupSyncRaf } from '@posthog/quill-charts/testing'
+
+import { renderWithInsights } from '~/test/insight-testing'
+
+import __trendsBarBreakdown from '../../mocks/fixtures/api/projects/team_id/insights/trendsBarBreakdown.json'
+import __trendsPie from '../../mocks/fixtures/api/projects/team_id/insights/trendsPie.json'
+import ExporterQueryScene from './ExporterQueryScene'
+
+let cleanupJsdom: () => void
+let cleanupRaf: () => void
+
+beforeEach(() => {
+ cleanupJsdom = setupJsdom()
+ cleanupRaf = setupSyncRaf()
+})
+
+afterEach(() => {
+ cleanupRaf()
+ cleanupJsdom()
+ cleanup()
+})
+
+describe('ExporterQueryScene', () => {
+ function renderAdhoc(fixture: any, legend = false): { container: HTMLElement } {
+ return renderWithInsights({
+ component: (
+ <ExporterQueryScene
+ query={fixture.query}
+ queryResults={{ results: fixture.result }}
+ themes={MOCK_DATA_COLOR_THEMES}
+ exportOptions={{ legend }}
+ />
+ ),
+ })
+ }
+
+ // An ad-hoc export has no cachedInsight, so the query only reaches insightDataLogic via insightProps.
+ // Miss that and it falls back to a bare TrendsQuery, rendering every export as a plain line chart.
+ it.each([
+ ['bar', __trendsBarBreakdown, 'trend-bar-graph'],
+ ['pie', __trendsPie, 'trend-pie-graph'],
+ ])('renders the %s display the query asks for', async (_name, fixture, dataAttr) => {
+ const { container } = renderAdhoc(fixture)
+
+ await waitFor(() => {
+ expect(container.querySelector(`[data-attr="${dataAttr}"]`)).toBeInTheDocument()
+ })
+ })
+
+ it('lets the chart draw the quill in-chart legend, like a saved-insight export', async () => {
+ const { container } = renderAdhoc(__trendsBarBreakdown, true)
+
+ await waitFor(() => {
+ expect(container.querySelector('[data-attr="hog-chart-timeseries-bar-legend"]')).toBeInTheDocument()
+ })
+ // Exactly one legend: the legacy horizontal legend below the chart must not render too.
+ expect(container.querySelector('.InsightLegendMenu')).not.toBeInTheDocument()
+ })
+})
diff --git a/frontend/src/exporter/scenes/ExporterQueryScene.tsx b/frontend/src/exporter/scenes/ExporterQueryScene.tsx
new file mode 100644
index 000000000000..e8618f89452c
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterQueryScene.tsx
@@ -0,0 +1,103 @@
+import '../ExportedInsight/ExportedInsight.scss'
+
+import clsx from 'clsx'
+import { BindLogic, useMountedLogic } from 'kea'
+
+import { InsightLegend } from 'lib/components/InsightLegend/InsightLegend'
+import { DISPLAY_TYPES_WITHOUT_LEGEND } from 'lib/components/InsightLegend/utils'
+import { SINGLE_SERIES_DISPLAY_TYPES } from 'lib/constants'
+import { dataThemeLogic } from 'scenes/dataThemeLogic'
+import { insightLogic } from 'scenes/insights/insightLogic'
+import { DISPLAYS_WITH_IN_CHART_LEGEND } from 'scenes/insights/insightVizDataLogic'
+
+import { Query } from '~/queries/Query/Query'
+import { SharingConfigurationSettings } from '~/queries/schema/schema-general'
+import { getDisplay, isInsightVizNode, isTrendsQuery } from '~/queries/utils'
+import { ChartDisplayType, InsightLogicProps } from '~/types'
+
+import { ExportedData } from '../types'
+
+/**
+ * Renders an ad-hoc query export (`export_context.source`, no saved insight) from the
+ * pre-computed result the sharing view inlined — never POSTs to the query API, which the
+ * asset token can't authenticate. Reuses the ExportedInsight classes so the image
+ * exporter's wait selector and content measurement work unchanged.
+ */
+export default function ExporterQueryScene({
+ query,
+ queryResults,
+ themes,
+ exportOptions,
+}: {
+ query: NonNullable<ExportedData['query']>
+ queryResults: ExportedData['query_results']
+ themes: NonNullable<ExportedData['themes']>
+ exportOptions: SharingConfigurationSettings
+}): JSX.Element {
+ useMountedLogic(dataThemeLogic({ themes }))
+
+ // getDisplay rather than a raw trendsFilter read, so deprecated display aliases pick the same
+ // legend layout here as the chart they get normalized to.
+ const trendsDisplay = isInsightVizNode(query) && isTrendsQuery(query.source) ? getDisplay(query.source) : undefined
+ const showLegend =
+ exportOptions.legend &&
+ isInsightVizNode(query) &&
+ isTrendsQuery(query.source) &&
+ !SINGLE_SERIES_DISPLAY_TYPES.includes(trendsDisplay as ChartDisplayType) &&
+ !DISPLAY_TYPES_WITHOUT_LEGEND.includes(trendsDisplay as ChartDisplayType)
+
+ // Displays covered by the quill in-chart legend draw the legend inside the chart itself.
+ const usesQuillInChartLegend =
+ !trendsDisplay || DISPLAYS_WITH_IN_CHART_LEGEND.includes(trendsDisplay as ChartDisplayType)
+
+ if (isInsightVizNode(query) && isTrendsQuery(query.source)) {
+ query = {
+ ...query,
+ source: {
+ ...query.source,
+ trendsFilter: usesQuillInChartLegend
+ ? // Pinned to the bottom to match the legacy exported layout (legend below the chart).
+ { ...query.source.trendsFilter, showLegend: !!showLegend, legendPosition: 'bottom' }
+ : // The legend is rendered separately below, so don't show it alongside the chart too.
+ { ...query.source.trendsFilter, showLegend: false },
+ },
+ }
+ }
+
+ // `query` carries the display type, breakdown, and formulas. Without it insightDataLogic falls back
+ // to a bare default TrendsQuery, and every ad-hoc export renders as a plain line chart. The
+ // `new-AdHoc.` prefix is what gates that props-query path — insightDataLogic ignores `props.query`
+ // under any other dashboardItemId.
+ const insightLogicProps: InsightLogicProps = {
+ dashboardItemId: 'new-AdHoc.export',
+ query,
+ doNotLoad: true,
+ }
+
+ return (
+ <BindLogic logic={insightLogic} props={insightLogicProps}>
+ <div
+ className={clsx(
+ 'ExportedInsight',
+ trendsDisplay === ChartDisplayType.Metric && 'ExportedInsight--metric'
+ )}
+ >
+ <div className="ExportedInsight__content">
+ <Query
+ query={query}
+ cachedResults={queryResults}
+ context={{ insightProps: insightLogicProps }}
+ embedded
+ readOnly
+ inSharedMode
+ />
+ {showLegend && !usesQuillInChartLegend && (
+ <div className="p-4">
+ <InsightLegend horizontal readOnly />
+ </div>
+ )}
+ </div>
+ </div>
+ </BindLogic>
+ )
+}
diff --git a/frontend/src/exporter/stories/ExporterOther.stories.tsx b/frontend/src/exporter/stories/ExporterOther.stories.tsx
index fe5d6ada3f9b..eef78ff9146b 100644
--- a/frontend/src/exporter/stories/ExporterOther.stories.tsx
+++ b/frontend/src/exporter/stories/ExporterOther.stories.tsx
@@ -1,4 +1,4 @@
-import type { Meta, StoryObj } from '@storybook/react'
+import type { Decorator, Meta, StoryObj } from '@storybook/react'
import { useEffect } from 'react'
import { ExportType, ExportedData } from '~/exporter/types'
@@ -8,6 +8,8 @@ import __dataTableHogQL from '../../mocks/fixtures/api/projects/team_id/insights
import __lifecycle from '../../mocks/fixtures/api/projects/team_id/insights/lifecycle.json'
import __retention from '../../mocks/fixtures/api/projects/team_id/insights/retention.json'
import __stickiness from '../../mocks/fixtures/api/projects/team_id/insights/stickiness.json'
+import __trendsBarBreakdown from '../../mocks/fixtures/api/projects/team_id/insights/trendsBarBreakdown.json'
+import __trendsLine from '../../mocks/fixtures/api/projects/team_id/insights/trendsLine.json'
import __userPaths from '../../mocks/fixtures/api/projects/team_id/insights/userPaths.json'
import { Exporter } from '../Exporter'
@@ -91,3 +93,35 @@ export const SQLInsightNoResults: Story = {
},
},
}
+
+/** Mirrors the 800px viewport the image exporter renders ad-hoc query exports in (see
+ * `_insight_query_screenshot_width`). Without it the test runner's shrink-to-fit root leaves the
+ * responsive chart canvas nothing to fill, collapsing the chart to the width of its axis labels. */
+const adhocExportViewport: Decorator = (StoryFn): JSX.Element => <div className="w-[800px]">{StoryFn()}</div>
+
+const adhocExportParameters = {
+ testOptions: { waitForSelector: '.ExportedInsight canvas' },
+}
+
+/** Ad-hoc query image export (`export_context.source`) — a query rendered from inlined results, with no saved insight. */
+export const AdhocQueryExport: Story = {
+ args: {
+ type: ExportType.Image,
+ query: (__trendsLine as any).query,
+ query_results: { results: (__trendsLine as any).result },
+ },
+ decorators: [adhocExportViewport],
+ parameters: adhocExportParameters,
+}
+
+/** Multi-series ad-hoc export with `?legend=true` — the horizontal exporter legend below the chart, never the in-chart side legend. */
+export const AdhocQueryExportWithLegend: Story = {
+ args: {
+ type: ExportType.Image,
+ query: (__trendsBarBreakdown as any).query,
+ query_results: { results: (__trendsBarBreakdown as any).result },
+ legend: true,
+ },
+ decorators: [adhocExportViewport],
+ parameters: adhocExportParameters,
+}
diff --git a/frontend/src/exporter/types.ts b/frontend/src/exporter/types.ts
index 13f071a46c4c..f8cb7f21e3f6 100644
--- a/frontend/src/exporter/types.ts
+++ b/frontend/src/exporter/types.ts
@@ -1,7 +1,7 @@
import { NotebookType } from 'scenes/notebooks/types'
import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
-import { AnyResponseType, SharingConfigurationSettings } from '~/queries/schema/schema-general'
+import { AnyResponseType, QuerySchema, SharingConfigurationSettings } from '~/queries/schema/schema-general'
import {
CohortType,
DashboardType,
@@ -61,6 +61,12 @@ export interface ExportedData extends SharingConfigurationSettings {
* `<Query cachedResults={…} />` without ever hitting the query API.
*/
inline_query_results?: Record<string, AnyResponseType>
+ /**
+ * Ad-hoc query for an insight-less image export (`export_context.source`), with its
+ * pre-computed result in `query_results` — same rationale as `inline_query_results`.
+ */
+ query?: QuerySchema
+ query_results?: AnyResponseType
autoplay?: boolean
/** Player adds border by default - we want to remove it **/
noBorder?: boolean
diff --git a/posthog/api/sharing.py b/posthog/api/sharing.py
index 8f51d3d6245b..6ee001437276 100644
--- a/posthog/api/sharing.py
+++ b/posthog/api/sharing.py
@@ -1226,6 +1226,51 @@ class SharingViewerPageViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSe
except Exception:
raise NotFound("No heatmap found")
+ elif isinstance(resource, ExportedAsset) and resource.export_context and resource.export_context.get("source"):
+ # Ad-hoc query export (no saved insight): compute the query server-side and inline the
+ # result so the exporter page can render `<Query cachedResults={…} />` without POSTing
+ # to the query API (which the asset token can't authenticate). The image exporter warms
+ # the cache right before rendering, so this is normally a cache hit.
+ # Render-once assets: only the exporter's short-lived render token may trigger this compute.
+ if self._token_purpose != EXPORTED_ASSET_PURPOSE_RENDER:
+ raise NotFound()
+ source_query = resource.export_context["source"]
+ execution_mode = shared_insights_execution_mode(
+ ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ ).execution_mode
+ try:
+ query_response = process_query_dict(
+ resource.team,
+ source_query,
+ execution_mode=execution_mode,
+ # Anonymous render surface; attribute the read to the export owner so
+ # warehouse HogQL access control resolves against their access.
+ user=resource.created_by,
+ )
+ except Exception as e:
+ logger.warning("exported_query_calculation_failed", asset_id=resource.id, exc_info=True)
+ capture_exception(e)
+ raise NotFound("Query could not be calculated")
+
+ serialized_response: Any = None
+ if isinstance(query_response, BaseModel):
+ serialized_response = query_response.model_dump(mode="json")
+ elif isinstance(query_response, dict):
+ serialized_response = query_response
+ # `process_query_dict` swallows validation errors and returns a response with `error`
+ # populated — don't ship those to the anonymous exporter page.
+ if not isinstance(serialized_response, dict) or serialized_response.get("error"):
+ logger.warning("exported_query_returned_error", asset_id=resource.id)
+ raise NotFound("Query could not be calculated")
+
+ asset_title = "Query"
+ exported_data.update(
+ {
+ "query": source_query,
+ "query_results": serialized_response,
+ "themes": get_themes_for_team(resource.team),
+ }
+ )
elif isinstance(resource, SharingConfiguration) and resource.interviewee_context:
from products.user_interviews.backend.facade.api import (
has_replied,
diff --git a/posthog/api/test/test_sharing.py b/posthog/api/test/test_sharing.py
index 013202d604cb..e57af21a03a0 100644
--- a/posthog/api/test/test_sharing.py
+++ b/posthog/api/test/test_sharing.py
@@ -1525,6 +1525,54 @@ class TestExportCacheKeyFlow(APIBaseTest):
mock_calculate.assert_called_once()
+class TestSharedAdhocQueryExport(APIBaseTest):
+ """The /exporter page for an insight-less PNG asset (export_context.source) must inline the
+ pre-computed query result — the anonymous page can't authenticate against the query API."""
+
+ _SOURCE_QUERY = {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [{"event": "$pageview"}]}}
+
+ def _create_asset(self) -> ExportedAsset:
+ return ExportedAsset.objects.create(
+ team=self.team,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ created_by=self.user,
+ export_context={"source": self._SOURCE_QUERY},
+ )
+
+ @patch("posthog.api.sharing.process_query_dict")
+ @patch("posthog.api.sharing.render_template")
+ def test_exporter_page_inlines_query_and_results(self, mock_render_template, mock_process_query):
+ mock_render_template.return_value = HttpResponse("<html></html>")
+ mock_process_query.return_value = {"results": [{"count": 42}], "cache_key": "abc"}
+ asset = self._create_asset()
+
+ response = self.client.get(f"/exporter?token={get_render_access_token(asset)}")
+ assert response.status_code == 200
+
+ exported_data = json.loads(mock_render_template.call_args[1]["context"]["exported_data"])
+ assert exported_data["query"] == self._SOURCE_QUERY
+ assert exported_data["query_results"] == {"results": [{"count": 42}], "cache_key": "abc"}
+ # The read must be attributed to the export owner so warehouse access control resolves.
+ assert mock_process_query.call_args[1]["user"] == self.user
+
+ @parameterized.expand(
+ [
+ ("query_raises", Exception("boom"), None),
+ ("query_returns_error", None, {"error": "boom"}),
+ ]
+ )
+ @patch("posthog.api.sharing.process_query_dict")
+ def test_exporter_page_404s_when_query_cannot_be_calculated(
+ self, _name, side_effect, return_value, mock_process_query
+ ):
+ mock_process_query.side_effect = side_effect
+ mock_process_query.return_value = return_value
+ asset = self._create_asset()
+
+ response = self.client.get(f"/exporter?token={get_render_access_token(asset)}")
+ assert response.status_code == 404
+
+
class TestSharedCohortInlining(APIBaseTest):
@mock_exporter_template
def test_shared_insight_inlines_referenced_cohort_names(self):
diff --git a/products/exports/backend/api/exports.py b/products/exports/backend/api/exports.py
index 68202cf5b86e..8bd5ac15cbb6 100644
--- a/products/exports/backend/api/exports.py
+++ b/products/exports/backend/api/exports.py
@@ -515,4 +515,8 @@ class ExportedAssetViewSet(
@action(methods=["GET"], detail=True, required_scopes=["export:read"])
def content(self, request: Request, *args: Any, **kwargs: Any) -> HttpResponse:
instance = self.get_object()
- return get_content_response(instance, request.query_params.get("download") == "true")
+ return get_content_response(
+ instance,
+ download=request.query_params.get("download") == "true",
+ direct=request.query_params.get("direct") == "true",
+ )
diff --git a/products/exports/backend/facade/api.py b/products/exports/backend/facade/api.py
new file mode 100644
index 000000000000..fec1a26fd75a
--- /dev/null
+++ b/products/exports/backend/facade/api.py
@@ -0,0 +1,117 @@
+"""Facade for the exports product — the surface other products may import.
+
+Currently exposes synchronous PNG rendering so composed endpoints (e.g. a task run
+delivering a chart to Slack) can render server-side without shuttling bytes through
+API clients.
+"""
+
+from datetime import timedelta
+
+from django.conf import settings
+
+import structlog
+from asgiref.sync import async_to_sync
+from temporalio.common import WorkflowIDReusePolicy
+
+from posthog.models import Team, User
+from posthog.rbac.user_access_control import UserAccessControl
+from posthog.storage import object_storage
+from posthog.temporal.common.client import async_connect
+from posthog.temporal.exports.workflows import ExportAssetWorkflow, ExportAssetWorkflowInputs
+
+from products.exports.backend.models.exported_asset import ExportedAsset
+from products.product_analytics.backend.models.insight import Insight
+
+logger = structlog.get_logger(__name__)
+
+# Caps the whole workflow including retries; callers block on this, so it must stay
+# well under the web tier's request timeout.
+RENDER_TIMEOUT = timedelta(seconds=90)
+
+
+def _validate_adhoc_export_context(export_context: dict) -> None:
+ """The ad-hoc render pipeline (viewport sizing, the exporter page's Query dispatch)
+ assumes an InsightVizNode-wrapped source; anything else renders a JSON dump instead
+ of a chart, so reject it here with a real error instead."""
+ source = export_context.get("source")
+ if not isinstance(source, dict) or source.get("kind") != "InsightVizNode":
+ raise ValueError("export_context.source must be an InsightVizNode-wrapped query")
+
+
+def render_png_export(
+ *,
+ team: Team,
+ created_by: User,
+ export_context: dict | None = None,
+ insight_id: int | None = None,
+) -> tuple[ExportedAsset, bytes | None]:
+ """Render a PNG export synchronously and return the asset together with its content bytes.
+
+ Blocks until the export workflow finishes (typically a few seconds). On failure the
+ returned bytes are None and ``asset.exception`` carries the error.
+ """
+ if created_by is None:
+ # Access control below resolves against created_by; a principal-less render would
+ # silently skip it, so service callers must attribute the render to a real user.
+ raise ValueError("created_by is required")
+ if (export_context is None) == (insight_id is None):
+ raise ValueError("Provide exactly one of export_context or insight_id")
+ if export_context is not None:
+ _validate_adhoc_export_context(export_context)
+ if insight_id is not None:
+ insight = Insight.objects.filter(id=insight_id, team_id=team.id, deleted=False).first()
+ # Object-level access matters here: created_by may not be allowed to view the insight.
+ if insight is None or not UserAccessControl(user=created_by, team=team).check_access_level_for_object(
+ insight, "viewer"
+ ):
+ raise ValueError("Insight not found")
+
+ asset = ExportedAsset.objects.create(
+ team=team,
+ created_by=created_by,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ export_context=export_context,
+ insight_id=insight_id,
+ )
+
+ async def _run() -> None:
+ client = await async_connect()
+ await client.execute_workflow(
+ ExportAssetWorkflow.run,
+ ExportAssetWorkflowInputs(
+ exported_asset_id=asset.id,
+ team_id=team.id,
+ distinct_id=str(created_by.distinct_id),
+ ),
+ id=f"export-asset-{asset.id}",
+ task_queue=settings.ANALYTICS_PLATFORM_TASK_QUEUE,
+ id_reuse_policy=WorkflowIDReusePolicy.TERMINATE_IF_RUNNING,
+ execution_timeout=RENDER_TIMEOUT,
+ )
+
+ try:
+ async_to_sync(_run)()
+ except Exception as e:
+ # export_asset_direct records activity failures on the asset, but a dispatch
+ # failure (Temporal unreachable, workflow never started) would leave
+ # asset.exception empty — record it so the documented failure contract
+ # ("bytes are None and asset.exception carries the error") always holds.
+ logger.info("render_png_export_failed", asset_id=asset.id, error=str(e))
+ asset.refresh_from_db()
+ if not asset.exception:
+ asset.exception = str(e) or "Export dispatch failed"
+ asset.save(update_fields=["exception"])
+
+ asset.refresh_from_db()
+ if asset.exception:
+ return asset, None
+ content = asset.content
+ if not content and asset.content_location:
+ content = object_storage.read_bytes(asset.content_location)
+ if not content:
+ # A workflow that reports success but stores nothing would otherwise return no bytes
+ # and no exception, leaving callers unable to tell it apart from a successful render.
+ asset.exception = "Export produced no content"
+ asset.save(update_fields=["exception"])
+ return asset, None
+ return asset, bytes(content)
diff --git a/products/exports/backend/models/exported_asset.py b/products/exports/backend/models/exported_asset.py
index 2e47f921bff4..440eb4a8838a 100644
--- a/products/exports/backend/models/exported_asset.py
+++ b/products/exports/backend/models/exported_asset.py
@@ -240,8 +240,17 @@ def asset_for_token(token: str) -> tuple[ExportedAsset, str | None]:
return asset, info.get("purpose")
-def get_content_response(asset: ExportedAsset, download: bool = False):
- if asset.content_location:
+# Formats direct mode may buffer through a web worker. Rendered chart/dashboard screenshots
+# are size-bounded; videos and spreadsheets are not, and read_bytes loads the whole object,
+# so unbounded formats keep the presigned redirect regardless of ?direct.
+_DIRECT_CONTENT_FORMATS = frozenset({ExportedAsset.ExportFormat.PNG})
+
+
+def get_content_response(asset: ExportedAsset, download: bool = False, direct: bool = False):
+ # direct=True serves the bytes instead of redirecting to a presigned object-storage URL,
+ # for API clients (e.g. sandboxed agents) that can reach PostHog but not the storage host.
+ direct = direct and asset.export_format in _DIRECT_CONTENT_FORMATS
+ if asset.content_location and not direct:
content_disposition = f'attachment; filename="{asset.filename}"' if download else None
presigned_url = object_storage.get_presigned_url(
asset.content_location,
@@ -252,6 +261,8 @@ def get_content_response(asset: ExportedAsset, download: bool = False):
return HttpResponseRedirect(presigned_url)
content = asset.content
+ if not content and asset.content_location:
+ content = object_storage.read_bytes(asset.content_location)
if not content:
raise NotFound()
diff --git a/products/exports/backend/tasks/image_exporter.py b/products/exports/backend/tasks/image_exporter.py
index 9150b20109b9..e207e65f07e7 100644
--- a/products/exports/backend/tasks/image_exporter.py
+++ b/products/exports/backend/tasks/image_exporter.py
@@ -22,6 +22,7 @@ from posthog.schema import ChartDisplayType, FunnelLayout, NodeKind
from posthog.hogql.errors import TableAccessDeniedError
+from posthog.api.services.query import process_query_dict
from posthog.caching.calculate_results import calculate_for_query_based_insight
from posthog.event_usage import AnalyticsProps, EventSource
from posthog.exceptions_capture import capture_exception
@@ -137,6 +138,49 @@ ScreenWidth = Literal[600, 800, 1920, 1400, 4000]
CSSSelector = Literal[".InsightCard", ".ExportedInsight", ".replayer-wrapper", ".heatmap-exporter"]
+def _insight_query_wants_legend(query: dict) -> bool:
+ """A static PNG has no hover tooltips, so multi-series charts default the exporter's
+ horizontal legend on — unless the query explicitly opted out."""
+ source = query.get("source", query) # This to handle the InsightVizNode wrapper
+ if not isinstance(source, dict) or source.get("kind") != NodeKind.TRENDS_QUERY:
+ return False
+ trends_filter = source.get("trendsFilter") or {}
+ if trends_filter.get("showLegend") is False:
+ return False
+ series = source.get("series")
+ return (isinstance(series, list) and len(series) > 1) or bool(source.get("breakdownFilter"))
+
+
+def _insight_query_screenshot_width(query: dict) -> ScreenWidth:
+ """Initial viewport width for an insight-style query render.
+
+ Only left-to-right funnels (vertical layout, which is the default) need the wide
+ viewport — they grow horizontally with step count. Top-to-bottom funnels (horizontal
+ layout) grow vertically, not horizontally. Small funnels are constrained later by the
+ width measurement. The higher the number, the more RAM the Chromium driver needs.
+
+ A metric renders as a wide 2:1 card whose height derives from the viewport width, so a
+ narrower viewport keeps it at dashboard-tile size instead of a 400px-tall banner.
+ Mirrors the frontend's check (InsightVizNode wrapper required), which gates the
+ metric card CSS — a bare TrendsQuery gets neither, so it must keep the default viewport.
+ """
+ source = query.get("source", query) # This to handle the InsightVizNode wrapper
+ is_funnel = source.get("kind") == NodeKind.FUNNELS_QUERY
+ funnels_filter = source.get("funnelsFilter") or {}
+ funnel_layout = funnels_filter.get("layout")
+ is_left_to_right_funnel = is_funnel and (funnel_layout is None or funnel_layout == FunnelLayout.VERTICAL)
+ if is_left_to_right_funnel:
+ return 4000
+
+ trends_filter = source.get("trendsFilter") or {}
+ is_metric = (
+ query.get("kind") == NodeKind.INSIGHT_VIZ_NODE
+ and source.get("kind") == NodeKind.TRENDS_QUERY
+ and trends_filter.get("display") == ChartDisplayType.METRIC
+ )
+ return 600 if is_metric else 800
+
+
def _export_to_png(
exported_asset: ExportedAsset,
max_height_pixels: Optional[int] = None,
@@ -187,33 +231,7 @@ def _export_to_png(
cache_keys_param = _build_cache_keys_param(insight_cache_keys)
url_to_render = absolute_uri(f"/exporter?token={access_token}{legend_param}{cache_keys_param}")
wait_for_css_selector = ".ExportedInsight"
- query = exported_asset.insight.query or {}
- source = query.get("source", query) # This to handle the InsightVizNode wrapper
- is_funnel = source.get("kind") == NodeKind.FUNNELS_QUERY
- # Only use wide width for left-to-right funnels (vertical layout, which is the default)
- # Top-to-bottom funnels (horizontal layout) grow vertically, not horizontally
- funnels_filter = source.get("funnelsFilter") or {}
- funnel_layout = funnels_filter.get("layout")
- is_left_to_right_funnel = is_funnel and (funnel_layout is None or funnel_layout == FunnelLayout.VERTICAL)
- # A metric renders as a wide 2:1 card whose height derives from the viewport width, so a
- # narrower viewport keeps it at dashboard-tile size instead of a 400px-tall banner.
- # Mirrors the frontend's check (InsightVizNode wrapper required), which gates the
- # metric card CSS — a bare TrendsQuery gets neither, so it must keep the default viewport.
- trends_filter = source.get("trendsFilter") or {}
- is_metric = (
- query.get("kind") == NodeKind.INSIGHT_VIZ_NODE
- and source.get("kind") == NodeKind.TRENDS_QUERY
- and trends_filter.get("display") == ChartDisplayType.METRIC
- )
- # Set initial window size large enough for wide content like left-to-right funnels with many steps
- # Small funnels will be constrained later.
- # The higher the number, the more RAM will be required by the Chromium driver.
- if is_left_to_right_funnel:
- screenshot_width = 4000
- elif is_metric:
- screenshot_width = 600
- else:
- screenshot_width = 800
+ screenshot_width = _insight_query_screenshot_width(exported_asset.insight.query or {})
elif exported_asset.dashboard is not None:
cache_keys_param = _build_cache_keys_param(insight_cache_keys)
url_to_render = absolute_uri(f"/exporter?token={access_token}{cache_keys_param}")
@@ -264,9 +282,21 @@ def _export_to_png(
css_selector=wait_for_css_selector,
token_preview=access_token[:10],
)
+ elif exported_asset.export_context and exported_asset.export_context.get("source"):
+ # Ad-hoc query export: no saved insight, the query lives in export_context. The
+ # sharing view computes the (cache-warmed) result server-side at page load, so
+ # give the navigation extra headroom over the insight path.
+ # The exporter page still skips the legend for display types without one.
+ legend_param = (
+ "&legend=true" if _insight_query_wants_legend(exported_asset.export_context["source"]) else ""
+ )
+ url_to_render = absolute_uri(f"/exporter?token={access_token}{legend_param}")
+ wait_for_css_selector = ".ExportedInsight"
+ screenshot_width = _insight_query_screenshot_width(exported_asset.export_context["source"])
+ page_load_timeout = 100
else:
raise InvalidExportContext(
- "Export is missing required dashboard, insight ID, or session_recording_id in export_context"
+ "Export is missing required dashboard, insight ID, session_recording_id, or query source in export_context"
)
logger.info("exporting_asset", asset_id=exported_asset.id, render_url=url_to_render)
@@ -596,6 +626,26 @@ def export_image(
)
if result.cache_key:
insight_cache_keys[insight.id] = result.cache_key
+ elif exported_asset.export_context and exported_asset.export_context.get("source"):
+ logger.info("export_image.calculate_adhoc_query", asset_id=exported_asset.id)
+ # Ad-hoc query export: run the query now so a bad query fails here (with a real
+ # exception on the asset) rather than inside the headless browser, and so the
+ # sharing view's cache-aggressive recompute at page load is a cache hit.
+ warm_result = process_query_dict(
+ exported_asset.team,
+ exported_asset.export_context["source"],
+ execution_mode=ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE,
+ # Background render (no request user); attribute the read to the export owner.
+ user=exported_asset.created_by,
+ )
+ # Validation failures come back as an error response rather than raising
+ # (process_query_dict only raises for dashboard contexts) — surface them here
+ # instead of letting the render burn a browserless timeout on a broken page.
+ warm_error = (
+ warm_result.get("error") if isinstance(warm_result, dict) else getattr(warm_result, "error", None)
+ )
+ if warm_error:
+ raise InvalidExportContext(f"Invalid query: {warm_error}")
if exported_asset.export_format == "image/png":
with EXPORT_TIMER.labels(type=exported_asset.export_format).time():
diff --git a/products/exports/backend/tasks/test/test_image_exporter.py b/products/exports/backend/tasks/test/test_image_exporter.py
index a221290de6ff..0ba37577481f 100644
--- a/products/exports/backend/tasks/test/test_image_exporter.py
+++ b/products/exports/backend/tasks/test/test_image_exporter.py
@@ -102,6 +102,57 @@ class TestImageExporter(APIBaseTest):
with self.assertRaises(InvalidExportContext):
image_exporter._export_to_png(exported_asset)
+ @patch("products.exports.backend.tasks.image_exporter.process_query_dict")
+ def test_adhoc_query_export_renders_without_insight(
+ self,
+ mock_process_query: Any,
+ mock_remove: Any,
+ mock_open_file: Any,
+ mock_screenshot_asset: Any,
+ ) -> None:
+ mock_process_query.return_value = {"results": []}
+ source = {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [{"event": "$pageview"}]}}
+ exported_asset = ExportedAsset.objects.create(
+ team=self.team,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ created_by=self.user,
+ export_context={"source": source},
+ )
+
+ with self.settings(OBJECT_STORAGE_ENABLED=False):
+ image_exporter.export_image(exported_asset)
+
+ call_args, call_kwargs = mock_process_query.call_args
+ assert call_args == (self.team, source)
+ assert call_kwargs["execution_mode"] == ExecutionMode.RECENT_CACHE_CALCULATE_BLOCKING_IF_STALE
+ assert call_kwargs["user"] == self.user
+
+ url_to_render = mock_screenshot_asset.call_args[0][1]
+ assert "/exporter?token=" in url_to_render
+ assert exported_asset.content == b"image_data"
+
+ @patch("products.exports.backend.tasks.image_exporter.process_query_dict")
+ def test_adhoc_query_export_fails_fast_on_invalid_query(
+ self,
+ mock_process_query: Any,
+ mock_remove: Any,
+ mock_open_file: Any,
+ mock_screenshot_asset: Any,
+ ) -> None:
+ mock_process_query.return_value = {"results": None, "error": "1 validation error for QuerySchemaRoot"}
+ exported_asset = ExportedAsset.objects.create(
+ team=self.team,
+ export_format=ExportedAsset.ExportFormat.PNG,
+ created_by=self.user,
+ export_context={"source": {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}}},
+ )
+
+ with self.settings(OBJECT_STORAGE_ENABLED=False), self.assertRaisesRegex(Exception, "Invalid query"):
+ image_exporter.export_image(exported_asset)
+
+ # The browser must never be reached — the point is failing before the render.
+ mock_screenshot_asset.assert_not_called()
+
def test_image_exporter_writes_to_asset_when_object_storage_is_disabled(self, *args: Any) -> None:
with self.settings(OBJECT_STORAGE_ENABLED=False):
image_exporter.export_image(self.exported_asset)
@@ -648,6 +699,92 @@ class TestImageExporterQueryOverrideE2E(ClickhouseTestMixin, APIBaseTest):
assert url_default != url_override
+class TestInsightQueryScreenshotWidth(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("funnel_default_layout", {"kind": "InsightVizNode", "source": {"kind": "FunnelsQuery"}}, 4000),
+ (
+ "funnel_explicit_vertical",
+ {"kind": "InsightVizNode", "source": {"kind": "FunnelsQuery", "funnelsFilter": {"layout": "vertical"}}},
+ 4000,
+ ),
+ (
+ "funnel_horizontal",
+ {
+ "kind": "InsightVizNode",
+ "source": {"kind": "FunnelsQuery", "funnelsFilter": {"layout": "horizontal"}},
+ },
+ 800,
+ ),
+ ("bare_funnel_query_without_wrapper", {"kind": "FunnelsQuery"}, 4000),
+ ("trends", {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery"}}, 800),
+ (
+ "metric",
+ {
+ "kind": "InsightVizNode",
+ "source": {"kind": "TrendsQuery", "trendsFilter": {"display": "Metric"}},
+ },
+ 600,
+ ),
+ (
+ "bare_metric_query_without_wrapper",
+ {"kind": "TrendsQuery", "trendsFilter": {"display": "Metric"}},
+ 800,
+ ),
+ ("empty_query", {}, 800),
+ ]
+ )
+ def test_width_for_query(self, _name: str, query: dict, expected: int) -> None:
+ assert image_exporter._insight_query_screenshot_width(query) == expected
+
+
+class TestInsightQueryWantsLegend(SimpleTestCase):
+ @parameterized.expand(
+ [
+ (
+ "two_series_gets_legend",
+ {
+ "kind": "InsightVizNode",
+ "source": {"kind": "TrendsQuery", "series": [{"event": "a"}, {"event": "b"}]},
+ },
+ True,
+ ),
+ (
+ "breakdown_gets_legend",
+ {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"event": "a"}],
+ "breakdownFilter": {"breakdown": "$browser"},
+ },
+ },
+ True,
+ ),
+ (
+ "single_series_skipped",
+ {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [{"event": "a"}]}},
+ False,
+ ),
+ (
+ "explicit_false_respected",
+ {
+ "kind": "InsightVizNode",
+ "source": {
+ "kind": "TrendsQuery",
+ "series": [{"event": "a"}, {"event": "b"}],
+ "trendsFilter": {"showLegend": False},
+ },
+ },
+ False,
+ ),
+ ("non_insight_kind", {"kind": "DataTableNode"}, False),
+ ]
+ )
+ def test_legend_defaulting(self, _name: str, query: dict, expected: bool) -> None:
+ assert image_exporter._insight_query_wants_legend(query) == expected
+
+
class TestBuildCdpEndpoint(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/exports/backend/tests/test_exported_asset_model.py b/products/exports/backend/tests/test_exported_asset_model.py
index 4187336b1d8f..e5c252c783e4 100644
--- a/products/exports/backend/tests/test_exported_asset_model.py
+++ b/products/exports/backend/tests/test_exported_asset_model.py
@@ -2,10 +2,17 @@ from datetime import UTC, datetime, timedelta
from freezegun import freeze_time
from posthog.test.base import APIBaseTest
+from unittest.mock import patch
from parameterized import parameterized
-from products.exports.backend.models.exported_asset import SEVEN_DAYS, SIX_MONTHS, TWELVE_MONTHS, ExportedAsset
+from products.exports.backend.models.exported_asset import (
+ SEVEN_DAYS,
+ SIX_MONTHS,
+ TWELVE_MONTHS,
+ ExportedAsset,
+ get_content_response,
+)
class TestExportedAssetModel(APIBaseTest):
@@ -180,3 +187,27 @@ class TestExportedAssetFilename(APIBaseTest):
export_context={"filename": "cohort-test"},
)
assert asset.filename == "cohort-test-2024-06-15-103000.xlsx"
+
+
+class TestDirectContentResponse(APIBaseTest):
+ @parameterized.expand(
+ [
+ ("bounded_png_serves_bytes", ExportedAsset.ExportFormat.PNG, 200),
+ ("unbounded_video_redirects", ExportedAsset.ExportFormat.MP4, 302),
+ ]
+ )
+ def test_direct_mode_only_buffers_bounded_formats(
+ self, _name: str, export_format: str, expected_status: int
+ ) -> None:
+ asset = ExportedAsset.objects.create(
+ team=self.team,
+ export_format=export_format,
+ content=b"bytes" if expected_status == 200 else None,
+ content_location="exports/some/key" if expected_status == 302 else None,
+ )
+ with patch(
+ "products.exports.backend.models.exported_asset.object_storage.get_presigned_url",
+ return_value="https://storage.example.com/presigned",
+ ):
+ response = get_content_response(asset, direct=True)
+ assert response.status_code == expected_status
diff --git a/products/exports/backend/tests/test_facade.py b/products/exports/backend/tests/test_facade.py
new file mode 100644
index 000000000000..b02ec287e2fe
--- /dev/null
+++ b/products/exports/backend/tests/test_facade.py
@@ -0,0 +1,24 @@
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.exports.backend.facade.api import _validate_adhoc_export_context
+
+
+class TestValidateAdhocExportContext(SimpleTestCase):
+ def test_accepts_insight_viz_wrapped_source(self):
+ _validate_adhoc_export_context(
+ {"source": {"kind": "InsightVizNode", "source": {"kind": "TrendsQuery", "series": [{"event": "a"}]}}}
+ )
+
+ @parameterized.expand(
+ [
+ ("bare_trends_query", {"source": {"kind": "TrendsQuery", "series": [{"event": "a"}]}}),
+ ("data_table", {"source": {"kind": "DataTableNode"}}),
+ ("non_dict_source", {"source": "SELECT 1"}),
+ ("missing_source", {}),
+ ]
+ )
+ def test_rejects_unwrapped_sources(self, _name, export_context):
+ with self.assertRaises(ValueError):
+ _validate_adhoc_export_context(export_context)