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.

chore(desktop): trim canvas data service comments (#98855)

Paul D'Ambra1d11b66ea9b0
diff --git a/products/desktop/packages/core/src/canvas/canvasDataService.ts b/products/desktop/packages/core/src/canvas/canvasDataService.ts
index 8c31a0be1b13..987bd8791a7c 100644
--- a/products/desktop/packages/core/src/canvas/canvasDataService.ts
+++ b/products/desktop/packages/core/src/canvas/canvasDataService.ts
@@ -21,26 +21,24 @@ import {
runQuery,
} from "./posthogApi";
-// Last-resort attribution if we can't resolve the signed-in user (and the
-// canvas didn't pass its own distinctId).
const FALLBACK_DISTINCT_ID = "freeform-canvas";
const MAX_CANVAS_RESULT_ROWS = 1_000;
const MAX_CANVAS_RESULT_BYTES = 2 * 1024 * 1024;
-// Floor between background recomputes of one stale query (see `revalidate`).
const REVALIDATE_MIN_INTERVAL_MS = 30_000;
const MAX_REVALIDATION_ENTRIES = 512;
const utf8Encoder = new TextEncoder();
-// True when the JSON's UTF-8 encoding exceeds the byte limit. UTF-8 is 1–3
-// bytes per UTF-16 code unit, so the string length bounds the byte count from
-// both sides — only payloads in the ambiguous band pay for a full encode.
function exceedsByteLimit(json: string): boolean {
if (json.length > MAX_CANVAS_RESULT_BYTES) return true;
if (json.length * 3 <= MAX_CANVAS_RESULT_BYTES) return false;
return utf8Encoder.encode(json).byteLength > MAX_CANVAS_RESULT_BYTES;
}
+function normalizeHogQLRows(results: unknown[]): unknown[] {
+ return results.map((result) => (Array.isArray(result) ? result : [result]));
+}
+
function boundedResult(result: CanvasDataResult): CanvasDataResult {
if (
result.results.length > MAX_CANVAS_RESULT_ROWS ||
@@ -51,23 +49,11 @@ 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.
- */
+// Reject ignored overrides because the insight can return plausible saved defaults.
function assertVariablesApplied(
requested: Record<string, unknown> | undefined,
resolved: Record<string, unknown>,
@@ -88,30 +74,11 @@ function assertVariablesApplied(
}
}
-/**
- * The host-side data avenue behind a freeform canvas's `ph.query` shim.
- *
- * Runs HogQL through PostHog's cached query runner — the SAME avenue insights
- * use, so caching and cold-boot are handled for us — by passing
- * `refresh: "blocking"` (return a fresh cached result if one exists, else
- * compute synchronously). The PostHog token is injected here via
- * `authenticatedFetch`; it never crosses into the iframe.
- *
- * Edit-mode only for now (inline HogQL). The published/view tier (Phase 3) will
- * reject inline HogQL and require a named, server-stored insight referenced by
- * `ph.run(name, params)`, validated against a per-canvas allowlist.
- */
@injectable()
export class CanvasDataService {
private readonly log: ScopedLogger;
- // The public capture key (phc_…) per project id. Keyed by project so switching
- // projects in the same session doesn't reuse the previous project's key (this
- // is a singleton service).
private readonly projectTokens = new Map<number, string>();
- // The signed-in user's distinct_id, the default attribution in edit mode.
- // Per-user (not per-project), so a single cached value is correct.
private userDistinctId: string | undefined;
- // Epoch ms of each query's last background-recompute kickoff (see `revalidate`).
private readonly revalidatedAt = new Map<string, number>();
constructor(
@@ -125,27 +92,16 @@ export class CanvasDataService {
async query(input: CanvasDataQueryInput): Promise<CanvasDataResult> {
try {
- // A typed query node (TrendsQuery/etc.) runs as-is so the numbers match the
- // PostHog UI; an inline HogQL string is the escape hatch.
const isTyped = input.query != null;
const node = isTyped
? (input.query as Record<string, unknown>)
: { kind: "HogQLQuery", query: input.hogql as string };
- // Shape handling: HogQL returns rows (normalise a bare scalar row to a
- // 1-cell array); typed nodes return SERIES OBJECTS, passed through
- // untouched (wrapping them in arrays is what made every value read as 0).
+ // Typed results are series objects. Wrapping them makes their values read as zero.
const shaped = (results: unknown[]): unknown[] =>
- isTyped ? results : results.map((r) => (Array.isArray(r) ? r : [r]));
+ isTyped ? results : normalizeHogQLRows(results);
- // A canvas that declared a refresh window is a live surface: it re-reads
- // on its own cadence, so it gets dashboard semantics. Any cached result
- // paints immediately, and one older than the window is revalidated in the
- // background so the NEXT read is fresh. A canvas with no window keeps the
- // one-shot semantics: a fresh-enough cached result, else a blocking
- // compute.
if (input.refresh != null) {
- // The cache probe is an optimization; a transient failure on it must
- // not fail a read that the blocking path below could still serve.
+ // A failed cache probe must not block the query runner.
const cached = await readCachedQuery(this.authService, node).catch(
(err) => {
this.log.warn("Canvas cached-read probe failed", {
@@ -168,8 +124,6 @@ export class CanvasDataService {
});
}
}
- // Cache-first execution (the insights avenue): serve a fresh cached
- // result if present, otherwise compute it now.
const { columns, results } = await runQuery(this.authService, node, {
refresh: "blocking",
});
@@ -182,20 +136,13 @@ export class CanvasDataService {
}
}
- // Fire-and-forget background recompute of a stale cached result.
- // force_async recomputes unconditionally, so kickoffs are rate-limited per
- // query: a canvas polling faster than the compute finishes must not stack
- // ClickHouse runs behind it.
private revalidate(node: Record<string, unknown>): void {
const key = JSON.stringify(node);
const last = this.revalidatedAt.get(key);
if (last != null && Date.now() - last < REVALIDATE_MIN_INTERVAL_MS) return;
- // Delete first so a re-set refreshes the key's Map position and the size
- // cap below always evicts the least recently refreshed query.
+ // Re-insert the key so the size cap removes the least recently refreshed query.
this.revalidatedAt.delete(key);
this.revalidatedAt.set(key, Date.now());
- // The map only ever holds queries some canvas is actively re-reading;
- // still, cap it so a long session can't grow it without bound.
if (this.revalidatedAt.size > MAX_REVALIDATION_ENTRIES) {
const oldest = this.revalidatedAt.keys().next().value;
if (oldest !== undefined) this.revalidatedAt.delete(oldest);
@@ -209,10 +156,6 @@ 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, and
- // `variables` supplies the insight's SQL variables for this request.
async loadInsight(input: CanvasLoadInsightInput): Promise<CanvasDataResult> {
try {
const insight = await fetchInsightByShortId(
@@ -225,16 +168,10 @@ export class CanvasDataService {
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 SERIES
- // OBJECTS, which must pass through untouched (wrapping them reads every value
- // as 0).
const isRows = insight.queryKind === "HogQLQuery";
return boundedResult({
columns: insight.columns,
- results: isRows
- ? insight.results.map((r) => (Array.isArray(r) ? r : [r]))
- : insight.results,
+ results: isRows ? normalizeHogQLRows(insight.results) : insight.results,
});
} catch (err) {
this.log.warn("Canvas loadInsight failed", {
@@ -245,9 +182,6 @@ export class CanvasDataService {
}
}
- // The bootstrap config the iframe needs to run posthog-js (analytics +
- // session replay) itself: the public capture key + the signed-in user's
- // distinct_id. The private read token is never included.
async captureConfig(): Promise<CanvasCaptureConfig> {
const { apiHost } = await this.authService.getValidAccessToken();
const projectId = this.authService.getState().currentProjectId;
@@ -261,9 +195,6 @@ export class CanvasDataService {
return { apiHost, publicKey, distinctId };
}
- // Send an analytics event to the host's project using the PUBLIC project key.
- // This is the `ph.capture` avenue: the canvas never holds a key, the host
- // attaches the (safe-to-be-public) capture token and posts the event.
async capture(input: CanvasCaptureInput): Promise<CanvasCaptureResult> {
const { apiHost } = await this.authService.getValidAccessToken();
const projectId = this.authService.getState().currentProjectId;
@@ -272,9 +203,6 @@ export class CanvasDataService {
}
const apiKey = await this.getProjectToken(apiHost, projectId);
- // Attribution order: an explicit distinctId the canvas passed (e.g. a
- // per-visitor id once sharing exists) wins; otherwise the signed-in user
- // (edit mode); otherwise a stable fallback.
const distinctId =
input.distinctId ??
(await this.getUserDistinctId()) ??
@@ -288,7 +216,6 @@ export class CanvasDataService {
distinct_id: distinctId,
properties: {
...input.properties,
- // Mark provenance so these are easy to find/filter in the project.
$lib: "posthog-canvas",
},
}),
@@ -301,9 +228,6 @@ export class CanvasDataService {
return { ok: true };
}
- // The project's public capture key. Fetched from the authenticated project
- // endpoint (which the user can already read) and cached; capture itself uses
- // the public key, not the bearer token.
private async getProjectToken(
apiHost: string,
projectId: number,
@@ -323,8 +247,6 @@ export class CanvasDataService {
return data.api_token;
}
- // The signed-in user's distinct_id (so edit-mode captures attribute to "me" in
- // PostHog, not a placeholder). Cached; returns undefined if unavailable.
private async getUserDistinctId(): Promise<string | undefined> {
if (this.userDistinctId !== undefined) return this.userDistinctId;
const user = await fetchCurrentUser(this.authService);