: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
feat(canvas): pass SQL variables through ph.loadInsight (#81416)
Dylan Martin070f8997cd93
diff --git a/products/canvas/skills/querying-canvas-data/SKILL.md b/products/canvas/skills/querying-canvas-data/SKILL.mdindex 386c69baf30c..c888703bcc6a 100644--- a/products/canvas/skills/querying-canvas-data/SKILL.md+++ b/products/canvas/skills/querying-canvas-data/SKILL.md@@ -62,12 +62,34 @@ rows.— the saved insight re-scopes to the window with no time SQL. Typed nodes take the same`dateRange`. Re-run every query when the window changes.- A saved **SQL** insight may ignore `dateRange` (its window lives inside the SQL) — a reason to- prefer insight query types.+ prefer insight query types. If its window comes from a `{variables.…}` placeholder, drive it+ through `variables` (below) instead; `dateRange` will never reach it.- Inline HogQL escape hatch only: never bake `now()` or a hardcoded INTERVAL. Compute unix bounds(`Math.floor(win.start.getTime() / 1000)`) and write half-open`timestamp >= toDateTime(fromUnix) AND timestamp < toDateTime(toUnix)`. Prior period = theequal-length window immediately before; bucket with `toStartOfDay`/`toStartOfHour`.+## SQL variables++A saved SQL insight whose HogQL contains `{variables.name}` placeholders takes its values per call,+keyed by the variable's **code name** (not its uuid):++```js+await ph.loadInsight(shortId, { variables: { product: 'surveys', month: '2026-07-01' } })+```++This is how one saved insight fills a whole board — the same per-product insight loaded once per+product — rather than every tile resolving the insight's saved default.++- Read the code names off the insight's query first (`insight-get` over MCP). The host **rejects** a+ variable the insight doesn't use, and rejects one whose value didn't take effect, instead of+ silently falling back to the saved value — so a variable mismatch surfaces as a visible error, not+ as another product's numbers.+- Variables are part of the read cache key, so N products means N loads. Prefer **one** insight+ returning every product as rows over the same insight loaded N times, and slice it client-side.+- Values are typed by the variable's definition in PostHog (String / Number / Boolean / Date / List);+ pass the same shape the insight expects, and an array for a multi-select List variable.+## Side effects- `ph.capture(event, properties?, distinctId?)` — analytics events for interactionsdiff --git a/products/desktop/packages/core/src/canvas/canvasDataService.test.ts b/products/desktop/packages/core/src/canvas/canvasDataService.test.tsindex fb8b2dd35971..4b5c6a769ffe 100644--- a/products/desktop/packages/core/src/canvas/canvasDataService.test.ts+++ b/products/desktop/packages/core/src/canvas/canvasDataService.test.ts@@ -27,6 +27,7 @@ function insight(partial: Partial<InsightFetchResult>): InsightFetchResult {queryKind: "TrendsQuery",columns: [],results: [],+ resolvedVariables: {},...partial,};}@@ -94,6 +95,63 @@ describe("CanvasDataService.loadInsight", () => {);});+ it("forwards SQL variables alongside the date window", async () => {+ fetchInsightByShortId.mockResolvedValue(+ insight({ resolvedVariables: { product: "surveys" } }),+ );++ await makeService().loadInsight({+ shortId: "abc123",+ variables: { product: "surveys" },+ });++ expect(fetchInsightByShortId).toHaveBeenCalledWith(+ expect.anything(),+ "abc123",+ { dateRange: undefined, variables: { product: "surveys" } },+ );+ });++ // The API drops an override whose code_name matches nothing on the insight, and+ // ignores overrides entirely under sharing-token auth — both silently, leaving the+ // insight's own defaults to compute numbers that look real. Rendering another+ // product's revenue as this product's is worse than showing an error, so a+ // variable that didn't land has to reject.+ it.each([+ {+ name: "the insight has no such variable",+ resolvedVariables: { month: "2026-07-01" },+ expectedError: 'has no SQL variable "product"',+ },+ {+ name: "the override was ignored and the saved default came back",+ resolvedVariables: { product: "session_replay" },+ expectedError: "was not applied",+ },+ ])("rejects when $name", async ({ resolvedVariables, expectedError }) => {+ fetchInsightByShortId.mockResolvedValue(insight({ resolvedVariables }));++ await expect(+ makeService().loadInsight({+ shortId: "abc123",+ variables: { product: "surveys" },+ }),+ ).rejects.toThrow(expectedError);+ });++ it("accepts a non-string variable value the server echoes back", async () => {+ fetchInsightByShortId.mockResolvedValue(+ insight({ resolvedVariables: { threshold: 500, tiers: ["a", "b"] } }),+ );++ await expect(+ makeService().loadInsight({+ shortId: "abc123",+ variables: { threshold: 500, tiers: ["a", "b"] },+ }),+ ).resolves.toBeDefined();+ });+it("rejects when the insight can't be found", async () => {fetchInsightByShortId.mockRejectedValue(new Error('Insight "nope" not found'),diff --git a/products/desktop/packages/core/src/canvas/canvasDataService.ts b/products/desktop/packages/core/src/canvas/canvasDataService.tsindex 6d8d864e11cb..319a02a1ce59 100644--- a/products/desktop/packages/core/src/canvas/canvasDataService.ts+++ b/products/desktop/packages/core/src/canvas/canvasDataService.ts@@ -47,6 +47,43 @@ function boundedResult(result: CanvasDataResult): CanvasDataResult {return result;}+// Compare a requested SQL-variable value against the one the server resolved.+// Values round-trip verbatim, so structural equality is enough; `undefined`+// normalizes to null because that's how it serializes over the wire.+function sameVariableValue(a: unknown, b: unknown): boolean {+ return JSON.stringify(a ?? null) === JSON.stringify(b ?? null);+}++/**+ * Fail loudly when a requested SQL variable didn't actually take effect.+ *+ * The insights API drops an override whose `code_name` matches no variable on the+ * insight, and ignores overrides wholesale under sharing-token auth. Both are+ * SILENT: the insight then computes from its own saved defaults and returns numbers+ * that look real. On a per-product board that means every product rendering the+ * insight's default product — precisely the wrong-but-plausible data a canvas must+ * never show. So verify against what the server says it used, and refuse otherwise.+ */+function assertVariablesApplied(+ requested: Record<string, unknown> | undefined,+ resolved: Record<string, unknown>,+ shortId: string,+): void {+ for (const [codeName, requestedValue] of Object.entries(requested ?? {})) {+ if (!(codeName in resolved)) {+ const known = Object.keys(resolved);+ throw new Error(+ `Insight "${shortId}" has no SQL variable "${codeName}" (it uses: ${known.length > 0 ? known.join(", ") : "none"})`,+ );+ }+ if (!sameVariableValue(resolved[codeName], requestedValue)) {+ throw new Error(+ `SQL variable "${codeName}" was not applied to insight "${shortId}" — it resolved to ${JSON.stringify(resolved[codeName])}, not ${JSON.stringify(requestedValue)}`,+ );+ }+ }+}+/*** The host-side data avenue behind a freeform canvas's `ph.query` shim.*@@ -112,13 +149,19 @@ export class CanvasDataService {// The preferred data avenue: load a SAVED insight by short id and return its// STORED result from the insights endpoint (not a fresh /query/ run). The- // canvas date picker's window rides along as the insight's date override.+ // canvas date picker's window rides along as the insight's date override, and+ // `variables` supplies the insight's SQL variables for this request.async loadInsight(input: CanvasLoadInsightInput): Promise<CanvasDataResult> {try {const insight = await fetchInsightByShortId(this.authService,input.shortId,- { dateRange: input.dateRange },+ { dateRange: input.dateRange, variables: input.variables },+ );+ assertVariablesApplied(+ input.variables,+ insight.resolvedVariables,+ input.shortId,);// Mirror the shape handling in `query`: a SQL insight returns rows (coerce a// bare scalar row to a 1-cell array); a trends-style insight returns SERIESdiff --git a/products/desktop/packages/core/src/canvas/canvasTemplates.ts b/products/desktop/packages/core/src/canvas/canvasTemplates.tsindex 23ccc010f344..ee5c04881485 100644--- a/products/desktop/packages/core/src/canvas/canvasTemplates.ts+++ b/products/desktop/packages/core/src/canvas/canvasTemplates.ts@@ -46,6 +46,9 @@ const FREEFORM_BASE = ["- `await ph.loadInsight(shortId, { dateRange })` resolves to `{ columns, results }` — the insight's STORED result, read from the insights endpoint (NOT a fresh query run). `shortId` is the saved insight's short id; `dateRange` (optional) is `{ date_from, date_to }` from your date picker. THE RESULT SHAPE DIFFERS by insight type, read it correctly or every value comes back 0:",' • A trends-style insight (Trends/Funnels/Retention/Paths/web-analytics) → `results` is an array of SERIES OBJECTS (NOT rows). Each series = `{ data: number[] (per interval), labels: string[], days: string[] (ISO), count: number (sum), aggregated_value: number (single-value total), label, compare_label?: "current"|"previous" }`. So a KPI total = `results[0].count` (or `.aggregated_value`); a line chart = `results[0].data` over `results[0].days`. With a compare period, find the prior series by `compare_label === "previous"` (do NOT assume index order). `columns` is empty here — ignore it.'," • A SQL insight → `{ columns: string[], results: rows[][] }` — each row an array of cell values in `columns` order; read `results[rowIndex][colIndex]`.",+ '- SQL VARIABLES — a saved SQL insight whose HogQL contains `{variables.something}` placeholders is driven per call: `await ph.loadInsight(shortId, { variables: { product: "surveys", month: "2026-07-01" } })`, keyed by the variable\'s code name (NOT its uuid). This is how ONE saved insight fills a whole board — the same per-product insight loaded once per product. Read the insight\'s variable code names off its query via the MCP tools (`insight-get`) first; the host REJECTS a variable the insight does not use rather than quietly falling back to its saved value, so pass only what that insight actually references.',+ " • A SQL variable is a SEPARATE axis from the date picker: if an insight takes its month/day from a `{variables.…}` placeholder, drive it through `variables` — `dateRange` will NEVER reach it. Check which of the two an insight uses before wiring the picker to it.",+ " • Reads are cached per (insight, dateRange, variables), so N products means N loads. Prefer ONE insight that returns every product as rows over the same insight loaded N times — fewer round trips, and you slice it client-side.",'- `await ph.query(arg)` is the SECONDARY/escape path (ad-hoc, NOT saved) — reach for it only when you genuinely cannot save an insight. `arg` is a typed query node `ph.query({ kind: "TrendsQuery", series: [...], dateRange: {...} })` (series-object result, as above) or an inline HogQL string `ph.query("SELECT …")` (rows result, as above). Same result shapes as ph.loadInsight; prefer ph.loadInsight.','- `ph.capture(event, properties?, distinctId?)` sends an analytics event to the project (fire-and-forget; returns a promise). Use this for click/interaction tracking — e.g. `ph.capture("button_clicked", { label })`. NEVER roll your own posthog client or fetch the capture endpoint yourself.','- `ph.openExternal(url)` asks the host to open an absolute `https://posthog.com` (or `*.posthog.com`) URL — anything else is blocked, so do NOT link to other sites. Call it only from a user interaction (e.g. a click handler); the host ignores opens while the canvas is not focused, so calling it on load/in effects does nothing. Sandboxed `target="_blank"` navigation is intentionally blocked.',diff --git a/products/desktop/packages/core/src/canvas/freeformSchemas.ts b/products/desktop/packages/core/src/canvas/freeformSchemas.tsindex 721f428fde23..d0425225e79d 100644--- a/products/desktop/packages/core/src/canvas/freeformSchemas.ts+++ b/products/desktop/packages/core/src/canvas/freeformSchemas.ts@@ -60,12 +60,23 @@ export type CanvasDataResult = z.infer<typeof canvasDataResultSchema>;// `dateRange` (the canvas date picker's window) re-scopes the insight for this// request via `filters_override`. The result is the same `{ columns, results }`// shape as `ph.query`.+//+// `variables` supplies per-request values for a SQL insight's HogQL variables (the+// `{variables.code_name}` placeholders), forwarded as `variables_override`. This is+// what lets ONE saved insight serve a whole board — a per-product revenue insight+// rendered once per product — instead of only ever resolving its saved defaults. A+// SQL variable is a SEPARATE axis from `dateRange`: an insight whose month comes+// from a `{variables.month}` placeholder is driven through `variables`, and no+// `dateRange` will ever reach it.// ---------------------------------------------------------------------------export const canvasLoadInsightInput = z.object({shortId: z.string().min(1).max(128),dateRange: z.object({ date_from: z.string().nullish(), date_to: z.string().nullish() }).optional(),+ // Keyed by the variable's `code_name`, not its uuid — the host resolves ids+ // server-side, so canvas code never carries a variable uuid.+ variables: z.record(z.string().min(1).max(128), z.unknown()).optional(),});export type CanvasLoadInsightInput = z.infer<typeof canvasLoadInsightInput>;diff --git a/products/desktop/packages/core/src/canvas/posthogApi.ts b/products/desktop/packages/core/src/canvas/posthogApi.tsindex 36679408e59f..036f8df34ce3 100644--- a/products/desktop/packages/core/src/canvas/posthogApi.ts+++ b/products/desktop/packages/core/src/canvas/posthogApi.ts@@ -90,6 +90,61 @@ export interface InsightFetchResult {columns: string[];/** The insight's precomputed `result` (series objects for trends, rows for SQL). */results: unknown[];+ /**+ * The SQL-variable values the server actually resolved this request with, keyed by+ * `code_name`. Read off the returned query (which the API rebuilds with the+ * overrides applied), so it reflects what the numbers were computed from — not+ * what we asked for. Empty for an insight with no variables.+ */+ resolvedVariables: Record<string, unknown>;+}++/** A query node as far as this module cares: a kind, maybe a wrapped source, maybe variables. */+interface InsightQueryNode {+ kind?: string;+ source?: InsightQueryNode | null;+ variables?: Record<string, { code_name?: string; value?: unknown }> | null;+}++// SQL variables live on the HogQLQuery node, which sits under one or more wrapper+// nodes (DataVisualizationNode, InsightVizNode) — the same `source` chain the API+// walks when it applies the overrides. Bounded rather than blindly recursive: a+// malformed/cyclic node from the wire shouldn't spin here.+const MAX_QUERY_NODE_DEPTH = 5;++function readResolvedVariables(+ query: InsightQueryNode | null | undefined,+): Record<string, unknown> {+ let node = query;+ for (let depth = 0; node && depth < MAX_QUERY_NODE_DEPTH; depth++) {+ if (node.variables) {+ // Re-key by code_name: the API keys these by variable uuid, but code_name is+ // what the insight's SQL references and what callers pass.+ return Object.fromEntries(+ Object.values(node.variables)+ .filter((variable) => typeof variable?.code_name === "string")+ .map((variable) => [variable.code_name as string, variable.value]),+ );+ }+ node = node.source;+ }+ return {};+}++// `variables_override` wants full HogQLVariable-shaped entries. The server re-keys+// them by matching `code_name` against the project's variables and fills in the real+// uuid, so a code_name-keyed map is enough — no uuid lookup round-trip needed here.+// An entry WITHOUT `code_name` is dropped server-side without comment, hence the+// explicit field rather than relying on the map key.+function buildVariablesOverride(+ variables: Record<string, unknown>,+): Record<string, { code_name: string; value: unknown }> {+ return Object.fromEntries(+ Object.entries(variables).map(([codeName, value]) => [+ codeName,+ { code_name: codeName, value },+ ]),+ );}/**@@ -106,11 +161,20 @@ export interface InsightFetchResult {* if the saved insight's window can't be overridden (e.g. a raw-SQL insight) it* simply returns its saved window. Throws on no selected project, an HTTP* failure, or an unknown short id.+ *+ * `variables` overrides the insight's HogQL variables for this request via+ * `variables_override` — keyed by `code_name`, values applied to both the returned+ * query and the result it's computed from. The values the server actually landed on+ * come back as `resolvedVariables`; callers must compare, because the API drops+ * unmatched entries silently (see CanvasDataService.loadInsight).*/export async function fetchInsightByShortId(authService: AuthService,shortId: string,- opts?: { dateRange?: { date_from?: string | null; date_to?: string | null } },+ opts?: {+ dateRange?: { date_from?: string | null; date_to?: string | null };+ variables?: Record<string, unknown>;+ },): Promise<InsightFetchResult> {const { apiHost } = await authService.getValidAccessToken();const projectId = authService.getState().currentProjectId;@@ -125,6 +189,12 @@ export async function fetchInsightByShortId(if (opts?.dateRange) {params.set("filters_override", JSON.stringify(opts.dateRange));}+ if (opts?.variables && Object.keys(opts.variables).length > 0) {+ params.set(+ "variables_override",+ JSON.stringify(buildVariablesOverride(opts.variables)),+ );+ }const response = await authService.authenticatedFetch(fetch,@@ -137,7 +207,7 @@ export async function fetchInsightByShortId(const body = (await response.json()) as {results?: Array<{short_id?: string;- query?: { kind?: string } | null;+ query?: InsightQueryNode | null;columns?: string[] | null;result?: unknown;}>;@@ -152,6 +222,7 @@ export async function fetchInsightByShortId(queryKind: insight.query?.kind ?? null,columns: Array.isArray(insight.columns) ? insight.columns.map(String) : [],results: Array.isArray(insight.result) ? insight.result : [],+ resolvedVariables: readResolvedVariables(insight.query),};}diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.tsindex 81040af654b2..c950e10c374e 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.test.ts@@ -1,6 +1,13 @@import { assertCanvasCapability } from "@posthog/core/canvas/canvasCapabilities";import type { CanvasCapabilities } from "@posthog/shared";-import { describe, expect, it } from "vitest";+import { QueryClient } from "@tanstack/react-query";+import { describe, expect, it, vi } from "vitest";+import { handleFreeformDataRequest } from "./freeformDataBridge";++const loadInsight = vi.fn();+vi.mock("../hostClient", () => ({+ hostClient: () => ({ canvasData: { loadInsight: { mutate: loadInsight } } }),+}));const capabilities: CanvasCapabilities = {posthog: {@@ -43,3 +50,34 @@ describe("assertCanvasCapability", () => {).toThrow('Method "run" is not allowed');});});++describe("handleFreeformDataRequest", () => {+ // Reads are cached by their content, so `variables` has to be part of the key. If+ // it isn't, one insight rendered per product resolves every product from the first+ // product's cache entry — a whole board of identical numbers, no error anywhere.+ it("does not share a cached insight read across different SQL variables", async () => {+ const queryClient = new QueryClient();+ loadInsight.mockReset();+ loadInsight+ .mockResolvedValueOnce({ columns: ["mrr"], results: [[1]] })+ .mockResolvedValueOnce({ columns: ["mrr"], results: [[2]] });++ const read = (product: string) =>+ handleFreeformDataRequest(+ "loadInsight",+ { shortId: "abc123", variables: { product } },+ queryClient,+ );++ expect(await read("surveys")).toEqual({ columns: ["mrr"], results: [[1]] });+ expect(await read("session_replay")).toEqual({+ columns: ["mrr"],+ results: [[2]],+ });+ expect(loadInsight).toHaveBeenCalledTimes(2);++ // Same variables again still resolves from cache rather than re-querying.+ expect(await read("surveys")).toEqual({ columns: ["mrr"], results: [[1]] });+ expect(loadInsight).toHaveBeenCalledTimes(2);+ });+});diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.tsindex a14248ef65cd..118db8992ab4 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/freeformDataBridge.ts@@ -94,7 +94,14 @@ export async function handleFreeformDataRequest(if (!input?.shortId || typeof input.shortId !== "string") {throw new Error("ph.loadInsight(shortId) requires an insight short id");}- const args = { shortId: input.shortId, dateRange: input.dateRange };+ // `variables` is part of the cache key, not just the request: the same insight+ // loaded for two different products is two different results, and omitting it+ // here would serve the first product's numbers for every one of them.+ const args = {+ shortId: input.shortId,+ dateRange: input.dateRange,+ variables: input.variables,+ };return cachedRead(queryClient, "loadInsight", args, () =>hostClient().canvasData.loadInsight.mutate(args),);diff --git a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.tsindex a9842f9e7dd4..027288b8c95c 100644--- a/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts+++ b/products/desktop/packages/ui/src/features/canvas/freeform/sandboxRuntime.ts@@ -236,10 +236,18 @@ export function buildSandboxDocument(// render its STORED result from the insights endpoint (not a fresh /query/// run). Pass the date picker's window to re-scope it:// \`ph.loadInsight("AbC123", { dateRange: { date_from, date_to } })\`.+ // A SQL insight's \`{variables.x}\` placeholders are set per call, keyed by+ // code name: \`ph.loadInsight("AbC123", { variables: { product: "surveys" } })\`+ // — so one saved insight serves a whole board. The host REJECTS a variable the+ // insight doesn't use, rather than quietly falling back to its saved value.// Returns \`{ columns, results }\` — SAME shape as ph.query: a trends-style// insight returns SERIES OBJECTS, a SQL insight returns ROWS.loadInsight: (shortId, opts) =>- call("loadInsight", { shortId, dateRange: opts && opts.dateRange }),+ call("loadInsight", {+ shortId,+ dateRange: opts && opts.dateRange,+ variables: opts && opts.variables,+ }),// Run a query. Pass a TYPED query node (\`{ kind: "TrendsQuery", … }\`) for// UI-matching numbers (preferred), or an inline HogQL string (escape hatch).// Edit mode only; rejected by the host in view mode.