: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
fix(desktop): serialize a cloud task snapshot once per run, not per subscriber (#96131)
Adam Leithae880d309f33
diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.tsindex 022e24d06ccd..69b5e17eb903 100644--- a/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts+++ b/products/desktop/packages/core/src/cloud-task/cloud-task-engine.ts@@ -754,7 +754,12 @@ export class CloudTaskEngine extends TypedEventEmitter<CloudTaskEvents> {key,subscribers: existing.subscriberCount,});- void this.emitCurrentSnapshot(key);+ // Until the first snapshot is out, the bootstrap in flight delivers it to+ // every subscriber. Replaying here would fetch and emit the transcript a+ // second time, and each emit is serialized once per subscription.+ if (existing.hasEmittedSnapshot) {+ void this.emitCurrentSnapshot(key);+ }return;}diff --git a/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts b/products/desktop/packages/core/src/cloud-task/cloud-task.test.tsindex 4e08e4e29ca3..ffa8f5eb044e 100644--- a/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts+++ b/products/desktop/packages/core/src/cloud-task/cloud-task.test.ts@@ -1080,6 +1080,72 @@ describe("CloudTaskEngine", () => {await waitFor(() => getWatcherEmittedEntryCount() === 0);});+ it("does not replay a snapshot for a subscriber that joins while the watcher is still bootstrapping", async () => {+ const updates: unknown[] = [];+ service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));++ const historicalEntry = {+ type: "notification",+ timestamp: "2026-01-01T00:00:00Z",+ notification: {+ jsonrpc: "2.0",+ method: "_posthog/console",+ params: { sessionId: "run-1", level: "info", message: "history" },+ },+ };++ mockNetFetch+ .mockResolvedValueOnce(+ createJsonResponse({+ id: "run-1",+ status: "in_progress",+ stage: "build",+ output: null,+ error_message: null,+ branch: "main",+ updated_at: "2026-01-01T00:00:00Z",+ }),+ )+ .mockResolvedValueOnce(+ createJsonResponse([historicalEntry], 200, { "X-Has-More": "false" }),+ );+ mockStreamFetch.mockResolvedValueOnce(createOpenSseResponse(""));++ const input = {+ taskId: "task-1",+ runId: "run-1",+ apiHost: "https://app.example.com",+ teamId: 2,+ };+ service.watch(input);+ service.watch(input);++ await waitFor(() =>+ updates.some(+ (update) => (update as { kind?: string }).kind === "snapshot",+ ),+ );+ await new Promise((resolve) => setTimeout(resolve, 50));++ const snapshots = updates.filter(+ (update) => (update as { kind?: string }).kind === "snapshot",+ );+ expect(snapshots).toHaveLength(1);+ // One history page for the bootstrap: the second watch fetched nothing.+ const historyFetches = mockNetFetch.mock.calls.filter(([input]) =>+ String(input instanceof Request ? input.url : input).includes(+ "/session_logs/",+ ),+ );+ expect(historyFetches).toHaveLength(1);++ // The second subscriber still counts, so one unwatch keeps the watcher up.+ service.unwatch("task-1", "run-1");+ const watchers = (service as unknown as { watchers: Map<string, unknown> })+ .watchers;+ expect(watchers.has("task-1:run-1")).toBe(true);+ });+it("ignores keepalive SSE events while keeping the stream open", async () => {const updates: unknown[] = [];service.on(CloudTaskEvent.Update, (payload) => updates.push(payload));diff --git a/products/desktop/packages/core/src/cloud-task/cloudTaskClient.ts b/products/desktop/packages/core/src/cloud-task/cloudTaskClient.tsindex 053cab9c0f63..b8e05c5d97fd 100644--- a/products/desktop/packages/core/src/cloud-task/cloudTaskClient.ts+++ b/products/desktop/packages/core/src/cloud-task/cloudTaskClient.ts@@ -13,6 +13,11 @@ export interface CloudTaskClient {}): Promise<void>;unwatch(taskId: string, runId: string): Promise<void>;retry(taskId: string, runId: string): Promise<void>;+ /**+ * Each subscriber calls `watch()` from `onStarted`; the host counts one+ * subscriber per watch and drops one when the subscription ends. A subscriber+ * that never watches would still drop a count another subscriber depends on.+ */subscribe(taskId: string,runId: string,diff --git a/products/desktop/packages/core/src/cloud-task/sharedCloudTaskSubscriptions.test.ts b/products/desktop/packages/core/src/cloud-task/sharedCloudTaskSubscriptions.test.tsnew file mode 100644index 000000000000..ae9d053f9f1c--- /dev/null+++ b/products/desktop/packages/core/src/cloud-task/sharedCloudTaskSubscriptions.test.ts@@ -0,0 +1,145 @@+import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";+import { describe, expect, it, vi } from "vitest";+import {+ type CloudTaskSubscriptionHandlers,+ SharedCloudTaskSubscriptions,+} from "./sharedCloudTaskSubscriptions";++type TransportHandlers = CloudTaskSubscriptionHandlers & {+ onComplete: () => void;+};++function createTransport() {+ const opened: Array<{+ taskId: string;+ runId: string;+ handlers: TransportHandlers;+ unsubscribe: ReturnType<typeof vi.fn>;+ }> = [];+ const unwatch = vi.fn(() => Promise.resolve());+ return {+ opened,+ unwatch,+ subscribe: vi.fn(+ (taskId: string, runId: string, handlers: TransportHandlers) => {+ const unsubscribe = vi.fn();+ opened.push({ taskId, runId, handlers, unsubscribe });+ return unsubscribe;+ },+ ),+ };+}++function createHandlers() {+ return {+ onUpdate: vi.fn(),+ onError: vi.fn(),+ onStarted: vi.fn(),+ };+}++const statusUpdate: CloudTaskUpdatePayload = {+ taskId: "task-1",+ runId: "run-1",+ kind: "status",+ status: "in_progress",+ stage: null,+ output: null,+ errorMessage: null,+ branch: null,+};++describe("SharedCloudTaskSubscriptions", () => {+ it("rides every subscriber of one run on a single transport subscription", () => {+ const transport = createTransport();+ const shared = new SharedCloudTaskSubscriptions(transport);+ const first = createHandlers();+ const second = createHandlers();+ const otherRun = createHandlers();++ shared.subscribe("task-1", "run-1", first);+ shared.subscribe("task-1", "run-1", second);+ shared.subscribe("task-1", "run-2", otherRun);++ expect(transport.subscribe).toHaveBeenCalledTimes(2);+ expect(transport.opened.map((entry) => entry.runId)).toEqual([+ "run-1",+ "run-2",+ ]);++ transport.opened[0].handlers.onStarted();+ transport.opened[0].handlers.onUpdate(statusUpdate);++ expect(first.onStarted).toHaveBeenCalledTimes(1);+ expect(second.onStarted).toHaveBeenCalledTimes(1);+ expect(first.onUpdate).toHaveBeenCalledWith(statusUpdate);+ expect(second.onUpdate).toHaveBeenCalledWith(statusUpdate);+ expect(otherRun.onStarted).not.toHaveBeenCalled();+ expect(otherRun.onUpdate).not.toHaveBeenCalled();+ });++ it("starts a late subscriber and balances its watch when it leaves before the others", async () => {+ const transport = createTransport();+ const shared = new SharedCloudTaskSubscriptions(transport);+ const first = createHandlers();+ const late = createHandlers();++ const unsubscribeFirst = shared.subscribe("task-1", "run-1", first);+ transport.opened[0].handlers.onStarted();++ const unsubscribeLate = shared.subscribe("task-1", "run-1", late);+ expect(late.onStarted).not.toHaveBeenCalled();+ await Promise.resolve();+ expect(late.onStarted).toHaveBeenCalledTimes(1);+ expect(transport.subscribe).toHaveBeenCalledTimes(1);++ unsubscribeLate();+ expect(transport.unwatch).toHaveBeenCalledWith("task-1", "run-1");+ expect(transport.opened[0].unsubscribe).not.toHaveBeenCalled();++ unsubscribeFirst();+ expect(transport.opened[0].unsubscribe).toHaveBeenCalledTimes(1);+ // The host unwatches the last subscriber itself when the subscription ends.+ expect(transport.unwatch).toHaveBeenCalledTimes(1);+ });++ it("does not unwatch for a subscriber that left before the transport started", () => {+ const transport = createTransport();+ const shared = new SharedCloudTaskSubscriptions(transport);+ const first = createHandlers();+ const second = createHandlers();++ shared.subscribe("task-1", "run-1", first);+ const unsubscribeSecond = shared.subscribe("task-1", "run-1", second);++ unsubscribeSecond();+ transport.opened[0].handlers.onStarted();++ expect(transport.unwatch).not.toHaveBeenCalled();+ expect(second.onStarted).not.toHaveBeenCalled();+ expect(first.onStarted).toHaveBeenCalledTimes(1);+ });++ it("reports a transport error to every subscriber and opens a fresh subscription afterwards", () => {+ const transport = createTransport();+ const shared = new SharedCloudTaskSubscriptions(transport);+ const first = createHandlers();+ const second = createHandlers();+ const error = new Error("stream closed");++ shared.subscribe("task-1", "run-1", first);+ shared.subscribe("task-1", "run-1", second);+ transport.opened[0].handlers.onError(error);++ expect(first.onError).toHaveBeenCalledWith(error);+ expect(second.onError).toHaveBeenCalledWith(error);++ const replacement = createHandlers();+ shared.subscribe("task-1", "run-1", replacement);+ expect(transport.subscribe).toHaveBeenCalledTimes(2);++ transport.opened[1].handlers.onUpdate(statusUpdate);+ expect(replacement.onUpdate).toHaveBeenCalledWith(statusUpdate);+ expect(first.onUpdate).not.toHaveBeenCalled();+ });+});diff --git a/products/desktop/packages/core/src/cloud-task/sharedCloudTaskSubscriptions.ts b/products/desktop/packages/core/src/cloud-task/sharedCloudTaskSubscriptions.tsnew file mode 100644index 000000000000..981644460ed5--- /dev/null+++ b/products/desktop/packages/core/src/cloud-task/sharedCloudTaskSubscriptions.ts@@ -0,0 +1,133 @@+import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";++export interface CloudTaskSubscriptionHandlers {+ onUpdate: (update: CloudTaskUpdatePayload) => void;+ onError: (error: unknown) => void;+ onStarted: () => void;+}++/**+ * The single host subscription a channel rides on. `onComplete` fires when the+ * host ends the stream without an error.+ */+export interface CloudTaskSubscriptionTransport {+ subscribe(+ taskId: string,+ runId: string,+ handlers: CloudTaskSubscriptionHandlers & { onComplete: () => void },+ ): () => void;+ unwatch(taskId: string, runId: string): Promise<void>;+}++interface Listener {+ handlers: CloudTaskSubscriptionHandlers;+ started: boolean;+}++interface Channel {+ listeners: Set<Listener>;+ started: boolean;+ unsubscribe: () => void;+}++function channelKey(taskId: string, runId: string): string {+ return `${taskId}:${runId}`;+}++/**+ * Fans one host subscription per task run out to every local subscriber.+ *+ * The host serializes each update once per subscription it holds, so N+ * subscribers to one run would cost N serializations of every transcript+ * snapshot. Sharing the subscription makes that one.+ *+ * Contract kept from the unshared client: each subscriber calls `watch()` from+ * `onStarted`, and the host unwatches once when the shared subscription ends.+ * A subscriber that leaves while others stay therefore unwatches explicitly,+ * so the host's subscriber count still returns to zero.+ */+export class SharedCloudTaskSubscriptions {+ private readonly channels = new Map<string, Channel>();++ constructor(private readonly transport: CloudTaskSubscriptionTransport) {}++ subscribe(+ taskId: string,+ runId: string,+ handlers: CloudTaskSubscriptionHandlers,+ ): () => void {+ const key = channelKey(taskId, runId);+ const channel = this.channels.get(key) ?? this.open(key, taskId, runId);+ const listener: Listener = { handlers, started: false };+ channel.listeners.add(listener);++ if (channel.started) {+ // A late subscriber gets the same start signal the others got, after+ // `subscribe` has returned, as the transport would deliver it.+ queueMicrotask(() => {+ if (channel.listeners.has(listener) && !listener.started) {+ listener.started = true;+ handlers.onStarted();+ }+ });+ }++ return () => {+ if (!channel.listeners.delete(listener)) {+ return;+ }+ if (channel.listeners.size === 0) {+ if (this.channels.get(key) === channel) {+ this.channels.delete(key);+ }+ channel.unsubscribe();+ return;+ }+ if (listener.started) {+ void this.transport.unwatch(taskId, runId).catch(() => {});+ }+ };+ }++ private open(key: string, taskId: string, runId: string): Channel {+ const channel: Channel = {+ listeners: new Set(),+ started: false,+ unsubscribe: () => {},+ };+ this.channels.set(key, channel);++ const drop = (): void => {+ if (this.channels.get(key) === channel) {+ this.channels.delete(key);+ }+ };++ channel.unsubscribe = this.transport.subscribe(taskId, runId, {+ onStarted: () => {+ channel.started = true;+ for (const listener of [...channel.listeners]) {+ if (listener.started) continue;+ listener.started = true;+ listener.handlers.onStarted();+ }+ },+ onUpdate: (update) => {+ for (const listener of [...channel.listeners]) {+ listener.handlers.onUpdate(update);+ }+ },+ onError: (error) => {+ // The host subscription is dead; the next subscriber opens a new one.+ // Existing listeners keep their own recovery, as they did unshared.+ drop();+ for (const listener of [...channel.listeners]) {+ listener.handlers.onError(error);+ }+ },+ onComplete: drop,+ });++ return channel;+ }+}diff --git a/products/desktop/packages/host-router/src/cloud-task-client.ts b/products/desktop/packages/host-router/src/cloud-task-client.tsindex 8476ba818bec..93af287b17ec 100644--- a/products/desktop/packages/host-router/src/cloud-task-client.ts+++ b/products/desktop/packages/host-router/src/cloud-task-client.ts@@ -1,14 +1,33 @@import type { CloudTaskClient } from "@posthog/core/cloud-task/cloudTaskClient";import type { SendCommandInput } from "@posthog/core/cloud-task/schemas";+import { SharedCloudTaskSubscriptions } from "@posthog/core/cloud-task/sharedCloudTaskSubscriptions";import type { CloudTaskUpdatePayload } from "@posthog/shared/domain-types";import { inject, injectable } from "inversify";import { HOST_TRPC_CLIENT, type HostTrpcClient } from "./client";@injectable()export class TrpcCloudTaskClient implements CloudTaskClient {+ private readonly subscriptions: SharedCloudTaskSubscriptions;+constructor(@inject(HOST_TRPC_CLIENT) private readonly client: HostTrpcClient,- ) {}+ ) {+ this.subscriptions = new SharedCloudTaskSubscriptions({+ subscribe: (taskId, runId, handlers) => {+ const subscription = this.client.cloudTask.onUpdate.subscribe(+ { taskId, runId },+ {+ onData: handlers.onUpdate,+ onError: handlers.onError,+ onStarted: handlers.onStarted,+ onComplete: handlers.onComplete,+ },+ );+ return () => subscription.unsubscribe();+ },+ unwatch: (taskId, runId) => this.unwatch(taskId, runId),+ });+ }getContext(): Promise<{ apiHost: string; teamId: number } | null> {return this.client.cloudTask.context.query();@@ -38,11 +57,11 @@ export class TrpcCloudTaskClient implements CloudTaskClient {onError: (error: unknown) => void,onStarted: () => void,): () => void {- const subscription = this.client.cloudTask.onUpdate.subscribe(- { taskId, runId },- { onData: onUpdate, onError, onStarted },- );- return () => subscription.unsubscribe();+ return this.subscriptions.subscribe(taskId, runId, {+ onUpdate,+ onError,+ onStarted,+ });}sendCommand(input: SendCommandInput) {